Skip to content

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

TypeScript

Comparison evaluations and quality assessment (#77)

Cindy Zhang2184216d0ffb
diff --git a/internal/vibe-tests/.gitignore b/internal/vibe-tests/.gitignore
index e409d44519..264110b849 100644
--- a/internal/vibe-tests/.gitignore
+++ b/internal/vibe-tests/.gitignore
@@ -1,3 +1,10 @@
# XDS agent docs (generated)
.xds-docs/
AGENTS.md
+
+# Baseline comparison docs (generated)
+.baseline-docs/
+AGENTS.baseline.md
+
+# Test results (generated)
+results/
diff --git a/internal/vibe-tests/a11y-manifests/baseline.json b/internal/vibe-tests/a11y-manifests/baseline.json
new file mode 100644
index 0000000000..3f641dab67
--- /dev/null
+++ b/internal/vibe-tests/a11y-manifests/baseline.json
@@ -0,0 +1,380 @@
+{
+ "source": "https://www.radix-ui.com/primitives/docs/overview/accessibility",
+ "generatedAt": "2026-02-05T18:03:04.623Z",
+ "version": "1.0.0",
+ "components": {
+ "Button": {
+ "component": "Button",
+ "builtIn": [
+ "Native button element with proper role",
+ "Keyboard activation (Enter/Space)",
+ "Focus management"
+ ],
+ "keyboard": [
+ "Enter/Space to activate"
+ ],
+ "developerMust": [
+ "Provide aria-label for icon-only buttons",
+ "Use aria-pressed for toggle buttons",
+ "Use aria-expanded for buttons that control expandable content"
+ ],
+ "notes": [
+ "Based on native <button> element"
+ ]
+ },
+ "Dialog": {
+ "component": "Dialog",
+ "builtIn": [
+ "Focus trap - focus stays within dialog",
+ "Escape key closes dialog",
+ "aria-modal=\"true\" on dialog",
+ "aria-labelledby pointing to title",
+ "aria-describedby pointing to description",
+ "Returns focus to trigger on close",
+ "Scrolling blocked on body when open"
+ ],
+ "keyboard": [
+ "Escape to close",
+ "Tab/Shift+Tab to navigate within"
+ ],
+ "developerMust": [
+ "Provide DialogTitle for aria-labelledby",
+ "Provide DialogDescription for aria-describedby (or use aria-describedby={undefined})"
+ ],
+ "notes": [
+ "WAI-ARIA Dialog pattern"
+ ]
+ },
+ "DropdownMenu": {
+ "component": "DropdownMenu",
+ "builtIn": [
+ "role=\"menu\" on content",
+ "role=\"menuitem\" on items",
+ "Arrow key navigation",
+ "Typeahead to jump to items",
+ "Focus returns to trigger on close",
+ "Escape closes menu",
+ "Submenu support with proper aria-haspopup"
+ ],
+ "keyboard": [
+ "Arrow Down/Up to navigate",
+ "Enter/Space to select",
+ "Escape to close",
+ "Arrow Right/Left for submenus",
+ "A-Z for typeahead"
+ ],
+ "developerMust": [],
+ "notes": [
+ "WAI-ARIA Menu pattern"
+ ]
+ },
+ "Select": {
+ "component": "Select",
+ "builtIn": [
+ "role=\"combobox\" on trigger",
+ "role=\"listbox\" on content",
+ "role=\"option\" on items",
+ "aria-expanded on trigger",
+ "aria-activedescendant for focus",
+ "Arrow key navigation",
+ "Typeahead support"
+ ],
+ "keyboard": [
+ "Arrow Down/Up to navigate",
+ "Enter/Space to select",
+ "Escape to close",
+ "A-Z for typeahead",
+ "Home/End to jump"
+ ],
+ "developerMust": [
+ "Provide accessible label (Label component or aria-label)"
+ ],
+ "notes": [
+ "WAI-ARIA Combobox pattern (Select-Only)"
+ ]
+ },
+ "Checkbox": {
+ "component": "Checkbox",
+ "builtIn": [
+ "role=\"checkbox\"",
+ "aria-checked state",
+ "Keyboard activation (Space)",
+ "Supports indeterminate state"
+ ],
+ "keyboard": [
+ "Space to toggle"
+ ],
+ "developerMust": [
+ "Provide accessible label (Label component or aria-label)"
+ ],
+ "notes": [
+ "WAI-ARIA Checkbox pattern"
+ ]
+ },
+ "Switch": {
+ "component": "Switch",
+ "builtIn": [
+ "role=\"switch\"",
+ "aria-checked state",
+ "Keyboard activation (Space)"
+ ],
+ "keyboard": [
+ "Space to toggle"
+ ],
+ "developerMust": [
+ "Provide accessible label (Label component or aria-label)"
+ ],
+ "notes": [
+ "WAI-ARIA Switch pattern"
+ ]
+ },
+ "Tabs": {
+ "component": "Tabs",
+ "builtIn": [
+ "role=\"tablist\" on list",
+ "role=\"tab\" on triggers",
+ "role=\"tabpanel\" on content",
+ "aria-selected on active tab",
+ "Arrow key navigation between tabs",
+ "Automatic activation on focus (or manual mode)"
+ ],
+ "keyboard": [
+ "Arrow Left/Right to navigate tabs",
+ "Home/End to jump to first/last tab",
+ "Tab to move into panel"
+ ],
+ "developerMust": [],
+ "notes": [
+ "WAI-ARIA Tabs pattern"
+ ]
+ },
+ "Tooltip": {
+ "component": "Tooltip",
+ "builtIn": [
+ "aria-describedby linking trigger to content",
+ "Escape to dismiss",
+ "Delay before showing (configurable)",
+ "Touch-friendly behavior"
+ ],
+ "keyboard": [
+ "Escape to dismiss"
+ ],
+ "developerMust": [
+ "Ensure trigger is focusable (use asChild with focusable element)"
+ ],
+ "notes": [
+ "Content should be supplementary, not essential"
+ ]
+ },
+ "Popover": {
+ "component": "Popover",
+ "builtIn": [
+ "Focus management",
+ "Escape to close",
+ "Click outside to close",
+ "aria-haspopup on trigger"
+ ],
+ "keyboard": [
+ "Escape to close",
+ "Tab to navigate within"
+ ],
+ "developerMust": [
+ "Manage focus appropriately within popover content"
+ ],
+ "notes": [
+ "Non-modal by default - focus is not trapped"
+ ]
+ },
+ "AlertDialog": {
+ "component": "AlertDialog",
+ "builtIn": [
+ "Focus trap",
+ "aria-modal=\"true\"",
+ "role=\"alertdialog\"",
+ "aria-labelledby pointing to title",
+ "aria-describedby pointing to description",
+ "Escape is disabled by default (requires explicit action)"
+ ],
+ "keyboard": [
+ "Tab/Shift+Tab to navigate within"
+ ],
+ "developerMust": [
+ "Provide AlertDialogTitle",
+ "Provide AlertDialogDescription",
+ "Include at least one focusable action button"
+ ],
+ "notes": [
+ "WAI-ARIA AlertDialog pattern - for important interruptions"
+ ]
+ },
+ "Progress": {
+ "component": "Progress",
+ "builtIn": [
+ "role=\"progressbar\"",
+ "aria-valuenow",
+ "aria-valuemin",
+ "aria-valuemax"
+ ],
+ "keyboard": [],
+ "developerMust": [
+ "Provide aria-label or aria-labelledby for context"
+ ],
+ "notes": [
+ "Use aria-valuetext for non-percentage values"
+ ]
+ },
+ "Slider": {
+ "component": "Slider",
+ "builtIn": [
+ "role=\"slider\"",
+ "aria-valuenow, aria-valuemin, aria-valuemax",
+ "Arrow key adjustment",
+ "Home/End for min/max",
+ "Page Up/Down for larger steps"
+ ],
+ "keyboard": [
+ "Arrow Left/Down to decrease",
+ "Arrow Right/Up to increase",
+ "Home for minimum",
+ "End for maximum",
+ "Page Up/Down for larger steps"
+ ],
+ "developerMust": [
+ "Provide aria-label for context"
+ ],
+ "notes": [
+ "WAI-ARIA Slider pattern"
+ ]
+ },
+ "Accordion": {
+ "component": "Accordion",
+ "builtIn": [
+ "role=\"region\" on panels (when expanded)",
+ "aria-expanded on triggers",
+ "aria-controls linking trigger to panel",
+ "Arrow key navigation between triggers"
+ ],
+ "keyboard": [
+ "Enter/Space to toggle",
+ "Arrow Down/Up to navigate",
+ "Home/End to jump"
+ ],
+ "developerMust": [],
+ "notes": [
+ "WAI-ARIA Accordion pattern"
+ ]
+ },
+ "RadioGroup": {
+ "component": "RadioGroup",
+ "builtIn": [
+ "role=\"radiogroup\"",
+ "role=\"radio\" on items",
+ "aria-checked state",
+ "Arrow key navigation",
+ "Roving tabindex"
+ ],
+ "keyboard": [
+ "Arrow keys to navigate and select",
+ "Tab to enter/leave group"
+ ],
+ "developerMust": [
+ "Provide aria-label or aria-labelledby on group"
+ ],
+ "notes": [
+ "WAI-ARIA Radio Group pattern"
+ ]
+ },
+ "Label": {
+ "component": "Label",
+ "builtIn": [
+ "Native label element",
+ "Click on label focuses associated control",
+ "Proper htmlFor association"
+ ],
+ "keyboard": [],
+ "developerMust": [],
+ "notes": [
+ "Always use with form controls"
+ ]
+ },
+ "Input": {
+ "component": "Input",
+ "builtIn": [
+ "Native input element"
+ ],
+ "keyboard": [],
+ "developerMust": [
+ "Provide accessible label (Label component, aria-label, or aria-labelledby)",
+ "Use aria-describedby for error/help text",
+ "Set aria-invalid for error states"
+ ],
+ "notes": [
+ "shadcn Input is a styled native input"
+ ]
+ },
+ "Card": {
+ "component": "Card",
+ "builtIn": [],
+ "keyboard": [],
+ "developerMust": [
+ "If clickable, use button or link element, not onClick on div",
+ "Provide appropriate role if interactive"
+ ],
+ "notes": [
+ "Card is purely visual - has no semantic meaning"
+ ]
+ },
+ "Badge": {
+ "component": "Badge",
+ "builtIn": [],
+ "keyboard": [],
+ "developerMust": [
+ "Provide context via aria-label or surrounding text",
+ "For status badges, consider aria-live for dynamic updates"
+ ],
+ "notes": [
+ "Badge is purely visual - has no semantic meaning"
+ ]
+ },
+ "Avatar": {
+ "component": "Avatar",
+ "builtIn": [],
+ "keyboard": [],
+ "developerMust": [
+ "Provide alt text on AvatarImage",
+ "AvatarFallback provides fallback for screen readers"
+ ],
+ "notes": [
+ "Decorative avatars should have empty alt=\"\""
+ ]
+ },
+ "Skeleton": {
+ "component": "Skeleton",
+ "builtIn": [],
+ "keyboard": [],
+ "developerMust": [
+ "Provide aria-busy=\"true\" on parent container",
+ "Consider aria-live region for loading announcements"
+ ],
+ "notes": [
+ "Skeleton is decorative - loading state should be announced separately"
+ ]
+ },
+ "Table": {
+ "component": "Table",
+ "builtIn": [
+ "Native table element with proper structure",
+ "th elements for headers",
+ "Proper table semantics"
+ ],
+ "keyboard": [],
+ "developerMust": [
+ "Use TableCaption for table description",
+ "Use scope=\"col\" or scope=\"row\" on headers"
+ ],
+ "notes": [
+ "Use native table semantics, avoid role=\"presentation\""
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/internal/vibe-tests/a11y-manifests/baseline.md b/internal/vibe-tests/a11y-manifests/baseline.md
new file mode 100644
index 0000000000..317270299f
--- /dev/null
+++ b/internal/vibe-tests/a11y-manifests/baseline.md
@@ -0,0 +1,408 @@
+# Baseline (Radix/shadcn) Accessibility Manifest
+
+**Source:** https://www.radix-ui.com/primitives/docs/overview/accessibility
+**Generated:** 2026-02-05T18:03:04.623Z
+
+## Button
+
+**Built-in accessibility:**
+
+- Native button element with proper role
+- Keyboard activation (Enter/Space)
+- Focus management
+
+**Keyboard:**
+
+- Enter/Space to activate
+
+**Developer must provide:**
+
+- Provide aria-label for icon-only buttons
+- Use aria-pressed for toggle buttons
+- Use aria-expanded for buttons that control expandable content
+
+**Notes:**
+
+- Based on native <button> element
+
+## Dialog
+
+**Built-in accessibility:**
+
+- Focus trap - focus stays within dialog
+- Escape key closes dialog
+- aria-modal="true" on dialog
+- aria-labelledby pointing to title
+- aria-describedby pointing to description
+- Returns focus to trigger on close
+- Scrolling blocked on body when open
+
+**Keyboard:**
+
+- Escape to close
+- Tab/Shift+Tab to navigate within
+
+**Developer must provide:**
+
+- Provide DialogTitle for aria-labelledby
+- Provide DialogDescription for aria-describedby (or use aria-describedby={undefined})
+
+**Notes:**
+
+- WAI-ARIA Dialog pattern
+
+## DropdownMenu
+
+**Built-in accessibility:**
+
+- role="menu" on content
+- role="menuitem" on items
+- Arrow key navigation
+- Typeahead to jump to items
+- Focus returns to trigger on close
+- Escape closes menu
+- Submenu support with proper aria-haspopup
+
+**Keyboard:**
+
+- Arrow Down/Up to navigate
+- Enter/Space to select
+- Escape to close
+- Arrow Right/Left for submenus
+- A-Z for typeahead
+
+**Notes:**
+
+- WAI-ARIA Menu pattern
+
+## Select
+
+**Built-in accessibility:**
+
+- role="combobox" on trigger
+- role="listbox" on content
+- role="option" on items
+- aria-expanded on trigger
+- aria-activedescendant for focus
+- Arrow key navigation
+- Typeahead support
+
+**Keyboard:**
+
+- Arrow Down/Up to navigate
+- Enter/Space to select
+- Escape to close
+- A-Z for typeahead
+- Home/End to jump
+
+**Developer must provide:**
+
+- Provide accessible label (Label component or aria-label)
+
+**Notes:**
+
+- WAI-ARIA Combobox pattern (Select-Only)
+
+## Checkbox
+
+**Built-in accessibility:**
+
+- role="checkbox"
+- aria-checked state
+- Keyboard activation (Space)
+- Supports indeterminate state
+
+**Keyboard:**
+
+- Space to toggle
+
+**Developer must provide:**
+
+- Provide accessible label (Label component or aria-label)
+
+**Notes:**
+
+- WAI-ARIA Checkbox pattern
+
+## Switch
+
+**Built-in accessibility:**
+
+- role="switch"
+- aria-checked state
+- Keyboard activation (Space)
+
+**Keyboard:**
+
+- Space to toggle
+
+**Developer must provide:**
+
+- Provide accessible label (Label component or aria-label)
+
+**Notes:**
+
+- WAI-ARIA Switch pattern
+
+## Tabs
+
+**Built-in accessibility:**
+
+- role="tablist" on list
+- role="tab" on triggers
+- role="tabpanel" on content
+- aria-selected on active tab
+- Arrow key navigation between tabs
+- Automatic activation on focus (or manual mode)
+
+**Keyboard:**
+
+- Arrow Left/Right to navigate tabs
+- Home/End to jump to first/last tab
+- Tab to move into panel
+
+**Notes:**
+
+- WAI-ARIA Tabs pattern
+
+## Tooltip
+
+**Built-in accessibility:**
+
+- aria-describedby linking trigger to content
+- Escape to dismiss
+- Delay before showing (configurable)
+- Touch-friendly behavior
+
+**Keyboard:**
+
+- Escape to dismiss
+
+**Developer must provide:**
+
+- Ensure trigger is focusable (use asChild with focusable element)
+
+**Notes:**
+
+- Content should be supplementary, not essential
+
+## Popover
+
+**Built-in accessibility:**
+
+- Focus management
+- Escape to close
+- Click outside to close
+- aria-haspopup on trigger
+
+**Keyboard:**
+
+- Escape to close
+- Tab to navigate within
+
+**Developer must provide:**
+
+- Manage focus appropriately within popover content
+
+**Notes:**
+
+- Non-modal by default - focus is not trapped
+
+## AlertDialog
+
+**Built-in accessibility:**
+
+- Focus trap
+- aria-modal="true"
+- role="alertdialog"
+- aria-labelledby pointing to title
+- aria-describedby pointing to description
+- Escape is disabled by default (requires explicit action)
+
+**Keyboard:**
+
+- Tab/Shift+Tab to navigate within
+
+**Developer must provide:**
+
+- Provide AlertDialogTitle
+- Provide AlertDialogDescription
+- Include at least one focusable action button
+
+**Notes:**
+
+- WAI-ARIA AlertDialog pattern - for important interruptions
+
+## Progress
+
+**Built-in accessibility:**
+
+- role="progressbar"
+- aria-valuenow
+- aria-valuemin
+- aria-valuemax
+
+**Developer must provide:**
+
+- Provide aria-label or aria-labelledby for context
+
+**Notes:**
+
+- Use aria-valuetext for non-percentage values
+
+## Slider
+
+**Built-in accessibility:**
+
+- role="slider"
+- aria-valuenow, aria-valuemin, aria-valuemax
+- Arrow key adjustment
+- Home/End for min/max
+- Page Up/Down for larger steps
+
+**Keyboard:**
+
+- Arrow Left/Down to decrease
+- Arrow Right/Up to increase
+- Home for minimum
+- End for maximum
+- Page Up/Down for larger steps
+
+**Developer must provide:**
+
+- Provide aria-label for context
+
+**Notes:**
+
+- WAI-ARIA Slider pattern
+
+## Accordion
+
+**Built-in accessibility:**
+
+- role="region" on panels (when expanded)
+- aria-expanded on triggers
+- aria-controls linking trigger to panel
+- Arrow key navigation between triggers
+
+**Keyboard:**
+
+- Enter/Space to toggle
+- Arrow Down/Up to navigate
+- Home/End to jump
+
+**Notes:**
+
+- WAI-ARIA Accordion pattern
+
+## RadioGroup
+
+**Built-in accessibility:**
+
+- role="radiogroup"
+- role="radio" on items
+- aria-checked state
+- Arrow key navigation
+- Roving tabindex
+
+**Keyboard:**
+
+- Arrow keys to navigate and select
+- Tab to enter/leave group
+
+**Developer must provide:**
+
+- Provide aria-label or aria-labelledby on group
+
+**Notes:**
+
+- WAI-ARIA Radio Group pattern
+
+## Label
+
+**Built-in accessibility:**
+
+- Native label element
+- Click on label focuses associated control
+- Proper htmlFor association
+
+**Notes:**
+
+- Always use with form controls
+
+## Input
+
+**Built-in accessibility:**
+
+- Native input element
+
+**Developer must provide:**
+
+- Provide accessible label (Label component, aria-label, or aria-labelledby)
+- Use aria-describedby for error/help text
+- Set aria-invalid for error states
+
+**Notes:**
+
+- shadcn Input is a styled native input
+
+## Card
+
+**Developer must provide:**
+
+- If clickable, use button or link element, not onClick on div
+- Provide appropriate role if interactive
+
+**Notes:**
+
+- Card is purely visual - has no semantic meaning
+
+## Badge
+
+**Developer must provide:**
+
+- Provide context via aria-label or surrounding text
+- For status badges, consider aria-live for dynamic updates
+
+**Notes:**
+
+- Badge is purely visual - has no semantic meaning
+
+## Avatar
+
+**Developer must provide:**
+
+- Provide alt text on AvatarImage
+- AvatarFallback provides fallback for screen readers
+
+**Notes:**
+
+- Decorative avatars should have empty alt=""
+
+## Skeleton
+
+**Developer must provide:**
+
+- Provide aria-busy="true" on parent container
+- Consider aria-live region for loading announcements
+
+**Notes:**
+
+- Skeleton is decorative - loading state should be announced separately
+
+## Table
+
+**Built-in accessibility:**
+
+- Native table element with proper structure
+- th elements for headers
+- Proper table semantics
+
+**Developer must provide:**
+
+- Use TableCaption for table description
+- Use scope="col" or scope="row" on headers
+
+**Notes:**
+
+- Use native table semantics, avoid role="presentation"
diff --git a/internal/vibe-tests/a11y-manifests/xds.json b/internal/vibe-tests/a11y-manifests/xds.json
new file mode 100644
index 0000000000..924c78d1bc
--- /dev/null
+++ b/internal/vibe-tests/a11y-manifests/xds.json
@@ -0,0 +1,146 @@
+{
+ "source": "packages/core/src/*/README.md",
+ "generatedAt": "2026-02-05T18:03:04.596Z",
+ "version": "1.0.0",
+ "components": {
+ "Avatar": {
+ "component": "Avatar",
+ "builtIn": [
+ "Accessible: Proper role and aria-label support"
+ ],
+ "keyboard": [],
+ "developerMust": [],
+ "notes": []
+ },
+ "Button": {
+ "component": "Button",
+ "builtIn": [
+ "Variants: `primary`, `secondary`, `ghost`, `destructive`",
+ "Focus visible: Accessible focus outline with variant-specific colors"
+ ],
+ "keyboard": [],
+ "developerMust": [
+ "Provide aria-label for icon-only buttons",
+ "Use aria-pressed for toggle buttons"
+ ],
+ "notes": [
+ "`XDSButtonVariant` type is derived from the `variants` StyleX object using `keyof typeof variants`",
+ "Destructive variant uses `colorTokens.negative` for its focus outline color"
+ ]
+ },
+ "CheckboxInput": {
+ "component": "CheckboxInput",
+ "builtIn": [
+ "Accessible: Always includes a label (can be visually hidden)",
+ "Supports visually hidden labels (still accessible to screen readers)"
+ ],
+ "keyboard": [],
+ "developerMust": [],
+ "notes": [
+ "Label is clickable and properly associated with the input via `htmlFor`/`id`",
+ "Label is required prop - component handles label association"
+ ]
+ },
+ "DateInput": {
+ "component": "DateInput",
+ "builtIn": [
+ "Calendar Popover: Click icon or use keyboard to open calendar picker",
+ "Accessibility: Full keyboard navigation, focus trapping, screen reader support",
+ "Supports visually hidden labels (still accessible to screen readers)"
+ ],
+ "keyboard": [],
+ "developerMust": [],
+ "notes": [
+ "Label is required prop - component handles label association"
+ ]
+ },
+ "Field": {
+ "component": "Field",
+ "builtIn": [
+ "Accessible: Label properly associated with input via htmlFor/id",
+ "Uses aria-describedby for descriptions",
+ "Supports visually hidden labels (still accessible to screen readers)"
+ ],
+ "keyboard": [],
+ "developerMust": [],
+ "notes": [
+ "Label is always rendered for accessibility; use `isLabelHidden` to hide visually",
+ "Hidden label uses CSS technique that remains accessible to screen readers",
+ "Description is rendered when provided; if `descriptionID` is also provided, the description element gets that ID for `aria-describedby` association",
+ "Optional/Required text appears on the same line as the label"
+ ]
+ },
+ "Icon": {
+ "component": "Icon",
+ "builtIn": [
+ "Theme Colors: Color variants mapped to XDS icon color tokens",
+ "Accessible: Icons are hidden from screen readers by default (aria-hidden)"
+ ],
+ "keyboard": [],
+ "developerMust": [],
+ "notes": [
+ "Uses `aria-hidden=\"true\"` by default since icons are typically decorative",
+ "For meaningful icons, set `aria-hidden={false}`, `role=\"img\"`, and `aria-label`"
+ ]
+ },
+ "Selector": {
+ "component": "Selector",
+ "builtIn": [
+ "Uses `role=\"combobox\"` trigger",
+ "`role=\"listbox\"` dropdown",
+ "`role=\"group\"` for sections",
+ "`aria-activedescendant` for focus",
+ "Supports visually hidden labels (still accessible to screen readers)"
+ ],
+ "keyboard": [
+ "↑↓ navigate, Enter/Space select, Escape close, Home/End jump, A-Z typeahead."
+ ],
+ "developerMust": [],
+ "notes": []
+ },
+ "TextArea": {
+ "component": "TextArea",
+ "builtIn": [
+ "Accessible: Label properly associated with textarea via htmlFor/id",
+ "Supports visually hidden labels (still accessible to screen readers)"
+ ],
+ "keyboard": [],
+ "developerMust": [],
+ "notes": [
+ "Uses `useId` hook for accessible label-textarea association",
+ "Label is always rendered for accessibility; use `isLabelHidden` to hide visually",
+ "Hidden label uses CSS technique that remains accessible to screen readers",
+ "Wraps `XDSField` component for label, description, and optional/required handling",
+ "Optional/Required text appears on the same line as the label",
+ "Label is required prop - component handles label association"
+ ]
+ },
+ "TextInput": {
+ "component": "TextInput",
+ "builtIn": [
+ "Accessible: Label properly associated with input via htmlFor/id",
+ "Sets aria-invalid for error status",
+ "Supports visually hidden labels (still accessible to screen readers)"
+ ],
+ "keyboard": [],
+ "developerMust": [],
+ "notes": [
+ "Uses `useId` hook for accessible label-input association",
+ "Label is always rendered for accessibility; use `isLabelHidden` to hide visually",
+ "Hidden label uses CSS technique that remains accessible to screen readers",
+ "Wraps `XDSField` component for label, description, and optional/required handling",
+ "Optional/Required text appears on the same line as the label",
+ "Label is required prop - component handles label association"
+ ]
+ },
+ "theme": {
+ "component": "theme",
+ "builtIn": [
+ "XDSTheme Provider: Wraps app to provide CSS variables"
+ ],
+ "keyboard": [],
+ "developerMust": [],
+ "notes": []
+ }
+ }
+}
\ No newline at end of file
diff --git a/internal/vibe-tests/a11y-manifests/xds.md b/internal/vibe-tests/a11y-manifests/xds.md
new file mode 100644
index 0000000000..0498eb8bf2
--- /dev/null
+++ b/internal/vibe-tests/a11y-manifests/xds.md
@@ -0,0 +1,131 @@
+# XDS Accessibility Manifest
+
+**Source:** packages/core/src/\*/README.md
+**Generated:** 2026-02-05T18:03:04.596Z
+
+## Avatar
+
+**Built-in accessibility:**
+
+- Accessible: Proper role and aria-label support
+
+## Button
+
+**Built-in accessibility:**
+
+- Variants: `primary`, `secondary`, `ghost`, `destructive`
+- Focus visible: Accessible focus outline with variant-specific colors
+
+**Developer must provide:**
+
+- Provide aria-label for icon-only buttons
+- Use aria-pressed for toggle buttons
+
+**Notes:**
+
+- `XDSButtonVariant` type is derived from the `variants` StyleX object using `keyof typeof variants`
+- Destructive variant uses `colorTokens.negative` for its focus outline color
+
+## CheckboxInput
+
+**Built-in accessibility:**
+
+- Accessible: Always includes a label (can be visually hidden)
+- Supports visually hidden labels (still accessible to screen readers)
+
+**Notes:**
+
+- Label is clickable and properly associated with the input via `htmlFor`/`id`
+- Label is required prop - component handles label association
+
+## DateInput
+
+**Built-in accessibility:**
+
+- Calendar Popover: Click icon or use keyboard to open calendar picker
+- Accessibility: Full keyboard navigation, focus trapping, screen reader support
+- Supports visually hidden labels (still accessible to screen readers)
+
+**Notes:**
+
+- Label is required prop - component handles label association
+
+## Field
+
+**Built-in accessibility:**
+
+- Accessible: Label properly associated with input via htmlFor/id
+- Uses aria-describedby for descriptions
+- Supports visually hidden labels (still accessible to screen readers)
+
+**Notes:**
+
+- Label is always rendered for accessibility; use `isLabelHidden` to hide visually
+- Hidden label uses CSS technique that remains accessible to screen readers
+- Description is rendered when provided; if `descriptionID` is also provided, the description element gets that ID for `aria-describedby` association
+- Optional/Required text appears on the same line as the label
+
+## Icon
+
+**Built-in accessibility:**
+
+- Theme Colors: Color variants mapped to XDS icon color tokens
+- Accessible: Icons are hidden from screen readers by default (aria-hidden)
+
+**Notes:**
+
+- Uses `aria-hidden="true"` by default since icons are typically decorative
+- For meaningful icons, set `aria-hidden={false}`, `role="img"`, and `aria-label`
+
+## Selector
+
+**Built-in accessibility:**
+
+- Uses `role="combobox"` trigger
+- `role="listbox"` dropdown
+- `role="group"` for sections
+- `aria-activedescendant` for focus
+- Supports visually hidden labels (still accessible to screen readers)
+
+**Keyboard:**
+
+- ↑↓ navigate, Enter/Space select, Escape close, Home/End jump, A-Z typeahead.
+
+## TextArea
+
+**Built-in accessibility:**
+
+- Accessible: Label properly associated with textarea via htmlFor/id
+- Supports visually hidden labels (still accessible to screen readers)
+
+**Notes:**
+
+- Uses `useId` hook for accessible label-textarea association
+- Label is always rendered for accessibility; use `isLabelHidden` to hide visually
+- Hidden label uses CSS technique that remains accessible to screen readers
+- Wraps `XDSField` component for label, description, and optional/required handling
+- Optional/Required text appears on the same line as the label
+- Label is required prop - component handles label association
+
+## TextInput
+
+**Built-in accessibility:**
+
+- Accessible: Label properly associated with input via htmlFor/id
+- Sets aria-invalid for error status
+- Supports visually hidden labels (still accessible to screen readers)
+
+**Notes:**
+
+- Uses `useId` hook for accessible label-input association
+- Label is always rendered for accessibility; use `isLabelHidden` to hide visually
+- Hidden label uses CSS technique that remains accessible to screen readers
+- Wraps `XDSField` component for label, description, and optional/required handling
+- Optional/Required text appears on the same line as the label
+- Label is required prop - component handles label association
+
+## theme
+
+**Built-in accessibility:**
+
+- XDSTheme Provider: Wraps app to provide CSS variables
diff --git a/internal/vibe-tests/package.json b/internal/vibe-tests/package.json
index 578288638f..d98e1db7d6 100644
--- a/internal/vibe-tests/package.json
+++ b/internal/vibe-tests/package.json
@@ -20,7 +20,10 @@
"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"
+ "analyze": "tsx src/cli.ts analyze",
+ "quality": "tsx src/quality.ts",
+ "compare": "tsx src/compare.ts",
+ "generate-a11y-manifest": "tsx src/generate-a11y-manifest.ts"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.52.0",
diff --git a/internal/vibe-tests/src/aggregate.ts b/internal/vibe-tests/src/aggregate.ts
index 134e49dac5..f1e8a1be9e 100644
--- a/internal/vibe-tests/src/aggregate.ts
+++ b/internal/vibe-tests/src/aggregate.ts
@@ -17,6 +17,8 @@ import type {
EscapeHatchType,
JobBreakdown,
InputTokenBreakdown,
+ QualityAssessment,
+ QualityScore,
} from './types.js';
import {writeJson, getResultsDir} from './utils.js';
@@ -91,8 +93,13 @@ function estimateInputTokens(
/**
* Analyze code to break down tokens by job type
+ * @param code The generated code to analyze
+ * @param target The target design system ('xds' | 'baseline')
*/
-function analyzeJobBreakdown(code: string): JobBreakdown {
+function analyzeJobBreakdown(
+ code: string,
+ target: string = 'xds',
+): JobBreakdown {
const jobs = {
componentRouting: 0,
componentConfig: 0,
@@ -111,23 +118,51 @@ function analyzeJobBreakdown(code: string): JobBreakdown {
// Imports
if (stripped.startsWith('import')) {
- if (line.includes('XDS') || line.includes('@xds')) {
- jobs.componentRouting += chars;
+ if (target === 'xds') {
+ // XDS: imports from @xds/core are component routing
+ if (line.includes('XDS') || line.includes('@xds')) {
+ jobs.componentRouting += chars;
+ } else {
+ jobs.boilerplate += chars;
+ }
} else {
- jobs.boilerplate += chars;
+ // baseline: imports from @/components/ui are component routing
+ if (
+ line.includes('@/components/ui') ||
+ line.includes('components/ui')
+ ) {
+ jobs.componentRouting += chars;
+ } else if (
+ line.includes('@/lib/utils') ||
+ line.includes('class-variance-authority') ||
+ line.includes('clsx')
+ ) {
+ // cn() utility imports - part of styling system
+ jobs.componentConfig += chars;
+ } else {
+ jobs.boilerplate += chars;
+ }
}
continue;
}
- // StyleX styles block
- if (line.includes('stylex.create')) {
- inStyles = true;
+ // StyleX styles block - XDS only, this is supplemental styling
+ if (target === 'xds') {
+ if (line.includes('stylex.create')) {
+ inStyles = true;
+ }
+ if (inStyles) {
+ jobs.supplementalStyling += chars;
+ if (stripped === '});') {
+ inStyles = false;
+ }
+ continue;
+ }
}
- if (inStyles) {
+
+ // For baseline: inline style objects are supplemental (escape hatch)
+ if (target === 'baseline' && line.includes('style={{')) {
jobs.supplementalStyling += chars;
- if (stripped === '});') {
- inStyles = false;
- }
continue;
}
@@ -146,34 +181,101 @@ function analyzeJobBreakdown(code: string): JobBreakdown {
continue;
}
- // JSX with XDS components and props
- const propPatterns = [
- 'label=',
- 'value=',
- 'onChange=',
- 'variant=',
- 'disabled=',
- 'loading=',
- 'onClick=',
- 'placeholder=',
- 'isRequired',
- 'header=',
- 'content=',
- 'theme=',
- ];
- if (
- line.includes('<XDS') ||
- line.includes('</XDS') ||
- (stripped && propPatterns.some(p => line.includes(p)))
- ) {
- jobs.componentConfig += chars;
- continue;
+ // JSX with components and props
+ if (target === 'xds') {
+ // XDS component patterns
+ const propPatterns = [
+ 'label=',
+ 'value=',
+ 'onChange=',
+ 'variant=',
+ 'disabled=',
+ 'loading=',
+ 'onClick=',
+ 'placeholder=',
+ 'isRequired',
+ 'header=',
+ 'content=',
+ 'theme=',
+ ];
+ if (
+ line.includes('<XDS') ||
+ line.includes('</XDS') ||
+ (stripped && propPatterns.some(p => line.includes(p)))
+ ) {
+ jobs.componentConfig += chars;
+ continue;
+ }
+ } else {
+ // baseline component patterns
+ // In baseline, className with Tailwind IS styling (not component config)
+ // Only component props count as config
+ const baselineComponents = [
+ '<Button',
+ '</Button>',
+ '<Card',
+ '</Card>',
+ '<Input',
+ '</Input>',
+ '<Table',
+ '</Table>',
+ '<Dialog',
+ '</Dialog>',
+ '<Popover',
+ '</Popover>',
+ '<Select',
+ '</Select>',
+ '<Checkbox',
+ '</Checkbox>',
+ '<Badge',
+ '</Badge>',
+ '<Avatar',
+ '</Avatar>',
+ '<Tabs',
+ '</Tabs>',
+ '<Command',
+ '</Command>',
+ '<DropdownMenu',
+ '</DropdownMenu>',
+ ];
+ const baselinePropPatterns = [
+ 'variant=',
+ 'size=',
+ 'disabled=',
+ 'onClick=',
+ 'onChange=',
+ 'onValueChange=',
+ 'onCheckedChange=',
+ 'placeholder=',
+ 'asChild',
+ 'defaultValue=',
+ 'value=',
+ // Note: className is NOT included - that's styling, not config
+ ];
+ if (
+ baselineComponents.some(c => line.includes(c)) ||
+ (stripped && baselinePropPatterns.some(p => line.includes(p)))
+ ) {
+ jobs.componentConfig += chars;
+ continue;
+ }
+
+ // For baseline: className with Tailwind fills gaps that component props don't cover
+ // This is analogous to StyleX in XDS - supplemental styling
+ if (line.includes('className=')) {
+ jobs.supplementalStyling += chars;
+ continue;
+ }
}
// JSX structure (html elements)
- if (/<\/?[a-z]/.test(line) && !line.includes('XDS')) {
- jobs.contentAuthoring += chars;
- continue;
+ if (/<\/?[a-z]/.test(line)) {
+ if (target === 'xds' && line.includes('XDS')) {
+ // Already handled above
+ } else {
+ jobs.contentAuthoring += chars;
+ continue;
+ }
}
// State, handlers, logic
@@ -236,6 +338,7 @@ const ANTI_PATTERN_HATCHES: EscapeHatchType[] = [
'hardcoded_color',
'hardcoded_spacing',
'inline_style', // Should use StyleX instead
+ 'a11y_click_handler', // Accessibility issue: use button instead
];
interface TierCounts {
@@ -315,6 +418,26 @@ interface AggregateResult {
};
grandTotal: number;
};
+ // Quality assessment results (from quality agent)
+ quality?: {
+ assessed: number;
+ byScore: Record<QualityScore, number>;
+ accessibility: {
+ byScore: Record<QualityScore, number>;
+ totalIssues: number;
+ criticalIssues: number;
+ };
+ designSystem: {
+ byScore: Record<QualityScore, number>;
+ totalIssues: number;
+ criticalIssues: number;
+ };
+ codeQuality: {
+ byScore: Record<QualityScore, number>;
+ totalIssues: number;
+ criticalIssues: number;
+ };
+ };
}
/** Normalize escape hatch to object format (handles string or object) */
@@ -333,6 +456,20 @@ function normalizeEscapeHatch(h: string | EscapeHatch): EscapeHatch {
/** Calculate the tier for a single result */
function calculateTier(evaluation: Evaluation): ResultTier {
+ // If the evaluation explicitly marks this as a failure, respect that
+ // This is important for degradation tests where subagents evaluate in-context
+ if (evaluation.success === false) {
+ // Check if there's a failure mode indicating severity
+ if (
+ evaluation.failureMode === 'complete_context_loss' ||
+ evaluation.failureMode === 'hallucination'
+ ) {
+ return 'red';
+ }
+ // Context drift or other failures are yellow (degraded but not critical)
+ return 'yellow';
+ }
+
const normalizedHatches = evaluation.escapeHatches.map(normalizeEscapeHatch);
const criticalHatches = normalizedHatches.filter(
@@ -465,98 +602,171 @@ function extractComponentsFromCode(code: string): string[] {
/**
* Detect escape hatches in code
+ * @param code The generated code to analyze
+ * @param target The target design system ('xds' | 'baseline')
*/
-function detectEscapeHatches(code: string): EscapeHatch[] {
+function detectEscapeHatches(
+ code: string,
+ target: string = 'xds',
+): EscapeHatch[] {
const hatches: EscapeHatch[] = [];
- // Check for hardcoded colors (hex, rgb, hsl, or named colors in style context)
- const hardcodedColorRegex =
- /(?:color|background|border|fill|stroke)\s*:\s*['"]?(#[0-9a-fA-F]{3,8}|rgb\([^)]+\)|hsl\([^)]+\)|rgba\([^)]+\)|hsla\([^)]+\))['"]?/gi;
- let match;
- while ((match = hardcodedColorRegex.exec(code)) !== null) {
- hatches.push({
- type: 'hardcoded_color',
- severity: 'acceptable',
- detail: 'Hardcoded color value instead of CSS variable',
- codeSnippet: match[0],
- });
- }
-
- // Check for hardcoded spacing (px values in padding, margin, gap)
- const hardcodedSpacingRegex =
- /(?:padding|margin|gap|top|bottom|left|right|width|height)\s*:\s*['"]?\d+px['"]?/gi;
- while ((match = hardcodedSpacingRegex.exec(code)) !== null) {
- // Skip if it's inside a var() or uses spacing tokens
- if (!match[0].includes('var(')) {
+ // Check for hardcoded colors (hex, rgb, hsl in StyleX style definitions)
+ // Only flag colors in stylex.create() blocks, not in data objects
+ // Dynamic data colors (like user-defined label colors) are acceptable
+ if (target === 'xds') {
+ // Match colors specifically in style property contexts (after colon with property name)
+ // Skip if the color is a variable reference (like label.color) or data property
+ const hardcodedColorRegex =
+ /(?:backgroundColor|borderColor|color|fill|stroke)\s*:\s*['"]?(#[0-9a-fA-F]{3,8}|rgb\([^)]+\)|hsl\([^)]+\)|rgba\([^)]+\)|hsla\([^)]+\))['"]?/gi;
+ let match;
+ while ((match = hardcodedColorRegex.exec(code)) !== null) {
+ // Skip if it looks like it's in a data array (preceded by id, name, etc.)
+ const context = code.slice(Math.max(0, match.index - 50), match.index);
+ if (
+ context.includes('name:') ||
+ context.includes('id:') ||
+ context.includes('label:')
+ ) {
+ continue; // Skip data objects
+ }
hatches.push({
- type: 'hardcoded_spacing',
+ type: 'hardcoded_color',
severity: 'acceptable',
- detail: 'Hardcoded spacing value instead of spacing token',
+ detail: 'Hardcoded color value instead of CSS variable',
codeSnippet: match[0],
});
}
}
- // Check for inline style props (not StyleX)
- const inlineStyleRegex = /style\s*=\s*\{\{/g;
+ // Check for hardcoded spacing (px values in padding, margin, gap)
+ // Skip for baseline since Tailwind classes handle this differently
+ // Note: width/height are dimension constraints, not spacing - they're acceptable
+ if (target === 'xds') {
+ // Only match true spacing properties, not dimensions
+ const hardcodedSpacingRegex =
+ /(?:padding|margin|gap|paddingTop|paddingBottom|paddingLeft|paddingRight|paddingBlock|paddingInline|marginTop|marginBottom|marginLeft|marginRight|marginBlock|marginInline|rowGap|columnGap)\s*:\s*['"]?\d+px['"]?/gi;
+ let match;
+ while ((match = hardcodedSpacingRegex.exec(code)) !== null) {
+ // Skip if it's inside a var() or uses spacing tokens
+ if (!match[0].includes('var(')) {
+ hatches.push({
+ type: 'hardcoded_spacing',
+ severity: 'acceptable',
+ detail: 'Hardcoded spacing value instead of spacing token',
+ codeSnippet: match[0],
+ });
+ }
+ }
+ }
+
+ // Check for inline style props (not StyleX/Tailwind)
+ // Skip inline styles that only use variable references (dynamic data values)
+ const inlineStyleRegex = /style\s*=\s*\{\{([^}]+)\}\}/g;
+ let match;
while ((match = inlineStyleRegex.exec(code)) !== null) {
+ const styleContent = match[1];
+ // Check if the style only contains variable references (no literals)
+ // Pattern like "backgroundColor: item.color" or "color: data.value" is OK
+ const hasOnlyVariableRefs = /^\s*\w+:\s*[\w.]+\s*$/.test(styleContent);
+ if (hasOnlyVariableRefs) {
+ // Skip - this is a legitimate dynamic data value
+ continue;
+ }
hatches.push({
type: 'inline_style',
severity: 'acceptable',
- detail: 'Inline style object instead of StyleX',
+ detail:
+ target === 'xds'
+ ? 'Inline style object instead of StyleX'
+ : 'Inline style object instead of Tailwind',
codeSnippet: match[0],
});
}
- // Check for wrapper divs (plain divs that could use XDS layout)
+ // Check for wrapper divs (plain divs that could use layout components)
const wrapperDivRegex = /<div\s+(?:className|style)/g;
while ((match = wrapperDivRegex.exec(code)) !== null) {
hatches.push({
type: 'wrapper_div',
severity: 'acceptable',
- detail: 'Wrapper div that could potentially use XDS layout components',
+ detail:
+ target === 'xds'
+ ? 'Wrapper div that could potentially use XDS layout components'
+ : 'Wrapper div (common in Tailwind patterns)',
codeSnippet: match[0],
});
}
- // Check for hallucinated props (common mistakes)
- // Only flag clearly invalid patterns, not valid but uncommon props
- const hallucinatedProps = [
- {pattern: /variant\s*=\s*["']outline["']/g, prop: 'variant="outline"'},
- {pattern: /size\s*=\s*["'](?:xs|xxl|xxxl)["']/g, prop: 'invalid size prop'},
- ];
- for (const {pattern, prop} of hallucinatedProps) {
- if (pattern.test(code)) {
- hatches.push({
- type: 'hallucination',
- severity: 'critical',
- detail: `Potentially hallucinated prop: ${prop}`,
- codeSnippet: prop,
- });
+ // Check for accessibility issues: onClick on non-interactive elements
+ // Elements like <span>, <div>, <p>, <td> with onClick should use <button> instead
+ const a11yClickRegex =
+ /<(span|div|p|td|tr|li|label|img|svg)\b[^>]*\bonClick\b/gi;
+ while ((match = a11yClickRegex.exec(code)) !== null) {
+ // Skip if it has role="button" or tabIndex (attempts at a11y fix)
+ const elementContext = code.slice(match.index, match.index + 200);
+ if (
+ elementContext.includes('role="button"') ||
+ elementContext.includes("role='button'") ||
+ elementContext.includes('tabIndex')
+ ) {
+ continue; // Has some a11y attributes, less severe
}
+ hatches.push({
+ type: 'a11y_click_handler',
+ severity: 'acceptable', // Still acceptable but flagged as anti-pattern
+ detail: `onClick on <${match[1]}> should use Button component for accessibility`,
+ codeSnippet: match[0].slice(0, 60),
+ });
}
- // Check for StyleX with valid CSS variables (this is acceptable - supplemental_css)
- const stylexBlockRegex = /stylex\.create\(\{[\s\S]*?\}\)/g;
- while ((match = stylexBlockRegex.exec(code)) !== null) {
- // Only flag if it has significant styling (not just layout)
- const block = match[0];
- if (
- block.includes('backgroundColor') ||
- block.includes('borderColor') ||
- block.includes('color:')
- ) {
- // Check if using CSS variables
- if (block.includes('var(--')) {
+ // Check for hallucinated props - target-specific
+ if (target === 'xds') {
+ // XDS-specific hallucination checks
+ const hallucinatedProps = [
+ {pattern: /variant\s*=\s*["']outline["']/g, prop: 'variant="outline"'},
+ {
+ pattern: /size\s*=\s*["'](?:xs|xxl|xxxl)["']/g,
+ prop: 'invalid size prop',
+ },
+ ];
+ for (const {pattern, prop} of hallucinatedProps) {
+ if (pattern.test(code)) {
hatches.push({
- type: 'supplemental_css',
- severity: 'acceptable',
- detail: 'StyleX styling using CSS variables',
- codeSnippet: block.slice(0, 100) + '...',
+ type: 'hallucination',
+ severity: 'critical',
+ detail: `Potentially hallucinated prop: ${prop}`,
+ codeSnippet: prop,
});
}
}
}
+ // baseline has different valid patterns, so no hallucination checks for now
+
+ // Check for StyleX with valid CSS variables (this is acceptable - supplemental_css)
+ // Only relevant for XDS
+ if (target === 'xds') {
+ const stylexBlockRegex = /stylex\.create\(\{[\s\S]*?\}\)/g;
+ while ((match = stylexBlockRegex.exec(code)) !== null) {
+ // Only flag if it has significant styling (not just layout)
+ const block = match[0];
+ if (
+ block.includes('backgroundColor') ||
+ block.includes('borderColor') ||
+ block.includes('color:')
+ ) {
+ // Check if using CSS variables
+ if (block.includes('var(--')) {
+ hatches.push({
+ type: 'supplemental_css',
+ severity: 'acceptable',
+ detail: 'StyleX styling using CSS variables',
+ codeSnippet: block.slice(0, 100) + '...',
+ });
+ }
+ }
+ }
+ }
return hatches;
}
@@ -565,11 +775,11 @@ function detectEscapeHatches(code: string): EscapeHatch[] {
* Load results from individual result files (.tsx code files)
* Evaluates code externally instead of relying on self-evaluation
*/
-function loadResults(resultsDir: string): TestResult[] {
+function loadResults(resultsDir: string): (TestResult & {target?: string})[] {
const individualResultsDir = path.join(resultsDir, 'results');
const tasksDir = path.join(resultsDir, 'tasks');
const manifestPath = path.join(resultsDir, 'manifest.json');
- const results: TestResult[] = [];
+ const results: (TestResult & {target?: string})[] = [];
if (!fs.existsSync(individualResultsDir)) {
throw new Error(`No results directory found at ${individualResultsDir}`);
@@ -620,7 +830,10 @@ function loadResults(resultsDir: string): TestResult[] {
}
// Load manifest for iteration info
- let manifest: {iterationId: string; config: {persona: string}} | null = null;
+ let manifest: {
+ iterationId: string;
+ config: {persona: string; target?: string};
+ } | null = null;
if (fs.existsSync(manifestPath)) {
try {
manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
@@ -647,6 +860,7 @@ function loadResults(resultsDir: string): TestResult[] {
prompt: string;
expectedComponents: string[];
persona: string;
+ target?: string;
} | null = null;
if (fs.existsSync(taskPath)) {
task = JSON.parse(fs.readFileSync(taskPath, 'utf-8'));
@@ -665,7 +879,7 @@ function loadResults(resultsDir: string): TestResult[] {
// External evaluation: extract components and detect escape hatches
const componentsUsed = extractComponentsFromCode(code);
- const escapeHatches = detectEscapeHatches(code);
+ const escapeHatches = detectEscapeHatches(code, task?.target || 'xds');
// Determine success based on critical escape hatches
const hasCritical = escapeHatches.some(h => h.severity === 'critical');
@@ -682,7 +896,7 @@ function loadResults(resultsDir: string): TestResult[] {
}
}
- const result: TestResult = {
+ const result: TestResult & {target?: string} = {
id: `${manifest?.iterationId || 'unknown'}-${promptId}`,
timestamp: new Date().toISOString(),
systemVersion: 'claude-code-interactive',
@@ -706,6 +920,7 @@ function loadResults(resultsDir: string): TestResult[] {
inputTokens: 0,
outputTokens: 0,
docsRead,
+ target: task?.target || manifest?.config?.target || 'xds',
};
results.push(result);
@@ -717,6 +932,38 @@ function loadResults(resultsDir: string): TestResult[] {
return results;
}
+/**
+ * Load quality assessments from .quality.json files
+ */
+function loadQualityAssessments(
+ resultsDir: string,
+): Map<string, QualityAssessment> {
+ const individualResultsDir = path.join(resultsDir, 'results');
+ const assessments = new Map<string, QualityAssessment>();
+
+ if (!fs.existsSync(individualResultsDir)) {
+ return assessments;
+ }
+
+ const files = fs
+ .readdirSync(individualResultsDir)
+ .filter(f => f.endsWith('.quality.json'));
+
+ for (const file of files) {
+ try {
+ const promptId = file.replace('.quality.json', '');
+ const assessmentPath = path.join(individualResultsDir, file);
+ const content = fs.readFileSync(assessmentPath, 'utf-8');
+ const assessment = JSON.parse(content) as QualityAssessment;
+ assessments.set(promptId, assessment);
+ } catch (e) {
+ console.warn(`Warning: Failed to parse quality assessment ${file}: ${e}`);
+ }
+ }
+
+ return assessments;
+}
+
function aggregate(iterationId: string): AggregateResult {
const resultsDir = path.join(getResultsDir(), iterationId);
@@ -955,7 +1202,10 @@ function aggregate(iterationId: string): AggregateResult {
};
for (const result of results) {
- const breakdown = analyzeJobBreakdown(result.response);
+ const breakdown = analyzeJobBreakdown(
+ result.response,
+ result.target || 'xds',
+ );
// Accumulate output totals
totalJobs.componentRouting += breakdown.componentRouting;
@@ -1063,6 +1313,94 @@ function aggregate(iterationId: string): AggregateResult {
grandTotal,
};
+ // Load and aggregate quality assessments
+ const qualityAssessments = loadQualityAssessments(resultsDir);
+ let quality:
+ | {
+ assessed: number;
+ byScore: Record<QualityScore, number>;
+ accessibility: {
+ byScore: Record<QualityScore, number>;
+ totalIssues: number;
+ criticalIssues: number;
+ };
+ designSystem: {
+ byScore: Record<QualityScore, number>;
+ totalIssues: number;
+ criticalIssues: number;
+ };
+ codeQuality: {
+ byScore: Record<QualityScore, number>;
+ totalIssues: number;
+ criticalIssues: number;
+ };
+ }
+ | undefined;
+
+ if (qualityAssessments.size > 0) {
+ const byScore: Record<QualityScore, number> = {
+ good: 0,
+ 'needs-work': 0,
+ poor: 0,
+ };
+ const accessibility = {
+ byScore: {good: 0, 'needs-work': 0, poor: 0} as Record<
+ QualityScore,
+ number
+ >,
+ totalIssues: 0,
+ criticalIssues: 0,
+ };
+ const designSystem = {
+ byScore: {good: 0, 'needs-work': 0, poor: 0} as Record<
+ QualityScore,
+ number
+ >,
+ totalIssues: 0,
+ criticalIssues: 0,
+ };
+ const codeQuality = {
+ byScore: {good: 0, 'needs-work': 0, poor: 0} as Record<
+ QualityScore,
+ number
+ >,
+ totalIssues: 0,
+ criticalIssues: 0,
+ };
+
+ for (const assessment of qualityAssessments.values()) {
+ byScore[assessment.overallScore]++;
+
+ accessibility.byScore[assessment.accessibility.score]++;
+ accessibility.totalIssues += assessment.accessibility.issues.length;
+ accessibility.criticalIssues += assessment.accessibility.issues.filter(
+ i => i.severity === 'critical',
+ ).length;
+
+ designSystem.byScore[assessment.designSystemAdherence.score]++;
+ designSystem.totalIssues +=
+ assessment.designSystemAdherence.issues.length;
+ designSystem.criticalIssues +=
+ assessment.designSystemAdherence.issues.filter(
+ i => i.severity === 'critical',
+ ).length;
+
+ codeQuality.byScore[assessment.codeQuality.score]++;
+ codeQuality.totalIssues += assessment.codeQuality.issues.length;
+ codeQuality.criticalIssues += assessment.codeQuality.issues.filter(
+ i => i.severity === 'critical',
+ ).length;
+ }
+
+ quality = {
+ assessed: qualityAssessments.size,
+ byScore,
+ accessibility,
+ designSystem,
+ codeQuality,
+ };
+ }
+
return {
iterationId,
totalTests: results.length,
@@ -1086,6 +1424,7 @@ function aggregate(iterationId: string): AggregateResult {
totalOutputTokens,
jobStats,
tokenUsage,
+ quality,
};
}
@@ -1099,7 +1438,7 @@ function printReport(agg: AggregateResult): void {
// Tiered breakdown
console.log(`\nπŸ† Quality Tiers:`);
console.log(
- ` πŸ₯‡ Gold (pure XDS): ${agg.tiers.gold} (${agg.tierRate.gold}%)`,
+ ` πŸ₯‡ Gold (pure DS): ${agg.tiers.gold} (${agg.tierRate.gold}%)`,
);
console.log(
` 🟒 Green (acceptable): ${agg.tiers.green} (${agg.tierRate.green}%)`,
@@ -1147,7 +1486,7 @@ function printReport(agg: AggregateResult): void {
console.log(` β”‚ INPUT TOKENS (estimated from doc reading) β”‚`);
console.log(` β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€`);
console.log(
- ` β”‚ AGENTS.md: ${String(tu.input.total.agentsMd).padStart(6)} tokens β”‚`,
+ ` β”‚ Agent docs: ${String(tu.input.total.agentsMd).padStart(6)} tokens β”‚`,
);
console.log(
` β”‚ Design docs: ${String(tu.input.total.designDocs).padStart(6)} tokens β”‚`,
@@ -1169,7 +1508,7 @@ function printReport(agg: AggregateResult): void {
const p = agg.jobStats.percentages;
const outputTokens = Math.round(tu.output.total.total / 4);
console.log(
- ` β”‚ Component routing: ${String(p.componentRouting).padStart(3)}% (~${Math.round(tu.output.total.componentRouting / 4)} tokens) β”‚`,
+ ` β”‚ Library imports: ${String(p.componentRouting).padStart(3)}% (~${Math.round(tu.output.total.componentRouting / 4)} tokens) β”‚`,
);
console.log(
` β”‚ Component config: ${String(p.componentConfig).padStart(3)}% (~${Math.round(tu.output.total.componentConfig / 4)} tokens) β”‚`,
@@ -1201,7 +1540,7 @@ function printReport(agg: AggregateResult): void {
console.log(`\nπŸ”§ Job Breakdown (output token distribution):`);
const p = agg.jobStats.percentages;
console.log(
- ` Component routing: ${String(p.componentRouting).padStart(3)}%`,
+ ` Library imports: ${String(p.componentRouting).padStart(3)}%`,
);
console.log(
` Component config: ${String(p.componentConfig).padStart(3)}%`,
@@ -1262,6 +1601,26 @@ function printReport(agg: AggregateResult): void {
}
}
+ // Quality assessment results (if present)
+ if (agg.quality) {
+ const q = agg.quality;
+ console.log(`\nπŸ”¬ Quality Assessment (${q.assessed} assessed):`);
+ console.log(` Overall Scores:`);
+ console.log(
+ ` βœ“ Good: ${q.byScore.good} ⚠ Needs Work: ${q.byScore['needs-work']} βœ— Poor: ${q.byScore.poor}`,
+ );
+ console.log(` By Category:`);
+ console.log(
+ ` Accessibility: ${q.accessibility.totalIssues} issues (${q.accessibility.criticalIssues} critical)`,
+ );
+ console.log(
+ ` Design System: ${q.designSystem.totalIssues} issues (${q.designSystem.criticalIssues} critical)`,
+ );
+ console.log(
+ ` Code Quality: ${q.codeQuality.totalIssues} issues (${q.codeQuality.criticalIssues} critical)`,
+ );
+ }
+
if (Object.keys(agg.acceptableEscapeHatches).length > 0) {
console.log(`\nβœ“ Acceptable Escape Hatches:`);
for (const [type, count] of Object.entries(agg.acceptableEscapeHatches)) {
@@ -1301,7 +1660,7 @@ function printReport(agg: AggregateResult): void {
function generateHtmlReport(
iterationId: string,
agg: AggregateResult,
- results: TestResult[],
+ results: (TestResult & {target?: string})[],
): string {
const escapeHtml = (str: string | undefined) =>
(str || '')
@@ -1566,7 +1925,7 @@ function generateHtmlReport(
: '-';
// Calculate per-test token breakdown
- const jobBreakdown = analyzeJobBreakdown(r.response);
+ const jobBreakdown = analyzeJobBreakdown(r.response, r.target || 'xds');
const inputBreakdown = estimateInputTokens(r.docsRead);
const outputTokens = Math.round(jobBreakdown.total / 4);
const totalTokens = inputBreakdown.total + outputTokens;
@@ -1617,12 +1976,12 @@ function generateHtmlReport(
const jobRows = agg.jobStats
? `
<tr>
- <td><strong>Component Routing</strong><br><span class="job-desc">Import statements for XDS components</span></td>
+ <td><strong>Library Imports</strong><br><span class="job-desc">Import statements for design system components</span></td>
<td>${agg.jobStats.percentages.componentRouting}%</td>
<td>~${Math.round(tu.output.total.componentRouting / 4)}</td>
</tr>
<tr>
- <td><strong>Component Config</strong><br><span class="job-desc">Props and attributes on XDS components</span></td>
+ <td><strong>Component Config</strong><br><span class="job-desc">Props and attributes on components</span></td>
<td>${agg.jobStats.percentages.componentConfig}%</td>
<td>~${Math.round(tu.output.total.componentConfig / 4)}</td>
</tr>
@@ -1652,7 +2011,7 @@ function generateHtmlReport(
// Input token descriptions
const inputRows = `
<tr>
- <td><strong>AGENTS.md</strong><br><span class="job-desc">Component catalog and XDS guidance</span></td>
+ <td><strong>Agent Docs</strong><br><span class="job-desc">Component catalog and design system guidance</span></td>
<td>${tu.input.total.agentsMd}</td>
</tr>
<tr>
@@ -1702,6 +2061,74 @@ function generateHtmlReport(
`;
}
+ // Generate quality assessment HTML if present
+ let qualityHtml = '';
+ if (agg.quality) {
+ const q = agg.quality;
+ const scoreBar = (good: number, needsWork: number, poor: number) => {
+ const total = good + needsWork + poor;
+ if (total === 0) return '';
+ return `
+ <div class="score-bar">
+ <span class="score good" style="width: ${(good / total) * 100}%"></span>
+ <span class="score needs-work" style="width: ${(needsWork / total) * 100}%"></span>
+ <span class="score poor" style="width: ${(poor / total) * 100}%"></span>
+ </div>
+ `;
+ };
+
+ qualityHtml = `
+ <div class="card">
+ <h2>πŸ”¬ Quality Assessment</h2>
+ <p style="color: #666; font-size: 0.9em;">${q.assessed} of ${agg.totalTests} tests assessed by quality agent.</p>
+
+ <div class="quality-grid">
+ <div class="quality-stat">
+ <div class="quality-label">Overall</div>
+ ${scoreBar(q.byScore.good, q.byScore['needs-work'], q.byScore.poor)}
+ <div class="quality-counts">
+ <span class="score-label good">βœ“ ${q.byScore.good} Good</span>
+ <span class="score-label needs-work">⚠ ${q.byScore['needs-work']} Needs Work</span>
+ <span class="score-label poor">βœ— ${q.byScore.poor} Poor</span>
+ </div>
+ </div>
+ </div>
+
+ <table style="margin-top: 16px;">
+ <thead>
+ <tr><th>Category</th><th>Good</th><th>Needs Work</th><th>Poor</th><th>Issues</th><th>Critical</th></tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>β™Ώ Accessibility</td>
+ <td style="color: #16a34a;">${q.accessibility.byScore.good}</td>
+ <td style="color: #ca8a04;">${q.accessibility.byScore['needs-work']}</td>
+ <td style="color: #dc2626;">${q.accessibility.byScore.poor}</td>
+ <td>${q.accessibility.totalIssues}</td>
+ <td style="color: ${q.accessibility.criticalIssues > 0 ? '#dc2626' : '#666'};">${q.accessibility.criticalIssues}</td>
+ </tr>
+ <tr>
+ <td>🎨 Design System</td>
+ <td style="color: #16a34a;">${q.designSystem.byScore.good}</td>
+ <td style="color: #ca8a04;">${q.designSystem.byScore['needs-work']}</td>
+ <td style="color: #dc2626;">${q.designSystem.byScore.poor}</td>
+ <td>${q.designSystem.totalIssues}</td>
+ <td style="color: ${q.designSystem.criticalIssues > 0 ? '#dc2626' : '#666'};">${q.designSystem.criticalIssues}</td>
+ </tr>
+ <tr>
+ <td>πŸ”§ Code Quality</td>
+ <td style="color: #16a34a;">${q.codeQuality.byScore.good}</td>
+ <td style="color: #ca8a04;">${q.codeQuality.byScore['needs-work']}</td>
+ <td style="color: #dc2626;">${q.codeQuality.byScore.poor}</td>
+ <td>${q.codeQuality.totalIssues}</td>
+ <td style="color: ${q.codeQuality.criticalIssues > 0 ? '#dc2626' : '#666'};">${q.codeQuality.criticalIssues}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ `;
+ }
+
return `<!DOCTYPE html>
<html lang="en">
<head>
@@ -1785,6 +2212,19 @@ function generateHtmlReport(
.badge.effort-significant { background: #fee2e2; color: #dc2626; }
.docs-cell { max-width: 200px; }
.job-desc { font-size: 0.8em; color: #666; font-weight: normal; }
+ .quality-grid { display: flex; gap: 16px; flex-wrap: wrap; }
+ .quality-stat { flex: 1; min-width: 200px; }
+ .quality-label { font-weight: 600; margin-bottom: 8px; }
+ .score-bar { display: flex; width: 100%; height: 12px; border-radius: 6px; overflow: hidden; background: #e5e7eb; }
+ .score-bar .score { height: 100%; }
+ .score-bar .score.good { background: #22c55e; }
+ .score-bar .score.needs-work { background: #eab308; }
+ .score-bar .score.poor { background: #ef4444; }
+ .quality-counts { margin-top: 8px; font-size: 0.85em; }
+ .score-label { margin-right: 12px; }
+ .score-label.good { color: #16a34a; }
+ .score-label.needs-work { color: #ca8a04; }
+ .score-label.poor { color: #dc2626; }
tr.tier-gold { background: #fffbeb; }
tr.tier-green { background: #f0fdf4; }
tr.tier-yellow { background: #fefce8; }
@@ -1842,7 +2282,7 @@ function generateHtmlReport(
</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
+ Gold = Pure design system | Green = Acceptable escape hatches | Yellow = Anti-patterns (break theming) | Red = Critical failures
</p>
</div>
@@ -1877,6 +2317,8 @@ function generateHtmlReport(
${tokenUsageHtml}
+ ${qualityHtml}
+
${degradationGraphHtml}
${
diff --git a/internal/vibe-tests/src/compare.ts b/internal/vibe-tests/src/compare.ts
new file mode 100644
index 0000000000..f1dd3b6bd6
--- /dev/null
+++ b/internal/vibe-tests/src/compare.ts
@@ -0,0 +1,634 @@
+#!/usr/bin/env tsx
+/**
+ * @file Comparison Report Generator
+ * @description Generates side-by-side comparison of XDS vs baseline quality assessments
+ *
+ * Usage:
+ * yarn workspace @xds/vibe-tests compare --xds <id> --baseline <id>
+ */
+
+import fs from 'fs';
+import path from 'path';
+import type {QualityAssessment} from './types.js';
+
+const RESULTS_DIR = path.join(import.meta.dirname, '..', 'results');
+
+interface ComparisonResult {
+ promptId: string;
+ xds: QualityAssessment | null;
+ baseline: QualityAssessment | null;
+}
+
+interface AggregateData {
+ iterationId: string;
+ totalTests: number;
+ successCount: number;
+ successRate: number;
+ tiers?: {
+ gold: number;
+ green: number;
+ yellow: number;
+ red: number;
+ };
+ totalDurationMs?: number;
+ avgDurationMs?: number;
+ tokenUsage?: {
+ input: {total: number};
+ output: {total: number};
+ grandTotal: number;
+ };
+ quality?: {
+ assessed: number;
+ byScore: Record<string, number>;
+ accessibility: {totalIssues: number; criticalIssues: number};
+ designSystem: {totalIssues: number; criticalIssues: number};
+ codeQuality: {totalIssues: number; criticalIssues: number};
+ };
+}
+
+function loadAggregate(iterationId: string): AggregateData | null {
+ const filePath = path.join(RESULTS_DIR, iterationId, 'aggregate.json');
+ if (!fs.existsSync(filePath)) {
+ return null;
+ }
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+}
+
+function loadQualityAssessment(
+ iterationId: string,
+ promptId: string,
+): QualityAssessment | null {
+ const filePath = path.join(
+ RESULTS_DIR,
+ iterationId,
+ 'results',
+ `${promptId}.quality.json`,
+ );
+ if (!fs.existsSync(filePath)) {
+ return null;
+ }
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+}
+
+function loadPromptIds(iterationId: string): string[] {
+ const manifestPath = path.join(RESULTS_DIR, iterationId, 'manifest.json');
+ if (!fs.existsSync(manifestPath)) {
+ return [];
+ }
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
+ return manifest.prompts.map((p: {id: string}) => p.id);
+}
+
+function severityIcon(severity: string): string {
+ switch (severity) {
+ case 'critical':
+ return 'πŸ”΄';
+ case 'moderate':
+ return '🟑';
+ case 'minor':
+ return 'βšͺ';
+ default:
+ return 'β€’';
+ }
+}
+
+function scoreIcon(score: string): string {
+ switch (score) {
+ case 'good':
+ return 'βœ…';
+ case 'needs-work':
+ return '⚠️';
+ case 'poor':
+ return '❌';
+ default:
+ return '❓';
+ }
+}
+
+function formatIssues(
+ issues: Array<{severity: string; issue: string}>,
+ indent: string = ' ',
+): string {
+ if (issues.length === 0) return `${indent}(no issues)`;
+ return issues
+ .map(i => `${indent}${severityIcon(i.severity)} ${i.issue}`)
+ .join('\n');
+}
+
+function formatTime(ms: number): string {
+ const seconds = ms / 1000;
+ if (seconds < 60) return `${seconds.toFixed(1)}s`;
+ const minutes = Math.floor(seconds / 60);
+ const secs = seconds % 60;
+ return `${minutes}m ${secs.toFixed(0)}s`;
+}
+
+function generateComparisonReport(
+ xdsIteration: string,
+ baselineIteration: string,
+): string {
+ const lines: string[] = [];
+
+ lines.push(
+ '═══════════════════════════════════════════════════════════════════════════',
+ );
+ lines.push(' VIBE TEST COMPARISON REPORT');
+ lines.push(
+ ` XDS (${xdsIteration}) vs Baseline (${baselineIteration})`,
+ );
+ lines.push(
+ '═══════════════════════════════════════════════════════════════════════════',
+ );
+ lines.push('');
+
+ // Load aggregate data
+ const xdsAgg = loadAggregate(xdsIteration);
+ const baselineAgg = loadAggregate(baselineIteration);
+
+ // ===== METRICS SUMMARY =====
+ lines.push('πŸ“Š METRICS SUMMARY');
+ lines.push(
+ '───────────────────────────────────────────────────────────────────────────',
+ );
+ lines.push('');
+ lines.push(
+ 'β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”',
+ );
+ lines.push(
+ 'β”‚ Metric β”‚ XDS β”‚ Baseline β”‚ Winner β”‚',
+ );
+ lines.push(
+ 'β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€',
+ );
+
+ // Success Rate
+ const xdsSuccess = xdsAgg
+ ? `${xdsAgg.successRate.toFixed(0)}% (${xdsAgg.successCount}/${xdsAgg.totalTests})`
+ : 'N/A';
+ const baselineSuccess = baselineAgg
+ ? `${baselineAgg.successRate.toFixed(0)}% (${baselineAgg.successCount}/${baselineAgg.totalTests})`
+ : 'N/A';
+ const successWinner =
+ !xdsAgg || !baselineAgg
+ ? 'β€”'
+ : xdsAgg.successRate > baselineAgg.successRate
+ ? 'XDS'
+ : baselineAgg.successRate > xdsAgg.successRate
+ ? 'Baseline'
+ : 'Tie';
+ lines.push(
+ `β”‚ Success Rate β”‚ ${xdsSuccess.padEnd(15)} β”‚ ${baselineSuccess.padEnd(15)} β”‚ ${successWinner.padEnd(8)} β”‚`,
+ );
+
+ // Total Time
+ const xdsTime = xdsAgg?.totalDurationMs
+ ? formatTime(xdsAgg.totalDurationMs)
+ : 'N/A';
+ const baselineTime = baselineAgg?.totalDurationMs
+ ? formatTime(baselineAgg.totalDurationMs)
+ : 'N/A';
+ const timeWinner =
+ !xdsAgg?.totalDurationMs || !baselineAgg?.totalDurationMs
+ ? 'β€”'
+ : xdsAgg.totalDurationMs < baselineAgg.totalDurationMs
+ ? 'XDS'
+ : baselineAgg.totalDurationMs < xdsAgg.totalDurationMs
+ ? 'Baseline'
+ : 'Tie';
+ lines.push(
+ `β”‚ Total Time β”‚ ${xdsTime.padEnd(15)} β”‚ ${baselineTime.padEnd(15)} β”‚ ${timeWinner.padEnd(8)} β”‚`,
+ );
+
+ // Avg Time per Test
+ const xdsAvg = xdsAgg?.avgDurationMs
+ ? formatTime(xdsAgg.avgDurationMs)
+ : 'N/A';
+ const baselineAvg = baselineAgg?.avgDurationMs
+ ? formatTime(baselineAgg.avgDurationMs)
+ : 'N/A';
+ lines.push(
+ `β”‚ Avg Time/Test β”‚ ${xdsAvg.padEnd(15)} β”‚ ${baselineAvg.padEnd(15)} β”‚ ${timeWinner.padEnd(8)} β”‚`,
+ );
+
+ // Input Tokens
+ const xdsInputVal = (xdsAgg?.tokenUsage?.input?.total as {total?: number})
+ ?.total;
+ const baselineInputVal = (
+ baselineAgg?.tokenUsage?.input?.total as {total?: number}
+ )?.total;
+ const xdsInput = xdsInputVal ? xdsInputVal.toLocaleString() : 'N/A';
+ const baselineInput = baselineInputVal
+ ? baselineInputVal.toLocaleString()
+ : 'N/A';
+ const inputWinner =
+ !xdsInputVal || !baselineInputVal
+ ? 'β€”'
+ : xdsInputVal < baselineInputVal
+ ? 'XDS'
+ : baselineInputVal < xdsInputVal
+ ? 'Baseline'
+ : 'Tie';
+ lines.push(
+ `β”‚ Input Tokens β”‚ ${xdsInput.padEnd(15)} β”‚ ${baselineInput.padEnd(15)} β”‚ ${inputWinner.padEnd(8)} β”‚`,
+ );
+
+ // Output Tokens
+ const xdsOutputVal = (xdsAgg?.tokenUsage?.output?.total as {total?: number})
+ ?.total;
+ const baselineOutputVal = (
+ baselineAgg?.tokenUsage?.output?.total as {total?: number}
+ )?.total;
+ const xdsOutput = xdsOutputVal ? xdsOutputVal.toLocaleString() : 'N/A';
+ const baselineOutput = baselineOutputVal
+ ? baselineOutputVal.toLocaleString()
+ : 'N/A';
+ const outputWinner =
+ !xdsOutputVal || !baselineOutputVal
+ ? 'β€”'
+ : xdsOutputVal < baselineOutputVal
+ ? 'XDS'
+ : baselineOutputVal < xdsOutputVal
+ ? 'Baseline'
+ : 'Tie';
+ lines.push(
+ `β”‚ Output Tokens β”‚ ${xdsOutput.padEnd(15)} β”‚ ${baselineOutput.padEnd(15)} β”‚ ${outputWinner.padEnd(8)} β”‚`,
+ );
+
+ lines.push(
+ 'β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜',
+ );
+ lines.push('');
+
+ // ===== QUALITY TIERS =====
+ if (xdsAgg?.tiers || baselineAgg?.tiers) {
+ lines.push('πŸ† QUALITY TIERS');
+ lines.push(
+ '───────────────────────────────────────────────────────────────────────────',
+ );
+ lines.push('');
+ lines.push(
+ 'β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”',
+ );
+ lines.push(
+ 'β”‚ Tier β”‚ XDS β”‚ Baseline β”‚',
+ );
+ lines.push(
+ 'β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€',
+ );
+
+ const tiers = ['gold', 'green', 'yellow', 'red'] as const;
+ const tierLabels = {
+ gold: 'πŸ₯‡ Gold (pure DS)',
+ green: '🟒 Green (acceptable)',
+ yellow: '🟑 Yellow (anti-pattern)',
+ red: 'πŸ”΄ Red (critical)',
+ };
+
+ for (const tier of tiers) {
+ const xdsVal = xdsAgg?.tiers?.[tier] ?? 0;
+ const baselineVal = baselineAgg?.tiers?.[tier] ?? 0;
+ const xdsPct = xdsAgg?.totalTests
+ ? `${xdsVal} (${((xdsVal / xdsAgg.totalTests) * 100).toFixed(0)}%)`
+ : 'N/A';
+ const baselinePct = baselineAgg?.totalTests
+ ? `${baselineVal} (${((baselineVal / baselineAgg.totalTests) * 100).toFixed(0)}%)`
+ : 'N/A';
+ lines.push(
+ `β”‚ ${tierLabels[tier].padEnd(23)} β”‚ ${xdsPct.padEnd(15)} β”‚ ${baselinePct.padEnd(15)} β”‚`,
+ );
+ }
+
+ lines.push(
+ 'β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜',
+ );
+ lines.push('');
+ }
+
+ // ===== QUALITY ASSESSMENT SUMMARY =====
+ if (xdsAgg?.quality || baselineAgg?.quality) {
+ lines.push('πŸ”¬ QUALITY ASSESSMENT SUMMARY');
+ lines.push(
+ '───────────────────────────────────────────────────────────────────────────',
+ );
+ lines.push('');
+ lines.push(
+ 'β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”',
+ );
+ lines.push(
+ 'β”‚ Category β”‚ XDS β”‚ Baseline β”‚ Winner β”‚',
+ );
+ lines.push(
+ 'β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€',
+ );
+
+ // Overall Good scores
+ const xdsGood = xdsAgg?.quality?.byScore?.good ?? 0;
+ const baselineGood = baselineAgg?.quality?.byScore?.good ?? 0;
+ const goodWinner =
+ xdsGood > baselineGood
+ ? 'XDS'
+ : baselineGood > xdsGood
+ ? 'Baseline'
+ : 'Tie';
+ lines.push(
+ `β”‚ βœ… Overall Good β”‚ ${String(xdsGood).padEnd(15)} β”‚ ${String(baselineGood).padEnd(15)} β”‚ ${goodWinner.padEnd(8)} β”‚`,
+ );
+
+ // Needs Work
+ const xdsNeedsWork = xdsAgg?.quality?.byScore?.['needs-work'] ?? 0;
+ const baselineNeedsWork =
+ baselineAgg?.quality?.byScore?.['needs-work'] ?? 0;
+ const needsWorkWinner =
+ xdsNeedsWork < baselineNeedsWork
+ ? 'XDS'
+ : baselineNeedsWork < xdsNeedsWork
+ ? 'Baseline'
+ : 'Tie';
+ lines.push(
+ `β”‚ ⚠️ Needs Work β”‚ ${String(xdsNeedsWork).padEnd(15)} β”‚ ${String(baselineNeedsWork).padEnd(15)} β”‚ ${needsWorkWinner.padEnd(8)} β”‚`,
+ );
+
+ // Poor
+ const xdsPoor = xdsAgg?.quality?.byScore?.poor ?? 0;
+ const baselinePoor = baselineAgg?.quality?.byScore?.poor ?? 0;
+ const poorWinner =
+ xdsPoor < baselinePoor
+ ? 'XDS'
+ : baselinePoor < xdsPoor
+ ? 'Baseline'
+ : 'Tie';
+ lines.push(
+ `β”‚ ❌ Poor β”‚ ${String(xdsPoor).padEnd(15)} β”‚ ${String(baselinePoor).padEnd(15)} β”‚ ${poorWinner.padEnd(8)} β”‚`,
+ );
+
+ lines.push(
+ 'β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€',
+ );
+
+ // A11y Issues
+ const xdsA11y = xdsAgg?.quality?.accessibility;
+ const baselineA11y = baselineAgg?.quality?.accessibility;
+ const xdsA11yStr = xdsA11y
+ ? `${xdsA11y.totalIssues} (${xdsA11y.criticalIssues} crit)`
+ : 'N/A';
+ const baselineA11yStr = baselineA11y
+ ? `${baselineA11y.totalIssues} (${baselineA11y.criticalIssues} crit)`
+ : 'N/A';
+ const a11yWinner =
+ !xdsA11y || !baselineA11y
+ ? 'β€”'
+ : xdsA11y.criticalIssues < baselineA11y.criticalIssues
+ ? 'XDS'
+ : baselineA11y.criticalIssues < xdsA11y.criticalIssues
+ ? 'Baseline'
+ : xdsA11y.totalIssues < baselineA11y.totalIssues
+ ? 'XDS'
+ : baselineA11y.totalIssues < xdsA11y.totalIssues
+ ? 'Baseline'
+ : 'Tie';
+ lines.push(
+ `β”‚ β™Ώ A11y Issues β”‚ ${xdsA11yStr.padEnd(15)} β”‚ ${baselineA11yStr.padEnd(15)} β”‚ ${a11yWinner.padEnd(8)} β”‚`,
+ );
+
+ // Design System Issues
+ const xdsDS = xdsAgg?.quality?.designSystem;
+ const baselineDS = baselineAgg?.quality?.designSystem;
+ const xdsDSStr = xdsDS
+ ? `${xdsDS.totalIssues} (${xdsDS.criticalIssues} crit)`
+ : 'N/A';
+ const baselineDSStr = baselineDS
+ ? `${baselineDS.totalIssues} (${baselineDS.criticalIssues} crit)`
+ : 'N/A';
+ const dsWinner =
+ !xdsDS || !baselineDS
+ ? 'β€”'
+ : xdsDS.totalIssues < baselineDS.totalIssues
+ ? 'XDS'
+ : baselineDS.totalIssues < xdsDS.totalIssues
+ ? 'Baseline'
+ : 'Tie';
+ lines.push(
+ `β”‚ 🎨 Design System Issues β”‚ ${xdsDSStr.padEnd(15)} β”‚ ${baselineDSStr.padEnd(15)} β”‚ ${dsWinner.padEnd(8)} β”‚`,
+ );
+
+ // Code Quality Issues
+ const xdsCQ = xdsAgg?.quality?.codeQuality;
+ const baselineCQ = baselineAgg?.quality?.codeQuality;
+ const xdsCQStr = xdsCQ
+ ? `${xdsCQ.totalIssues} (${xdsCQ.criticalIssues} crit)`
+ : 'N/A';
+ const baselineCQStr = baselineCQ
+ ? `${baselineCQ.totalIssues} (${baselineCQ.criticalIssues} crit)`
+ : 'N/A';
+ const cqWinner =
+ !xdsCQ || !baselineCQ
+ ? 'β€”'
+ : xdsCQ.totalIssues < baselineCQ.totalIssues
+ ? 'XDS'
+ : baselineCQ.totalIssues < xdsCQ.totalIssues
+ ? 'Baseline'
+ : 'Tie';
+ lines.push(
+ `β”‚ πŸ’» Code Quality Issues β”‚ ${xdsCQStr.padEnd(15)} β”‚ ${baselineCQStr.padEnd(15)} β”‚ ${cqWinner.padEnd(8)} β”‚`,
+ );
+
+ lines.push(
+ 'β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜',
+ );
+ lines.push('');
+ }
+
+ // Get prompt IDs from both iterations
+ const xdsPrompts = loadPromptIds(xdsIteration);
+ const baselinePrompts = loadPromptIds(baselineIteration);
+ const allPrompts = [...new Set([...xdsPrompts, ...baselinePrompts])];
+
+ // ===== PER-TEST QUALITY SCORES =====
+ lines.push('πŸ“ PER-TEST QUALITY SCORES');
+ lines.push('───────────────────────────────────────────────────────────────');
+ lines.push(
+ 'β”‚ Test β”‚ Category β”‚ XDS Overall β”‚ Baseline Overall β”‚ Winner β”‚',
+ );
+ lines.push(
+ 'β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€',
+ );
+
+ const results: ComparisonResult[] = [];
+ let xdsWins = 0;
+ let baselineWins = 0;
+ let ties = 0;
+
+ for (const promptId of allPrompts) {
+ const xds = loadQualityAssessment(xdsIteration, promptId);
+ const baseline = loadQualityAssessment(baselineIteration, promptId);
+ results.push({promptId, xds, baseline});
+
+ const xdsScore = xds?.overallScore || 'N/A';
+ const baselineScore = baseline?.overallScore || 'N/A';
+
+ let winner = 'β€”';
+ if (xdsScore === 'good' && baselineScore !== 'good') {
+ winner = 'XDS';
+ xdsWins++;
+ } else if (baselineScore === 'good' && xdsScore !== 'good') {
+ winner = 'Baseline';
+ baselineWins++;
+ } else if (xdsScore === baselineScore) {
+ winner = 'Tie';
+ ties++;
+ } else if (xdsScore === 'needs-work' && baselineScore === 'poor') {
+ winner = 'XDS';
+ xdsWins++;
+ } else if (baselineScore === 'needs-work' && xdsScore === 'poor') {
+ winner = 'Baseline';
+ baselineWins++;
+ } else {
+ ties++;
+ }
+
+ // Get category from manifest
+ const manifestPath = path.join(RESULTS_DIR, xdsIteration, 'manifest.json');
+ let category = '';
+ if (fs.existsSync(manifestPath)) {
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
+ const prompt = manifest.prompts.find(
+ (p: {id: string}) => p.id === promptId,
+ );
+ category = prompt?.category || '';
+ }
+
+ lines.push(
+ `β”‚ ${promptId.padEnd(7)} β”‚ ${category.padEnd(14)} β”‚ ${scoreIcon(xdsScore)} ${xdsScore.padEnd(9)} β”‚ ${scoreIcon(baselineScore)} ${baselineScore.padEnd(14)} β”‚ ${winner.padEnd(6)} β”‚`,
+ );
+ }
+
+ lines.push(
+ 'β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜',
+ );
+ lines.push('');
+ lines.push(
+ `Totals: XDS wins: ${xdsWins}, Baseline wins: ${baselineWins}, Ties: ${ties}`,
+ );
+ lines.push('');
+
+ // Detailed breakdown
+ lines.push('═══════════════════════════════════════════════════════════════');
+ lines.push(' DETAILED BREAKDOWN');
+ lines.push('═══════════════════════════════════════════════════════════════');
+
+ for (const result of results) {
+ lines.push('');
+ lines.push(
+ `β”Œβ”€β”€β”€ ${result.promptId} ───────────────────────────────────────────────┐`,
+ );
+ lines.push('');
+
+ // Accessibility comparison
+ lines.push(' πŸ“‹ ACCESSIBILITY');
+ lines.push(' ────────────────');
+ lines.push(
+ ` XDS: ${scoreIcon(result.xds?.accessibility.score || 'N/A')} ${result.xds?.accessibility.score || 'N/A'}`,
+ );
+ if (result.xds?.accessibility.issues.length) {
+ lines.push(formatIssues(result.xds.accessibility.issues));
+ }
+ lines.push('');
+ lines.push(
+ ` Baseline: ${scoreIcon(result.baseline?.accessibility.score || 'N/A')} ${result.baseline?.accessibility.score || 'N/A'}`,
+ );
+ if (result.baseline?.accessibility.issues.length) {
+ lines.push(formatIssues(result.baseline.accessibility.issues));
+ }
+ lines.push('');
+
+ // Design System comparison
+ lines.push(' 🎨 DESIGN SYSTEM ADHERENCE');
+ lines.push(' ──────────────────────────');
+ lines.push(
+ ` XDS: ${scoreIcon(result.xds?.designSystemAdherence.score || 'N/A')} ${result.xds?.designSystemAdherence.score || 'N/A'}`,
+ );
+ if (result.xds?.designSystemAdherence.issues.length) {
+ lines.push(formatIssues(result.xds.designSystemAdherence.issues));
+ }
+ lines.push('');
+ lines.push(
+ ` Baseline: ${scoreIcon(result.baseline?.designSystemAdherence.score || 'N/A')} ${result.baseline?.designSystemAdherence.score || 'N/A'}`,
+ );
+ if (result.baseline?.designSystemAdherence.issues.length) {
+ lines.push(formatIssues(result.baseline.designSystemAdherence.issues));
+ }
+ lines.push('');
+
+ // Code Quality comparison
+ lines.push(' πŸ’» CODE QUALITY');
+ lines.push(' ───────────────');
+ lines.push(
+ ` XDS: ${scoreIcon(result.xds?.codeQuality.score || 'N/A')} ${result.xds?.codeQuality.score || 'N/A'}`,
+ );
+ if (result.xds?.codeQuality.issues.length) {
+ lines.push(formatIssues(result.xds.codeQuality.issues));
+ }
+ lines.push('');
+ lines.push(
+ ` Baseline: ${scoreIcon(result.baseline?.codeQuality.score || 'N/A')} ${result.baseline?.codeQuality.score || 'N/A'}`,
+ );
+ if (result.baseline?.codeQuality.issues.length) {
+ lines.push(formatIssues(result.baseline.codeQuality.issues));
+ }
+ lines.push('');
+ lines.push(
+ 'β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜',
+ );
+ }
+
+ return lines.join('\n');
+}
+
+function printUsage(): void {
+ console.log(`
+Comparison Report Generator
+
+Usage:
+ yarn workspace @xds/vibe-tests compare --xds <id> --baseline <id>
+
+Options:
+ --xds, -x XDS iteration ID (required)
+ --baseline, -b Baseline iteration ID (required)
+ --help, -h Show this help message
+
+Examples:
+ yarn workspace @xds/vibe-tests compare --xds 887c6567 --baseline a3466fd9
+`);
+}
+
+async function main(): Promise<void> {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ printUsage();
+ process.exit(0);
+ }
+
+ // Parse arguments
+ let xdsIteration: string | null = null;
+ let baselineIteration: string | null = null;
+
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--xds' || args[i] === '-x') {
+ xdsIteration = args[++i];
+ } else if (args[i] === '--baseline' || args[i] === '-b') {
+ baselineIteration = args[++i];
+ }
+ }
+
+ if (!xdsIteration || !baselineIteration) {
+ console.error('Error: Both --xds and --baseline are required');
+ printUsage();
+ process.exit(1);
+ }
+
+ const report = generateComparisonReport(xdsIteration, baselineIteration);
+ console.log(report);
+}
+
+main().catch(console.error);
diff --git a/internal/vibe-tests/src/generate-a11y-manifest.ts b/internal/vibe-tests/src/generate-a11y-manifest.ts
new file mode 100644
index 0000000000..125a7e1cbd
--- /dev/null
+++ b/internal/vibe-tests/src/generate-a11y-manifest.ts
@@ -0,0 +1,608 @@
+#!/usr/bin/env tsx
+/**
+ * @file Accessibility Manifest Generator
+ * @description Generates accessibility manifests from official sources for XDS and baseline (Radix/shadcn)
+ *
+ * Usage:
+ * yarn workspace @xds/vibe-tests generate-a11y-manifest
+ *
+ * This script:
+ * 1. Parses XDS component README.md files for accessibility info
+ * 2. Fetches Radix accessibility docs from official sources
+ * 3. Generates structured manifests for fair quality assessment
+ */
+
+import fs from 'fs';
+import path from 'path';
+
+const VIBE_TESTS_DIR = path.join(import.meta.dirname, '..');
+const MANIFESTS_DIR = path.join(VIBE_TESTS_DIR, 'a11y-manifests');
+const XDS_CORE_DIR = path.join(
+ VIBE_TESTS_DIR,
+ '..',
+ '..',
+ 'packages',
+ 'core',
+ 'src',
+);
+
+interface ComponentA11yInfo {
+ component: string;
+ builtIn: string[];
+ keyboard: string[];
+ developerMust: string[];
+ notes: string[];
+}
+
+interface A11yManifest {
+ source: string;
+ generatedAt: string;
+ version: string;
+ components: Record<string, ComponentA11yInfo>;
+}
+
+/**
+ * Parse an XDS component README for accessibility information
+ */
+function parseXDSReadme(readmePath: string): ComponentA11yInfo | null {
+ if (!fs.existsSync(readmePath)) {
+ return null;
+ }
+
+ const content = fs.readFileSync(readmePath, 'utf-8');
+ const componentName = path.basename(path.dirname(readmePath));
+
+ const info: ComponentA11yInfo = {
+ component: componentName,
+ builtIn: [],
+ keyboard: [],
+ developerMust: [],
+ notes: [],
+ };
+
+ // Extract accessibility section
+ const a11yMatch = content.match(
+ /## Accessibility\n\n([\s\S]*?)(?=\n##|\n$|$)/,
+ );
+ if (a11yMatch) {
+ const a11yContent = a11yMatch[1].trim();
+ // Parse the content - could be a list or prose
+ const features = a11yContent
+ .split(/[,.]/)
+ .map(s => s.trim())
+ .filter(Boolean);
+ info.builtIn.push(...features);
+ }
+
+ // Extract keyboard section
+ const keyboardMatch = content.match(
+ /## Keyboard\n\n([\s\S]*?)(?=\n##|\n$|$)/,
+ );
+ if (keyboardMatch) {
+ const keyboardContent = keyboardMatch[1].trim();
+ info.keyboard.push(keyboardContent);
+ }
+
+ // Look for accessibility mentions in Features section
+ const featuresMatch = content.match(/## Features\n\n([\s\S]*?)(?=\n##)/);
+ if (featuresMatch) {
+ const featuresContent = featuresMatch[1];
+ const lines = featuresContent.split('\n');
+ for (const line of lines) {
+ const lower = line.toLowerCase();
+ if (
+ lower.includes('accessible') ||
+ lower.includes('aria') ||
+ lower.includes('screen reader') ||
+ lower.includes('focus') ||
+ lower.includes('keyboard')
+ ) {
+ // Extract the feature description
+ const featureMatch = line.match(/[-*]\s*\*\*([^*]+)\*\*:?\s*(.*)/);
+ if (featureMatch) {
+ info.builtIn.push(`${featureMatch[1]}: ${featureMatch[2]}`.trim());
+ } else {
+ info.builtIn.push(line.replace(/^[-*]\s*/, '').trim());
+ }
+ }
+ }
+ }
+
+ // Look for aria mentions in props table
+ const propsMatch = content.match(/## Props\n\n([\s\S]*?)(?=\n##)/);
+ if (propsMatch) {
+ const propsContent = propsMatch[1];
+ if (propsContent.includes('aria-invalid')) {
+ info.builtIn.push('Sets aria-invalid for error status');
+ }
+ if (propsContent.includes('aria-describedby')) {
+ info.builtIn.push('Uses aria-describedby for descriptions');
+ }
+ if (propsContent.includes('isLabelHidden')) {
+ info.builtIn.push(
+ 'Supports visually hidden labels (still accessible to screen readers)',
+ );
+ }
+ }
+
+ // Look for implementation notes mentioning accessibility
+ const implMatch = content.match(
+ /## Implementation Notes\n\n([\s\S]*?)(?=\n##|$)/,
+ );
+ if (implMatch) {
+ const implContent = implMatch[1];
+ const lines = implContent.split('\n');
+ for (const line of lines) {
+ const lower = line.toLowerCase();
+ if (
+ lower.includes('accessible') ||
+ lower.includes('aria') ||
+ lower.includes('screen reader') ||
+ lower.includes('htmlfor') ||
+ lower.includes('label')
+ ) {
+ info.notes.push(line.replace(/^[-*]\s*/, '').trim());
+ }
+ }
+ }
+
+ // Infer developer responsibilities based on component type
+ if (componentName.includes('Button')) {
+ info.developerMust.push('Provide aria-label for icon-only buttons');
+ info.developerMust.push('Use aria-pressed for toggle buttons');
+ }
+ if (componentName.includes('Input') || componentName.includes('TextArea')) {
+ // These have built-in label support, but note it
+ info.notes.push(
+ 'Label is required prop - component handles label association',
+ );
+ }
+
+ return info.builtIn.length > 0 || info.keyboard.length > 0 ? info : null;
+}
+
+/**
+ * Generate XDS accessibility manifest from component README files
+ */
+function generateXDSManifest(): A11yManifest {
+ const manifest: A11yManifest = {
+ source: 'packages/core/src/*/README.md',
+ generatedAt: new Date().toISOString(),
+ version: '1.0.0',
+ components: {},
+ };
+
+ // Find all component directories with README.md
+ const findReadmes = (dir: string): string[] => {
+ const readmes: string[] = [];
+ if (!fs.existsSync(dir)) return readmes;
+
+ const entries = fs.readdirSync(dir, {withFileTypes: true});
+ for (const entry of entries) {
+ if (entry.name === 'node_modules') continue;
+ const fullPath = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ const readmePath = path.join(fullPath, 'README.md');
+ if (fs.existsSync(readmePath)) {
+ readmes.push(readmePath);
+ }
+ readmes.push(...findReadmes(fullPath));
+ }
+ }
+ return readmes;
+ };
+
+ const readmePaths = findReadmes(XDS_CORE_DIR);
+ console.log(`Found ${readmePaths.length} XDS component README files`);
+
+ for (const readmePath of readmePaths) {
+ const info = parseXDSReadme(readmePath);
+ if (info) {
+ manifest.components[info.component] = info;
+ }
+ }
+
+ return manifest;
+}
+
+/**
+ * Radix component accessibility info (from official docs)
+ * Source: https://www.radix-ui.com/primitives/docs/overview/accessibility
+ */
+const RADIX_A11Y_INFO: Record<string, Omit<ComponentA11yInfo, 'component'>> = {
+ Button: {
+ builtIn: [
+ 'Native button element with proper role',
+ 'Keyboard activation (Enter/Space)',
+ 'Focus management',
+ ],
+ keyboard: ['Enter/Space to activate'],
+ developerMust: [
+ 'Provide aria-label for icon-only buttons',
+ 'Use aria-pressed for toggle buttons',
+ 'Use aria-expanded for buttons that control expandable content',
+ ],
+ notes: ['Based on native <button> element'],
+ },
+ Dialog: {
+ builtIn: [
+ 'Focus trap - focus stays within dialog',
+ 'Escape key closes dialog',
+ 'aria-modal="true" on dialog',
+ 'aria-labelledby pointing to title',
+ 'aria-describedby pointing to description',
+ 'Returns focus to trigger on close',
+ 'Scrolling blocked on body when open',
+ ],
+ keyboard: ['Escape to close', 'Tab/Shift+Tab to navigate within'],
+ developerMust: [
+ 'Provide DialogTitle for aria-labelledby',
+ 'Provide DialogDescription for aria-describedby (or use aria-describedby={undefined})',
+ ],
+ notes: ['WAI-ARIA Dialog pattern'],
+ },
+ DropdownMenu: {
+ builtIn: [
+ 'role="menu" on content',
+ 'role="menuitem" on items',
+ 'Arrow key navigation',
+ 'Typeahead to jump to items',
+ 'Focus returns to trigger on close',
+ 'Escape closes menu',
+ 'Submenu support with proper aria-haspopup',
+ ],
+ keyboard: [
+ 'Arrow Down/Up to navigate',
+ 'Enter/Space to select',
+ 'Escape to close',
+ 'Arrow Right/Left for submenus',
+ 'A-Z for typeahead',
+ ],
+ developerMust: [],
+ notes: ['WAI-ARIA Menu pattern'],
+ },
+ Select: {
+ builtIn: [
+ 'role="combobox" on trigger',
+ 'role="listbox" on content',
+ 'role="option" on items',
+ 'aria-expanded on trigger',
+ 'aria-activedescendant for focus',
+ 'Arrow key navigation',
+ 'Typeahead support',
+ ],
+ keyboard: [
+ 'Arrow Down/Up to navigate',
+ 'Enter/Space to select',
+ 'Escape to close',
+ 'A-Z for typeahead',
+ 'Home/End to jump',
+ ],
+ developerMust: ['Provide accessible label (Label component or aria-label)'],
+ notes: ['WAI-ARIA Combobox pattern (Select-Only)'],
+ },
+ Checkbox: {
+ builtIn: [
+ 'role="checkbox"',
+ 'aria-checked state',
+ 'Keyboard activation (Space)',
+ 'Supports indeterminate state',
+ ],
+ keyboard: ['Space to toggle'],
+ developerMust: ['Provide accessible label (Label component or aria-label)'],
+ notes: ['WAI-ARIA Checkbox pattern'],
+ },
+ Switch: {
+ builtIn: [
+ 'role="switch"',
+ 'aria-checked state',
+ 'Keyboard activation (Space)',
+ ],
+ keyboard: ['Space to toggle'],
+ developerMust: ['Provide accessible label (Label component or aria-label)'],
+ notes: ['WAI-ARIA Switch pattern'],
+ },
+ Tabs: {
+ builtIn: [
+ 'role="tablist" on list',
+ 'role="tab" on triggers',
+ 'role="tabpanel" on content',
+ 'aria-selected on active tab',
+ 'Arrow key navigation between tabs',
+ 'Automatic activation on focus (or manual mode)',
+ ],
+ keyboard: [
+ 'Arrow Left/Right to navigate tabs',
+ 'Home/End to jump to first/last tab',
+ 'Tab to move into panel',
+ ],
+ developerMust: [],
+ notes: ['WAI-ARIA Tabs pattern'],
+ },
+ Tooltip: {
+ builtIn: [
+ 'aria-describedby linking trigger to content',
+ 'Escape to dismiss',
+ 'Delay before showing (configurable)',
+ 'Touch-friendly behavior',
+ ],
+ keyboard: ['Escape to dismiss'],
+ developerMust: [
+ 'Ensure trigger is focusable (use asChild with focusable element)',
+ ],
+ notes: ['Content should be supplementary, not essential'],
+ },
+ Popover: {
+ builtIn: [
+ 'Focus management',
+ 'Escape to close',
+ 'Click outside to close',
+ 'aria-haspopup on trigger',
+ ],
+ keyboard: ['Escape to close', 'Tab to navigate within'],
+ developerMust: ['Manage focus appropriately within popover content'],
+ notes: ['Non-modal by default - focus is not trapped'],
+ },
+ AlertDialog: {
+ builtIn: [
+ 'Focus trap',
+ 'aria-modal="true"',
+ 'role="alertdialog"',
+ 'aria-labelledby pointing to title',
+ 'aria-describedby pointing to description',
+ 'Escape is disabled by default (requires explicit action)',
+ ],
+ keyboard: ['Tab/Shift+Tab to navigate within'],
+ developerMust: [
+ 'Provide AlertDialogTitle',
+ 'Provide AlertDialogDescription',
+ 'Include at least one focusable action button',
+ ],
+ notes: ['WAI-ARIA AlertDialog pattern - for important interruptions'],
+ },
+ Progress: {
+ builtIn: [
+ 'role="progressbar"',
+ 'aria-valuenow',
+ 'aria-valuemin',
+ 'aria-valuemax',
+ ],
+ keyboard: [],
+ developerMust: ['Provide aria-label or aria-labelledby for context'],
+ notes: ['Use aria-valuetext for non-percentage values'],
+ },
+ Slider: {
+ builtIn: [
+ 'role="slider"',
+ 'aria-valuenow, aria-valuemin, aria-valuemax',
+ 'Arrow key adjustment',
+ 'Home/End for min/max',
+ 'Page Up/Down for larger steps',
+ ],
+ keyboard: [
+ 'Arrow Left/Down to decrease',
+ 'Arrow Right/Up to increase',
+ 'Home for minimum',
+ 'End for maximum',
+ 'Page Up/Down for larger steps',
+ ],
+ developerMust: ['Provide aria-label for context'],
+ notes: ['WAI-ARIA Slider pattern'],
+ },
+ Accordion: {
+ builtIn: [
+ 'role="region" on panels (when expanded)',
+ 'aria-expanded on triggers',
+ 'aria-controls linking trigger to panel',
+ 'Arrow key navigation between triggers',
+ ],
+ keyboard: [
+ 'Enter/Space to toggle',
+ 'Arrow Down/Up to navigate',
+ 'Home/End to jump',
+ ],
+ developerMust: [],
+ notes: ['WAI-ARIA Accordion pattern'],
+ },
+ RadioGroup: {
+ builtIn: [
+ 'role="radiogroup"',
+ 'role="radio" on items',
+ 'aria-checked state',
+ 'Arrow key navigation',
+ 'Roving tabindex',
+ ],
+ keyboard: ['Arrow keys to navigate and select', 'Tab to enter/leave group'],
+ developerMust: ['Provide aria-label or aria-labelledby on group'],
+ notes: ['WAI-ARIA Radio Group pattern'],
+ },
+ Label: {
+ builtIn: [
+ 'Native label element',
+ 'Click on label focuses associated control',
+ 'Proper htmlFor association',
+ ],
+ keyboard: [],
+ developerMust: [],
+ notes: ['Always use with form controls'],
+ },
+ Input: {
+ builtIn: ['Native input element'],
+ keyboard: [],
+ developerMust: [
+ 'Provide accessible label (Label component, aria-label, or aria-labelledby)',
+ 'Use aria-describedby for error/help text',
+ 'Set aria-invalid for error states',
+ ],
+ notes: ['shadcn Input is a styled native input'],
+ },
+ Card: {
+ builtIn: [],
+ keyboard: [],
+ developerMust: [
+ 'If clickable, use button or link element, not onClick on div',
+ 'Provide appropriate role if interactive',
+ ],
+ notes: ['Card is purely visual - has no semantic meaning'],
+ },
+ Badge: {
+ builtIn: [],
+ keyboard: [],
+ developerMust: [
+ 'Provide context via aria-label or surrounding text',
+ 'For status badges, consider aria-live for dynamic updates',
+ ],
+ notes: ['Badge is purely visual - has no semantic meaning'],
+ },
+ Avatar: {
+ builtIn: [],
+ keyboard: [],
+ developerMust: [
+ 'Provide alt text on AvatarImage',
+ 'AvatarFallback provides fallback for screen readers',
+ ],
+ notes: ['Decorative avatars should have empty alt=""'],
+ },
+ Skeleton: {
+ builtIn: [],
+ keyboard: [],
+ developerMust: [
+ 'Provide aria-busy="true" on parent container',
+ 'Consider aria-live region for loading announcements',
+ ],
+ notes: [
+ 'Skeleton is decorative - loading state should be announced separately',
+ ],
+ },
+ Table: {
+ builtIn: [
+ 'Native table element with proper structure',
+ 'th elements for headers',
+ 'Proper table semantics',
+ ],
+ keyboard: [],
+ developerMust: [
+ 'Use TableCaption for table description',
+ 'Use scope="col" or scope="row" on headers',
+ ],
+ notes: ['Use native table semantics, avoid role="presentation"'],
+ },
+};
+
+/**
+ * Generate baseline (Radix/shadcn) accessibility manifest
+ */
+function generateBaselineManifest(): A11yManifest {
+ const manifest: A11yManifest = {
+ source: 'https://www.radix-ui.com/primitives/docs/overview/accessibility',
+ generatedAt: new Date().toISOString(),
+ version: '1.0.0',
+ components: {},
+ };
+
+ for (const [name, info] of Object.entries(RADIX_A11Y_INFO)) {
+ manifest.components[name] = {
+ component: name,
+ ...info,
+ };
+ }
+
+ return manifest;
+}
+
+/**
+ * Format manifest as markdown for review
+ */
+function formatManifestAsMarkdown(
+ manifest: A11yManifest,
+ title: string,
+): string {
+ const lines: string[] = [];
+ lines.push(`# ${title} Accessibility Manifest`);
+ lines.push('');
+ lines.push(`**Source:** ${manifest.source}`);
+ lines.push(`**Generated:** ${manifest.generatedAt}`);
+ lines.push('');
+
+ for (const [name, info] of Object.entries(manifest.components)) {
+ lines.push(`## ${name}`);
+ lines.push('');
+
+ if (info.builtIn.length > 0) {
+ lines.push('**Built-in accessibility:**');
+ for (const feature of info.builtIn) {
+ lines.push(`- ${feature}`);
+ }
+ lines.push('');
+ }
+
+ if (info.keyboard.length > 0) {
+ lines.push('**Keyboard:**');
+ for (const feature of info.keyboard) {
+ lines.push(`- ${feature}`);
+ }
+ lines.push('');
+ }
+
+ if (info.developerMust.length > 0) {
+ lines.push('**Developer must provide:**');
+ for (const req of info.developerMust) {
+ lines.push(`- ${req}`);
+ }
+ lines.push('');
+ }
+
+ if (info.notes.length > 0) {
+ lines.push('**Notes:**');
+ for (const note of info.notes) {
+ lines.push(`- ${note}`);
+ }
+ lines.push('');
+ }
+ }
+
+ return lines.join('\n');
+}
+
+async function main(): Promise<void> {
+ // Ensure manifests directory exists
+ if (!fs.existsSync(MANIFESTS_DIR)) {
+ fs.mkdirSync(MANIFESTS_DIR, {recursive: true});
+ }
+
+ console.log('Generating accessibility manifests...\n');
+
+ // Generate XDS manifest
+ console.log('πŸ“¦ Parsing XDS component README files...');
+ const xdsManifest = generateXDSManifest();
+ const xdsJsonPath = path.join(MANIFESTS_DIR, 'xds.json');
+ const xdsMdPath = path.join(MANIFESTS_DIR, 'xds.md');
+ fs.writeFileSync(xdsJsonPath, JSON.stringify(xdsManifest, null, 2));
+ fs.writeFileSync(xdsMdPath, formatManifestAsMarkdown(xdsManifest, 'XDS'));
+ console.log(
+ ` βœ“ Found ${Object.keys(xdsManifest.components).length} components with a11y info`,
+ );
+ console.log(` βœ“ Written to ${xdsJsonPath}`);
+ console.log(` βœ“ Markdown: ${xdsMdPath}`);
+
+ // Generate baseline manifest
+ console.log('\nπŸ“¦ Generating baseline (Radix/shadcn) manifest...');
+ const baselineManifest = generateBaselineManifest();
+ const baselineJsonPath = path.join(MANIFESTS_DIR, 'baseline.json');
+ const baselineMdPath = path.join(MANIFESTS_DIR, 'baseline.md');
+ fs.writeFileSync(baselineJsonPath, JSON.stringify(baselineManifest, null, 2));
+ fs.writeFileSync(
+ baselineMdPath,
+ formatManifestAsMarkdown(baselineManifest, 'Baseline (Radix/shadcn)'),
+ );
+ console.log(
+ ` βœ“ Documented ${Object.keys(baselineManifest.components).length} components`,
+ );
+ console.log(` βœ“ Written to ${baselineJsonPath}`);
+ console.log(` βœ“ Markdown: ${baselineMdPath}`);
+
+ console.log('\nβœ… Done! Manifests are ready for quality assessment.');
+ console.log('\nNext: Update quality-agent.ts to use these manifests.');
+}
+
+main().catch(console.error);
diff --git a/internal/vibe-tests/src/interactive.ts b/internal/vibe-tests/src/interactive.ts
index a81ea780ae..611d7f3d49 100644
--- a/internal/vibe-tests/src/interactive.ts
+++ b/internal/vibe-tests/src/interactive.ts
@@ -27,6 +27,654 @@ import {
const __dirname = path.dirname(fileURLToPath(import.meta.url));
+/**
+ * Install baseline docs (.baseline-docs/) for agent documentation
+ */
+function installBaselineDocs(): void {
+ const vibeTestsDir = path.join(__dirname, '..');
+ const baselineDocsDir = path.join(vibeTestsDir, '.baseline-docs');
+ const agentsMdPath = path.join(vibeTestsDir, 'AGENTS.baseline.md');
+
+ // Check if docs already exist and are recent
+ if (fs.existsSync(baselineDocsDir) && fs.existsSync(agentsMdPath)) {
+ const stats = fs.statSync(agentsMdPath);
+ const ageMs = Date.now() - stats.mtimeMs;
+ if (ageMs < 60 * 60 * 1000) {
+ return; // Less than 1 hour old, skip regeneration
+ }
+ }
+
+ console.log('Installing baseline documentation...');
+ ensureDir(baselineDocsDir);
+
+ // Generate AGENTS.baseline.md
+ const agentsMd = `# AGENTS.md
+
+Project-specific guidance for AI coding agents.
+
+<!-- SHADCN:START -->
+[baseline/ui Component Library]|root: ./.baseline-docs
+|IMPORTANT: Prefer retrieval-led reasoning. Read docs from .baseline-docs/ before generating baseline code.
+|principles.md: Key patterns, cn() utility, Tailwind usage
+|tokens.md: Tailwind theme configuration
+|layout: Card|Separator|Sheet|Tabs|ScrollArea|Collapsible|Resizable
+|components: Button|Input|Label|Checkbox|Select|Switch|Slider|Textarea|Avatar|Badge|Calendar|Command|Dialog|DropdownMenu|HoverCard|Popover|Tooltip|Progress|Skeleton|Table|Toast
+|theme: CSS variables via globals.css, dark mode via class strategy
+|For component API: read .baseline-docs/{ComponentName}.md
+<!-- SHADCN:END -->
+`;
+ fs.writeFileSync(agentsMdPath, agentsMd);
+
+ // Generate principles.md
+ fs.writeFileSync(
+ path.join(baselineDocsDir, 'principles.md'),
+ `# baseline/ui Principles
+
+## Key Patterns
+
+### cn() utility
+Use \`cn()\` for conditional class merging:
+\`\`\`tsx
+import { cn } from "@/lib/utils"
+<div className={cn("base-class", isActive && "active-class")} />
+\`\`\`
+
+### Component Structure
+Components are copied into your project at \`components/ui/\`. Import from there:
+\`\`\`tsx
+import { Button } from "@/components/ui/button"
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
+\`\`\`
+
+### Tailwind First
+All styling uses Tailwind utility classes. No CSS modules or styled-components.
+
+### Composition over Configuration
+Components are unstyled primitives. Compose them with Tailwind classes.
+
+## cva (Class Variance Authority)
+Define variants with cva:
+\`\`\`tsx
+const buttonVariants = cva(
+ "inline-flex items-center justify-center rounded-md text-sm font-medium",
+ {
+ variants: {
+ variant: {
+ default: "bg-primary text-primary-foreground hover:bg-primary/90",
+ destructive: "bg-destructive text-destructive-foreground",
+ outline: "border border-input bg-background hover:bg-accent",
+ secondary: "bg-secondary text-secondary-foreground",
+ ghost: "hover:bg-accent hover:text-accent-foreground",
+ link: "text-primary underline-offset-4 hover:underline",
+ },
+ size: {
+ default: "h-10 px-4 py-2",
+ sm: "h-9 rounded-md px-3",
+ lg: "h-11 rounded-md px-8",
+ icon: "h-10 w-10",
+ },
+ },
+ }
+)
+\`\`\`
+
+## Anti-patterns
+- Don't use inline style objects (use Tailwind)
+- Don't override component internals with CSS
+- Don't skip the cn() utility for conditional classes
+- Don't hardcode colors (use theme tokens)
+
+## Layout Patterns
+- Use flex/grid with Tailwind: \`flex gap-4\`, \`grid grid-cols-3\`
+- Container with padding: \`container mx-auto px-4\`
+- Stack with gap: \`flex flex-col gap-4\`
+`,
+ );
+
+ // Generate tokens.md
+ fs.writeFileSync(
+ path.join(baselineDocsDir, 'tokens.md'),
+ `# baseline/ui Theme Tokens
+
+## CSS Variables (in globals.css)
+\`\`\`css
+:root {
+ --background: 0 0% 100%;
+ --foreground: 222.2 84% 4.9%;
+ --card: 0 0% 100%;
+ --card-foreground: 222.2 84% 4.9%;
+ --popover: 0 0% 100%;
+ --popover-foreground: 222.2 84% 4.9%;
+ --primary: 222.2 47.4% 11.2%;
+ --primary-foreground: 210 40% 98%;
+ --secondary: 210 40% 96.1%;
+ --secondary-foreground: 222.2 47.4% 11.2%;
+ --muted: 210 40% 96.1%;
+ --muted-foreground: 215.4 16.3% 46.9%;
+ --accent: 210 40% 96.1%;
+ --accent-foreground: 222.2 47.4% 11.2%;
+ --destructive: 0 84.2% 60.2%;
+ --destructive-foreground: 210 40% 98%;
+ --border: 214.3 31.8% 91.4%;
+ --input: 214.3 31.8% 91.4%;
+ --ring: 222.2 84% 4.9%;
+ --radius: 0.5rem;
+}
+\`\`\`
+
+## Usage in Tailwind
+Reference with hsl():
+\`\`\`tsx
+<div className="bg-background text-foreground" />
+<div className="bg-primary text-primary-foreground" />
+<div className="border-border" />
+\`\`\`
+
+## Spacing (Tailwind default scale)
+- p-0, p-1 (0.25rem), p-2 (0.5rem), p-3 (0.75rem), p-4 (1rem)
+- gap-1, gap-2, gap-3, gap-4, gap-6, gap-8
+
+## Border Radius
+- rounded-sm (calc(var(--radius) - 4px))
+- rounded-md (calc(var(--radius) - 2px))
+- rounded-lg (var(--radius))
+- rounded-full
+
+## Typography
+- text-xs, text-sm, text-base, text-lg, text-xl, text-2xl
+- font-normal, font-medium, font-semibold, font-bold
+`,
+ );
+
+ // Generate component docs
+ const componentDocs: Record<string, string> = {
+ Button: `# Button
+
+## Usage
+\`\`\`tsx
+import { Button } from "@/components/ui/button"
+
+<Button>Click me</Button>
+<Button variant="outline">Outline</Button>
+<Button variant="destructive">Delete</Button>
+<Button size="sm">Small</Button>
+<Button size="lg">Large</Button>
+<Button disabled>Disabled</Button>
+\`\`\`
+
+## Props
+- \`variant\`: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link"
+- \`size\`: "default" | "sm" | "lg" | "icon"
+- \`asChild\`: boolean - Merge props onto child element
+
+## With Icons
+\`\`\`tsx
+<Button><Mail className="mr-2 h-4 w-4" /> Login with Email</Button>
+<Button size="icon"><ChevronRight className="h-4 w-4" /></Button>
+\`\`\`
+`,
+ Input: `# Input
+
+## Usage
+\`\`\`tsx
+import { Input } from "@/components/ui/input"
+import { Label } from "@/components/ui/label"
+
+<Input type="email" placeholder="Email" />
+<Input disabled />
+
+<div className="grid w-full max-w-sm items-center gap-1.5">
+ <Label htmlFor="email">Email</Label>
+ <Input type="email" id="email" placeholder="Email" />
+</div>
+\`\`\`
+
+## Props
+Standard HTML input props plus:
+- \`type\`: "text" | "email" | "password" | "number" | etc.
+- \`placeholder\`: string
+- \`disabled\`: boolean
+`,
+ Card: `# Card
+
+## Usage
+\`\`\`tsx
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card"
+
+<Card>
+ <CardHeader>
+ <CardTitle>Card Title</CardTitle>
+ <CardDescription>Card Description</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <p>Card Content</p>
+ </CardContent>
+ <CardFooter>
+ <p>Card Footer</p>
+ </CardFooter>
+</Card>
+\`\`\`
+
+## Subcomponents
+- \`Card\`: Container with border and shadow
+- \`CardHeader\`: Top section for title/description
+- \`CardTitle\`: Heading text
+- \`CardDescription\`: Secondary text
+- \`CardContent\`: Main content area
+- \`CardFooter\`: Bottom section for actions
+`,
+ Table: `# Table
+
+## Usage
+\`\`\`tsx
+import {
+ Table,
+ TableBody,
+ TableCaption,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table"
+
+<Table>
+ <TableCaption>A list of your recent invoices.</TableCaption>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-[100px]">Invoice</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead className="text-right">Amount</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ <TableRow>
+ <TableCell className="font-medium">INV001</TableCell>
+ <TableCell>Paid</TableCell>
+ <TableCell className="text-right">$250.00</TableCell>
+ </TableRow>
+ </TableBody>
+</Table>
+\`\`\`
+
+## Subcomponents
+- \`Table\`: Container
+- \`TableHeader\`: Header section
+- \`TableBody\`: Body section
+- \`TableRow\`: Row container
+- \`TableHead\`: Header cell
+- \`TableCell\`: Body cell
+- \`TableCaption\`: Caption text
+`,
+ Dialog: `# Dialog
+
+## Usage
+\`\`\`tsx
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog"
+
+<Dialog>
+ <DialogTrigger asChild>
+ <Button variant="outline">Open Dialog</Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Are you sure?</DialogTitle>
+ <DialogDescription>
+ This action cannot be undone.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button type="submit">Confirm</Button>
+ </DialogFooter>
+ </DialogContent>
+</Dialog>
+\`\`\`
+
+## Controlled
+\`\`\`tsx
+const [open, setOpen] = useState(false)
+<Dialog open={open} onOpenChange={setOpen}>...</Dialog>
+\`\`\`
+`,
+ Popover: `# Popover
+
+## Usage
+\`\`\`tsx
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover"
+
+<Popover>
+ <PopoverTrigger asChild>
+ <Button variant="outline">Open popover</Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-80">
+ <div className="grid gap-4">
+ <h4 className="font-medium">Dimensions</h4>
+ <p className="text-sm text-muted-foreground">
+ Set the dimensions for the layer.
+ </p>
+ </div>
+ </PopoverContent>
+</Popover>
+\`\`\`
+
+## Props (PopoverContent)
+- \`align\`: "start" | "center" | "end"
+- \`side\`: "top" | "right" | "bottom" | "left"
+- \`sideOffset\`: number (default 4)
+`,
+ Select: `# Select
+
+## Usage
+\`\`\`tsx
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select"
+
+<Select>
+ <SelectTrigger className="w-[180px]">
+ <SelectValue placeholder="Select a fruit" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="apple">Apple</SelectItem>
+ <SelectItem value="banana">Banana</SelectItem>
+ <SelectItem value="orange">Orange</SelectItem>
+ </SelectContent>
+</Select>
+\`\`\`
+
+## Controlled
+\`\`\`tsx
+const [value, setValue] = useState("")
+<Select value={value} onValueChange={setValue}>...</Select>
+\`\`\`
+`,
+ Checkbox: `# Checkbox
+
+## Usage
+\`\`\`tsx
+import { Checkbox } from "@/components/ui/checkbox"
+import { Label } from "@/components/ui/label"
+
+<div className="flex items-center space-x-2">
+ <Checkbox id="terms" />
+ <Label htmlFor="terms">Accept terms and conditions</Label>
+</div>
+\`\`\`
+
+## Controlled
+\`\`\`tsx
+const [checked, setChecked] = useState(false)
+<Checkbox checked={checked} onCheckedChange={setChecked} />
+\`\`\`
+
+## Props
+- \`checked\`: boolean | "indeterminate"
+- \`onCheckedChange\`: (checked: boolean) => void
+- \`disabled\`: boolean
+`,
+ Badge: `# Badge
+
+## Usage
+\`\`\`tsx
+import { Badge } from "@/components/ui/badge"
+
+<Badge>Badge</Badge>
+<Badge variant="secondary">Secondary</Badge>
+<Badge variant="outline">Outline</Badge>
+<Badge variant="destructive">Destructive</Badge>
+\`\`\`
+
+## Props
+- \`variant\`: "default" | "secondary" | "destructive" | "outline"
+`,
+ Tabs: `# Tabs
+
+## Usage
+\`\`\`tsx
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
+
+<Tabs defaultValue="account" className="w-[400px]">
+ <TabsList>
+ <TabsTrigger value="account">Account</TabsTrigger>
+ <TabsTrigger value="password">Password</TabsTrigger>
+ </TabsList>
+ <TabsContent value="account">Account settings here.</TabsContent>
+ <TabsContent value="password">Change password here.</TabsContent>
+</Tabs>
+\`\`\`
+
+## Controlled
+\`\`\`tsx
+const [value, setValue] = useState("account")
+<Tabs value={value} onValueChange={setValue}>...</Tabs>
+\`\`\`
+`,
+ Avatar: `# Avatar
+
+## Usage
+\`\`\`tsx
+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
+
+<Avatar>
+ <AvatarImage src="https://github.com/baseline.png" alt="@baseline" />
+ <AvatarFallback>CN</AvatarFallback>
+</Avatar>
+\`\`\`
+
+## Subcomponents
+- \`Avatar\`: Container
+- \`AvatarImage\`: Image element (with loading states)
+- \`AvatarFallback\`: Shown while image loads or on error
+`,
+ Tooltip: `# Tooltip
+
+## Usage
+\`\`\`tsx
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip"
+
+<TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="outline">Hover</Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Add to library</p>
+ </TooltipContent>
+ </Tooltip>
+</TooltipProvider>
+\`\`\`
+
+## Note
+Wrap your app in \`<TooltipProvider>\` once at the root.
+`,
+ DropdownMenu: `# DropdownMenu
+
+## Usage
+\`\`\`tsx
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu"
+
+<DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline">Open</Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuLabel>My Account</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem>Profile</DropdownMenuItem>
+ <DropdownMenuItem>Settings</DropdownMenuItem>
+ <DropdownMenuItem>Logout</DropdownMenuItem>
+ </DropdownMenuContent>
+</DropdownMenu>
+\`\`\`
+
+## Subcomponents
+- \`DropdownMenuCheckboxItem\`: Checkable item
+- \`DropdownMenuRadioGroup\` / \`DropdownMenuRadioItem\`: Radio items
+- \`DropdownMenuSub\` / \`DropdownMenuSubTrigger\` / \`DropdownMenuSubContent\`: Nested menus
+`,
+ Command: `# Command
+
+A command palette / combobox component (used for search, autocomplete).
+
+## Usage
+\`\`\`tsx
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command"
+
+<Command>
+ <CommandInput placeholder="Type a command or search..." />
+ <CommandList>
+ <CommandEmpty>No results found.</CommandEmpty>
+ <CommandGroup heading="Suggestions">
+ <CommandItem>Calendar</CommandItem>
+ <CommandItem>Search Emoji</CommandItem>
+ <CommandItem>Calculator</CommandItem>
+ </CommandGroup>
+ </CommandList>
+</Command>
+\`\`\`
+
+## With Popover (Combobox pattern)
+\`\`\`tsx
+<Popover>
+ <PopoverTrigger asChild>
+ <Button variant="outline">Select framework...</Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[200px] p-0">
+ <Command>
+ <CommandInput placeholder="Search..." />
+ <CommandList>
+ <CommandEmpty>No framework found.</CommandEmpty>
+ <CommandGroup>
+ <CommandItem onSelect={(value) => setSelected(value)}>
+ React
+ </CommandItem>
+ <CommandItem>Vue</CommandItem>
+ <CommandItem>Svelte</CommandItem>
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+</Popover>
+\`\`\`
+`,
+ Label: `# Label
+
+## Usage
+\`\`\`tsx
+import { Label } from "@/components/ui/label"
+import { Input } from "@/components/ui/input"
+
+<div className="grid w-full max-w-sm items-center gap-1.5">
+ <Label htmlFor="email">Email</Label>
+ <Input type="email" id="email" placeholder="Email" />
+</div>
+\`\`\`
+
+## Props
+- \`htmlFor\`: string - Associates with input id
+`,
+ Switch: `# Switch
+
+## Usage
+\`\`\`tsx
+import { Switch } from "@/components/ui/switch"
+import { Label } from "@/components/ui/label"
+
+<div className="flex items-center space-x-2">
+ <Switch id="airplane-mode" />
+ <Label htmlFor="airplane-mode">Airplane Mode</Label>
+</div>
+\`\`\`
+
+## Controlled
+\`\`\`tsx
+const [checked, setChecked] = useState(false)
+<Switch checked={checked} onCheckedChange={setChecked} />
+\`\`\`
+`,
+ Progress: `# Progress
+
+## Usage
+\`\`\`tsx
+import { Progress } from "@/components/ui/progress"
+
+<Progress value={33} />
+<Progress value={66} className="w-[60%]" />
+\`\`\`
+
+## Props
+- \`value\`: number (0-100)
+`,
+ Skeleton: `# Skeleton
+
+## Usage
+\`\`\`tsx
+import { Skeleton } from "@/components/ui/skeleton"
+
+<div className="flex items-center space-x-4">
+ <Skeleton className="h-12 w-12 rounded-full" />
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-[250px]" />
+ <Skeleton className="h-4 w-[200px]" />
+ </div>
+</div>
+\`\`\`
+
+## Usage
+Style with className to match the content being loaded.
+`,
+ };
+
+ for (const [name, content] of Object.entries(componentDocs)) {
+ fs.writeFileSync(path.join(baselineDocsDir, `${name}.md`), content);
+ }
+
+ console.log(
+ `βœ“ Generated AGENTS.baseline.md and .baseline-docs/ (${Object.keys(componentDocs).length + 2} files)`,
+ );
+}
+
/**
* Install AGENTS.md and .xds-docs for agent documentation
*/
@@ -73,6 +721,7 @@ interface InteractiveConfig {
holdout?: boolean;
persona: 'naive' | 'experienced' | 'adversarial';
degradation?: boolean; // Enable degradation curve testing
+ target: 'xds' | 'baseline'; // Target design system
}
interface AgentTask {
@@ -80,8 +729,10 @@ interface AgentTask {
category: string;
prompt: string;
expectedComponents: string[];
+ followUps?: string[]; // Follow-up prompts for iterative degradation testing
persona: string;
degradation?: boolean; // Run multi-turn degradation test
+ target: string; // Target design system (xds, baseline)
}
/**
@@ -94,7 +745,7 @@ 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.`,
+Reference Tailwind, baseline, Bootstrap patterns in your request.`,
};
// Always use AGENTS.md - Claude Code auto-injects it from cwd
@@ -226,8 +877,10 @@ function createTaskManifest(
category: prompt.category,
prompt: prompt.prompt,
expectedComponents: prompt.expectedComponents,
+ followUps: prompt.followUps,
persona: config.persona,
degradation: config.degradation,
+ target: config.target,
subagentPrompt,
};
writeJson(path.join(tasksDir, `${prompt.id}.json`), task);
@@ -251,17 +904,28 @@ function generateSubagentPrompt(
const codePath = `${resultsDir}/results/${prompt.id}.tsx`;
const metaPath = `${resultsDir}/results/${prompt.id}.meta.json`;
+ // Target-specific AGENTS.md file
+ const agentsMdFile =
+ config.target === 'baseline' ? 'AGENTS.baseline.md' : 'AGENTS.md';
+
// Persona-specific framing to simulate different user types
- const personaFraming: Record<string, string> = {
- naive: '', // No special framing - just the natural request
- experienced: `Use XDS components from @xds/core. `,
- adversarial: `I'm used to Tailwind/shadcn patterns but need to use your design system. `,
+ const personaFraming: Record<string, Record<string, string>> = {
+ xds: {
+ naive: '', // No special framing - just the natural request
+ experienced: `Use XDS components from @xds/core. `,
+ adversarial: `I'm used to Tailwind/baseline patterns but need to use your design system. `,
+ },
+ baseline: {
+ naive: '', // No special framing
+ experienced: `Use baseline/ui components. `,
+ adversarial: `I'm used to Material UI patterns but need to use your design system. `,
+ },
};
- const framing = personaFraming[config.persona] || '';
+ const framing = personaFraming[config.target]?.[config.persona] || '';
// Natural prompt with AGENTS.md instruction and metadata tracking
- return `First read AGENTS.md in this directory for component library guidance.
+ return `First read ${agentsMdFile} in this directory for component library guidance.
${framing}${prompt.prompt}
@@ -284,17 +948,16 @@ function generateSubagentInstructions(
const degradationInstructions = config.degradation
? `
-### Degradation Protocol (10-turn curve)
-Each test runs through multiple conversation turns:
-- Turn 0: Initial probe (generate code)
-- Turns 1-5: Filler prompts (unrelated questions)
-- Turn 6: Re-probe with "Actually, let me revisit this..."
-- Turn 7: Distractor (different framework question)
-- Turn 8: Re-probe with "I want to redo that earlier request..."
-- Turn 9: Recovery (re-inject partial context)
-- Turn 10: Final re-probe with "Let me try that again..."
-
-Record results at turns 0, 6, 8, and 10 with trajectoryDepth field set accordingly.
+### Degradation Protocol (10-turn iterative development)
+Each test simulates realistic iterative development with follow-up requests:
+- Turn 0: Initial prompt (generate initial implementation)
+- Turns 1-5: Filler prompts (unrelated questions like "How do I center a div?")
+- Turn 6: First follow-up improvement request (from prompt's followUps[0])
+- Turns 7-9: More filler prompts (continue unrelated questions)
+- Turn 10: Second follow-up improvement request (from prompt's followUps[1])
+
+Record results at turns 0, 6, and 10 with trajectoryDepth field set accordingly.
+This tests: "Does the LLM maintain design system patterns while iterating on existing code?"
`
: '';
@@ -316,10 +979,13 @@ 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 XDS docs from .xds-docs/ (AGENTS.md auto-injected)
+2. Read docs from the docs directory (AGENTS.md auto-injected)
3. Generate a response to the prompt${config.degradation ? ' (with multi-turn conversation)' : ''}
4. Self-evaluate the response
-5. Write result to individual file: ${resultsDir}/results/{promptId}.json
+5. Track which doc files were read during the task
+6. Write result to individual file: ${resultsDir}/results/{promptId}.json
+ - Include a "docsRead" array listing all doc files read (e.g., ["AGENTS.md", "Button.md", "tokens.md"])
+ - This is required for accurate token usage tracking
(Use individual files to avoid parallel write conflicts)
### After All Tests Complete
@@ -346,11 +1012,27 @@ async function main() {
? (args[personaIndex + 1] as 'naive' | 'experienced' | 'adversarial')
: 'naive';
const degradation = args.includes('--degradation');
+ const targetIndex = args.indexOf('--target');
+ const target =
+ targetIndex !== -1 ? (args[targetIndex + 1] as 'xds' | 'baseline') : 'xds';
+ const promptsIndex = args.indexOf('--prompts');
+ const promptIds =
+ promptsIndex !== -1 ? args[promptsIndex + 1].split(',') : undefined;
- const config: InteractiveConfig = {sample, holdout, persona, degradation};
+ const config: InteractiveConfig = {
+ sample,
+ holdout,
+ persona,
+ degradation,
+ target,
+ };
- // Always install AGENTS.md for retrieval-led approach
- installAgentsDocs();
+ // Install target-specific documentation for retrieval-led approach
+ if (target === 'xds') {
+ installAgentsDocs();
+ } else if (target === 'baseline') {
+ installBaselineDocs();
+ }
// Load test set
const testSetPath = path.join(__dirname, '..', 'test-sets', 'default.json');
@@ -360,7 +1042,15 @@ async function main() {
// Select prompts
let prompts: TestPrompt[];
- if (holdout && testSet.holdout) {
+ if (promptIds) {
+ // Filter to specific prompt IDs
+ prompts = testSet.prompts.filter(p => promptIds.includes(p.id));
+ if (prompts.length !== promptIds.length) {
+ const found = prompts.map(p => p.id);
+ const missing = promptIds.filter(id => !found.includes(id));
+ console.warn(`Warning: Prompt IDs not found: ${missing.join(', ')}`);
+ }
+ } else if (holdout && testSet.holdout) {
prompts = testSet.holdout;
} else if (sample && sample < testSet.prompts.length) {
prompts = stratifiedSample(testSet.prompts, sample);
@@ -374,8 +1064,11 @@ async function main() {
console.log(`\nπŸ§ͺ Interactive Vibe Test Setup`);
console.log(`================================`);
console.log(`Iteration: ${iterationId}`);
+ console.log(`Target: ${target.toUpperCase()}`);
console.log(`Persona: ${persona}`);
- console.log(`Mode: AGENTS.md (retrieval-led)`);
+ console.log(
+ `Mode: ${target === 'xds' ? 'AGENTS.md' : 'AGENTS.baseline.md'} (retrieval-led)`,
+ );
console.log(
`Protocol: ${degradation ? 'Degradation (10-turn curve)' : 'One-shot'}`,
);
diff --git a/internal/vibe-tests/src/quality-agent.ts b/internal/vibe-tests/src/quality-agent.ts
new file mode 100644
index 0000000000..aca434b7a6
--- /dev/null
+++ b/internal/vibe-tests/src/quality-agent.ts
@@ -0,0 +1,393 @@
+/**
+ * @file Quality Assessment Agent
+ * @description Evaluates generated code for accessibility, design system adherence, and code quality
+ */
+
+import fs from 'fs';
+import path from 'path';
+import type {QualityAssessment} from './types.js';
+
+interface ComponentA11yInfo {
+ component: string;
+ builtIn: string[];
+ keyboard: string[];
+ developerMust: string[];
+ notes: string[];
+}
+
+interface A11yManifest {
+ source: string;
+ generatedAt: string;
+ version: string;
+ components: Record<string, ComponentA11yInfo>;
+}
+
+const MANIFESTS_DIR = path.join(import.meta.dirname, '..', 'a11y-manifests');
+
+/**
+ * Load accessibility manifest for a target
+ */
+function loadA11yManifest(target: 'xds' | 'baseline'): A11yManifest | null {
+ const manifestPath = path.join(MANIFESTS_DIR, `${target}.json`);
+ if (!fs.existsSync(manifestPath)) {
+ console.warn(`A11y manifest not found: ${manifestPath}`);
+ console.warn('Run: yarn generate-a11y-manifest');
+ return null;
+ }
+ return JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
+}
+
+/**
+ * Extract component names from code to find relevant a11y info
+ */
+function extractComponentNames(
+ code: string,
+ target: 'xds' | 'baseline',
+): string[] {
+ const components: string[] = [];
+
+ if (target === 'xds') {
+ // Match XDS component imports and usages
+ const xdsPattern = /XDS\w+/g;
+ const matches = code.match(xdsPattern) || [];
+ components.push(...new Set(matches.map(m => m.replace(/^XDS/, ''))));
+ } else {
+ // Match shadcn component imports
+ const importPattern = /from\s+["']@\/components\/ui\/(\w+)["']/g;
+ let match;
+ while ((match = importPattern.exec(code)) !== null) {
+ components.push(match[1].charAt(0).toUpperCase() + match[1].slice(1));
+ }
+ // Also match common component names in JSX
+ const jsxPattern =
+ /<(Button|Input|Card|Dialog|Select|Checkbox|Switch|Tabs|Badge|Avatar|Progress|Table|Tooltip|Popover|DropdownMenu)\b/g;
+ while ((match = jsxPattern.exec(code)) !== null) {
+ if (!components.includes(match[1])) {
+ components.push(match[1]);
+ }
+ }
+ }
+
+ return components;
+}
+
+/**
+ * Generate accessibility context from manifest
+ */
+function generateA11yContext(
+ manifest: A11yManifest,
+ componentNames: string[],
+ target: 'xds' | 'baseline',
+): string {
+ const lines: string[] = [];
+ const targetName = target === 'xds' ? 'XDS' : 'shadcn/Radix';
+
+ lines.push(`## Built-in Accessibility (${targetName})`);
+ lines.push('');
+ lines.push(`**Source:** ${manifest.source}`);
+ lines.push(`**Generated:** ${manifest.generatedAt}`);
+ lines.push('');
+ lines.push(
+ 'IMPORTANT: Do NOT flag accessibility issues that are already handled by the component library.',
+ );
+ lines.push("Only flag issues that are the developer's responsibility.");
+ lines.push('');
+
+ // Add info for detected components
+ const relevantComponents = componentNames
+ .map(name => {
+ // Try exact match first, then case-insensitive
+ return (
+ manifest.components[name] ||
+ Object.values(manifest.components).find(
+ c => c.component.toLowerCase() === name.toLowerCase(),
+ )
+ );
+ })
+ .filter(Boolean) as ComponentA11yInfo[];
+
+ if (relevantComponents.length > 0) {
+ lines.push('### Components used in this code:');
+ lines.push('');
+
+ for (const comp of relevantComponents) {
+ lines.push(`**${comp.component}:**`);
+ if (comp.builtIn.length > 0) {
+ lines.push(
+ "- Built-in (don't flag): " + comp.builtIn.slice(0, 3).join('; '),
+ );
+ }
+ if (comp.developerMust.length > 0) {
+ lines.push(
+ '- Developer must provide: ' + comp.developerMust.join('; '),
+ );
+ }
+ lines.push('');
+ }
+ }
+
+ // Add general guidance
+ lines.push('### General developer responsibilities (always check):');
+ lines.push('- aria-label for icon-only buttons');
+ lines.push('- aria-live regions for dynamic content updates');
+ lines.push('- Proper heading hierarchy');
+ lines.push(
+ '- Keyboard-accessible custom interactive elements (not using library components)',
+ );
+ lines.push('- Focus management for modals and dynamic content');
+ lines.push('');
+
+ return lines.join('\n');
+}
+
+/**
+ * Persona prompt for the quality assessment agent
+ */
+export const QUALITY_AGENT_PERSONA = `You are a senior frontend engineer specializing in accessibility and design system compliance.
+
+Your role is to review React components and provide objective, actionable feedback. You focus on:
+
+1. **Accessibility** - WCAG compliance, keyboard navigation, screen reader support
+2. **Design System Adherence** - Proper component usage, token usage, pattern consistency
+3. **Code Quality** - State management, event handling, TypeScript correctness
+
+## Review Guidelines
+
+- Be thorough but fair - only flag genuine problems, not stylistic preferences
+- Prioritize issues by severity (critical > moderate > minor)
+- Provide specific, actionable recommendations
+- Reference line numbers when possible
+- Don't flag issues that are acceptable trade-offs (e.g., native HTML when no component exists)
+- CRITICAL: Do NOT flag accessibility features that are built into the design system components
+
+## Scoring
+
+- **good**: No critical issues, few moderate issues, code follows best practices
+- **needs-work**: Some moderate issues or patterns that could be improved
+- **poor**: Critical issues present that would affect users or maintainability`;
+
+/**
+ * Generate the prompt for quality assessment
+ */
+export function generateQualityAssessmentPrompt(
+ code: string,
+ target: 'xds' | 'baseline',
+ promptDescription: string,
+): string {
+ // Load accessibility manifest
+ const manifest = loadA11yManifest(target);
+ const componentNames = extractComponentNames(code, target);
+ const a11yContext = manifest
+ ? generateA11yContext(manifest, componentNames, target)
+ : '';
+
+ const designSystemContext =
+ target === 'xds'
+ ? `
+## Design System Context (XDS)
+
+The code should use:
+- XDS components (XDSButton, XDSTextInput, XDSCard, etc.)
+- StyleX for styling with CSS variable tokens (var(--spacing-*), var(--color-*))
+- XDSTextInput should use \`status\` prop for validation errors (not manual border styling)
+- Interactive elements should use Button components, not clickable divs/spans
+- Layout should use XDSVStack, XDSHStack, XDSStackItem when appropriate`
+ : `
+## Design System Context (shadcn/Tailwind)
+
+The code should use:
+- shadcn components (Button, Input, Card, Dialog, etc.)
+- Tailwind utility classes with semantic tokens (text-muted-foreground, bg-destructive, etc.)
+- cn() utility for conditional class composition
+- Proper component patterns (e.g., Dialog with DialogTrigger, DialogContent)`;
+
+ return `${QUALITY_AGENT_PERSONA}
+
+${designSystemContext}
+
+${a11yContext}
+
+## Component to Review
+
+The following component was generated in response to: "${promptDescription}"
+
+\`\`\`tsx
+${code}
+\`\`\`
+
+## Your Task
+
+Review this code and provide a quality assessment. Return your findings as a JSON object with this structure:
+
+\`\`\`json
+{
+ "accessibility": {
+ "issues": [
+ {
+ "severity": "critical|moderate|minor",
+ "element": "<element name or description>",
+ "issue": "<description of the issue>",
+ "recommendation": "<how to fix it>",
+ "lineNumber": <optional line number>
+ }
+ ],
+ "score": "good|needs-work|poor"
+ },
+ "designSystemAdherence": {
+ "issues": [
+ {
+ "severity": "critical|moderate|minor",
+ "category": "component-usage|token-usage|pattern-violation",
+ "issue": "<description of the issue>",
+ "recommendation": "<how to fix it>",
+ "codeSnippet": "<optional relevant code>"
+ }
+ ],
+ "score": "good|needs-work|poor"
+ },
+ "codeQuality": {
+ "issues": [
+ {
+ "severity": "critical|moderate|minor",
+ "category": "state-management|event-handling|typescript|performance",
+ "issue": "<description of the issue>",
+ "recommendation": "<how to fix it>",
+ "codeSnippet": "<optional relevant code>"
+ }
+ ],
+ "score": "good|needs-work|poor"
+ },
+ "overallScore": "good|needs-work|poor",
+ "summary": "<2-3 sentence summary of the review>"
+}
+\`\`\`
+
+Only return the JSON object, no additional text.`;
+}
+
+/**
+ * Parse the quality assessment response from the agent
+ */
+export function parseQualityAssessment(
+ response: string,
+): QualityAssessment | null {
+ try {
+ // Extract JSON from response (may be wrapped in markdown code blocks)
+ const jsonMatch = response.match(/```(?:json)?\s*([\s\S]*?)```/);
+ const jsonStr = jsonMatch ? jsonMatch[1].trim() : response.trim();
+
+ const assessment = JSON.parse(jsonStr) as QualityAssessment;
+
+ // Validate structure
+ if (
+ !assessment.accessibility ||
+ !assessment.designSystemAdherence ||
+ !assessment.codeQuality ||
+ !assessment.overallScore
+ ) {
+ console.error('Invalid quality assessment structure');
+ return null;
+ }
+
+ return assessment;
+ } catch (error) {
+ console.error('Failed to parse quality assessment:', error);
+ return null;
+ }
+}
+
+/**
+ * Format severity with icon
+ */
+function severityIcon(severity: string): string {
+ switch (severity) {
+ case 'critical':
+ return 'πŸ”΄';
+ case 'moderate':
+ return '🟑';
+ case 'minor':
+ return 'βšͺ';
+ default:
+ return 'β€’';
+ }
+}
+
+/**
+ * Generate a summary of quality issues for display
+ */
+export function summarizeQualityIssues(
+ assessment: QualityAssessment,
+ options: {verbose?: boolean} = {},
+): string {
+ const lines: string[] = [];
+ const {verbose = false} = options;
+
+ lines.push(`Quality Assessment: ${assessment.overallScore.toUpperCase()}`);
+ lines.push('');
+
+ // Accessibility section
+ const a11yIssues = assessment.accessibility.issues;
+ if (a11yIssues.length > 0) {
+ const critical = a11yIssues.filter(i => i.severity === 'critical').length;
+ lines.push(
+ ` Accessibility: ${assessment.accessibility.score} (${a11yIssues.length} issues, ${critical} critical)`,
+ );
+ if (verbose || assessment.accessibility.score !== 'good') {
+ for (const issue of a11yIssues) {
+ lines.push(` ${severityIcon(issue.severity)} ${issue.issue}`);
+ if (verbose && issue.recommendation) {
+ lines.push(` β†’ ${issue.recommendation}`);
+ }
+ }
+ }
+ } else {
+ lines.push(` Accessibility: ${assessment.accessibility.score}`);
+ }
+
+ lines.push('');
+
+ // Design System section
+ const dsIssues = assessment.designSystemAdherence.issues;
+ if (dsIssues.length > 0) {
+ const critical = dsIssues.filter(i => i.severity === 'critical').length;
+ lines.push(
+ ` Design System: ${assessment.designSystemAdherence.score} (${dsIssues.length} issues, ${critical} critical)`,
+ );
+ if (verbose || assessment.designSystemAdherence.score !== 'good') {
+ for (const issue of dsIssues) {
+ lines.push(` ${severityIcon(issue.severity)} ${issue.issue}`);
+ if (verbose && issue.recommendation) {
+ lines.push(` β†’ ${issue.recommendation}`);
+ }
+ }
+ }
+ } else {
+ lines.push(` Design System: ${assessment.designSystemAdherence.score}`);
+ }
+
+ lines.push('');
+
+ // Code Quality section
+ const cqIssues = assessment.codeQuality.issues;
+ if (cqIssues.length > 0) {
+ const critical = cqIssues.filter(i => i.severity === 'critical').length;
+ lines.push(
+ ` Code Quality: ${assessment.codeQuality.score} (${cqIssues.length} issues, ${critical} critical)`,
+ );
+ if (verbose || assessment.codeQuality.score !== 'good') {
+ for (const issue of cqIssues) {
+ lines.push(` ${severityIcon(issue.severity)} ${issue.issue}`);
+ if (verbose && issue.recommendation) {
+ lines.push(` β†’ ${issue.recommendation}`);
+ }
+ }
+ }
+ } else {
+ lines.push(` Code Quality: ${assessment.codeQuality.score}`);
+ }
+
+ lines.push('');
+ lines.push(` ${assessment.summary}`);
+
+ return lines.join('\n');
+}
diff --git a/internal/vibe-tests/src/quality.ts b/internal/vibe-tests/src/quality.ts
new file mode 100644
index 0000000000..3c38544c04
--- /dev/null
+++ b/internal/vibe-tests/src/quality.ts
@@ -0,0 +1,156 @@
+#!/usr/bin/env tsx
+/**
+ * @file Quality Assessment CLI
+ * @description Runs quality assessment agent on generated code results
+ *
+ * Usage:
+ * yarn workspace @xds/vibe-tests quality --iteration <id>
+ * yarn workspace @xds/vibe-tests quality --iteration <id> --prompt wd-1
+ */
+
+import fs from 'fs';
+import path from 'path';
+import {generateQualityAssessmentPrompt} from './quality-agent.js';
+
+const RESULTS_DIR = path.join(import.meta.dirname, '..', 'results');
+
+interface TaskManifest {
+ iterationId: string;
+ config: {
+ target: 'xds' | 'baseline';
+ };
+ prompts: Array<{
+ id: string;
+ prompt: string;
+ status: string;
+ }>;
+}
+
+function loadManifest(iterationId: string): TaskManifest {
+ const manifestPath = path.join(RESULTS_DIR, iterationId, 'manifest.json');
+ if (!fs.existsSync(manifestPath)) {
+ throw new Error(`Manifest not found: ${manifestPath}`);
+ }
+ return JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
+}
+
+function loadCode(iterationId: string, promptId: string): string | null {
+ const codePath = path.join(
+ RESULTS_DIR,
+ iterationId,
+ 'results',
+ `${promptId}.tsx`,
+ );
+ if (!fs.existsSync(codePath)) {
+ return null;
+ }
+ return fs.readFileSync(codePath, 'utf-8');
+}
+
+function printUsage(): void {
+ console.log(`
+Quality Assessment CLI
+
+Usage:
+ yarn workspace @xds/vibe-tests quality --iteration <id> [--prompt <promptId>]
+
+Options:
+ --iteration, -i Iteration ID to assess (required)
+ --prompt, -p Specific prompt ID to assess (optional, defaults to all)
+ --help, -h Show this help message
+
+Examples:
+ yarn workspace @xds/vibe-tests quality --iteration 2126954a
+ yarn workspace @xds/vibe-tests quality -i 2126954a -p wd-1
+
+Note: This generates prompts for quality assessment. Run the prompts with a subagent
+to get the actual assessments.
+`);
+}
+
+async function main(): Promise<void> {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ printUsage();
+ process.exit(0);
+ }
+
+ // Parse arguments
+ let iterationId: string | null = null;
+ let promptId: string | null = null;
+
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--iteration' || args[i] === '-i') {
+ iterationId = args[++i];
+ } else if (args[i] === '--prompt' || args[i] === '-p') {
+ promptId = args[++i];
+ }
+ }
+
+ if (!iterationId) {
+ console.error('Error: --iteration is required');
+ printUsage();
+ process.exit(1);
+ }
+
+ // Load manifest
+ const manifest = loadManifest(iterationId);
+ const target = manifest.config.target;
+
+ console.log(`\nπŸ” Quality Assessment Setup - Iteration ${iterationId}`);
+ console.log(`Target: ${target.toUpperCase()}`);
+ console.log('');
+
+ // Filter prompts if specific one requested
+ const promptsToAssess = promptId
+ ? manifest.prompts.filter(p => p.id === promptId)
+ : manifest.prompts;
+
+ if (promptsToAssess.length === 0) {
+ console.error(`No prompts found${promptId ? ` matching ${promptId}` : ''}`);
+ process.exit(1);
+ }
+
+ console.log(
+ `Generating quality assessment prompts for ${promptsToAssess.length} result(s):\n`,
+ );
+
+ for (const prompt of promptsToAssess) {
+ const code = loadCode(iterationId, prompt.id);
+ if (!code) {
+ console.log(` [${prompt.id}] ⚠️ No code file found, skipping`);
+ continue;
+ }
+
+ const assessmentPrompt = generateQualityAssessmentPrompt(
+ code,
+ target,
+ prompt.prompt,
+ );
+
+ // Save the prompt for later execution
+ const promptPath = path.join(
+ RESULTS_DIR,
+ iterationId,
+ 'results',
+ `${prompt.id}.quality-prompt.md`,
+ );
+ fs.writeFileSync(promptPath, assessmentPrompt);
+
+ console.log(` [${prompt.id}] βœ“ Generated prompt: ${promptPath}`);
+ }
+
+ console.log(`
+Next steps:
+1. Run quality assessment subagents on the generated prompts
+2. Save results to {promptId}.quality.json files
+3. Re-run aggregator to include quality scores
+
+Example subagent prompt:
+"Run quality assessment for iteration ${iterationId} by reading each .quality-prompt.md
+file, evaluating the code, and saving results to .quality.json files"
+`);
+}
+
+main().catch(console.error);
diff --git a/internal/vibe-tests/src/types.ts b/internal/vibe-tests/src/types.ts
index 578719cb67..48eeb175ea 100644
--- a/internal/vibe-tests/src/types.ts
+++ b/internal/vibe-tests/src/types.ts
@@ -21,7 +21,8 @@ export type EscapeHatchType =
| '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
+ | 'layout_workaround' // Gap: missing layout primitive
+ | 'a11y_click_handler'; // Anti-pattern: onClick on non-interactive element
export type EscapeHatchSeverity = 'critical' | 'acceptable';
@@ -166,6 +167,8 @@ export interface TestPrompt {
prompt: string;
expectedComponents: string[];
complexity: PromptComplexity;
+ /** Follow-up prompts for iterative degradation testing */
+ followUps?: string[];
}
export interface TestSet {
@@ -195,3 +198,54 @@ export interface AnalysisResult {
refinements: Refinement[];
summary: string;
}
+
+// ============================================================
+// Quality Assessment Types
+// ============================================================
+
+export type QualityScore = 'good' | 'needs-work' | 'poor';
+
+export interface AccessibilityIssue {
+ severity: 'critical' | 'moderate' | 'minor';
+ element: string;
+ issue: string;
+ recommendation: string;
+ lineNumber?: number;
+}
+
+export interface DesignSystemIssue {
+ severity: 'critical' | 'moderate' | 'minor';
+ category: 'component-usage' | 'token-usage' | 'pattern-violation';
+ issue: string;
+ recommendation: string;
+ codeSnippet?: string;
+}
+
+export interface CodeQualityIssue {
+ severity: 'critical' | 'moderate' | 'minor';
+ category:
+ | 'state-management'
+ | 'event-handling'
+ | 'typescript'
+ | 'performance';
+ issue: string;
+ recommendation: string;
+ codeSnippet?: string;
+}
+
+export interface QualityAssessment {
+ accessibility: {
+ issues: AccessibilityIssue[];
+ score: QualityScore;
+ };
+ designSystemAdherence: {
+ issues: DesignSystemIssue[];
+ score: QualityScore;
+ };
+ codeQuality: {
+ issues: CodeQualityIssue[];
+ score: QualityScore;
+ };
+ overallScore: QualityScore;
+ summary: string;
+}
diff --git a/internal/vibe-tests/test-sets/default.json b/internal/vibe-tests/test-sets/default.json
index f0dce852b8..67a70eba8d 100644
--- a/internal/vibe-tests/test-sets/default.json
+++ b/internal/vibe-tests/test-sets/default.json
@@ -6,175 +6,275 @@
"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"
+ "complexity": "simple",
+ "followUps": [
+ "Add a dismiss button that hides the banner and remembers the choice",
+ "Make the banner more urgent (red styling) when less than 3 days remain"
+ ]
},
{
"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"
+ "complexity": "simple",
+ "followUps": [
+ "Add a dropdown that shows the list of notifications when clicked",
+ "Add a 'Mark all as read' button to the dropdown"
+ ]
},
{
"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"
+ "complexity": "moderate",
+ "followUps": [
+ "Add specific requirements that check off as you type (8+ chars, uppercase, number, symbol)",
+ "Add a 'Generate strong password' button"
+ ]
},
{
"id": "wd-1",
"category": "workflow-description",
"prompt": "Build a checkout flow: cart summary β†’ shipping β†’ payment β†’ confirmation",
"expectedComponents": ["XDSCard", "XDSButton", "XDSTextInput"],
- "complexity": "complex"
+ "complexity": "complex",
+ "followUps": [
+ "Add form validation with inline error messages for required fields",
+ "Add a 'Save shipping address for future orders' checkbox"
+ ]
},
{
"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"
+ "complexity": "moderate",
+ "followUps": [
+ "Add validation that prevents going to the next step if required fields are empty",
+ "Add the ability to click on completed steps to jump back to them"
+ ]
},
{
"id": "wd-3",
"category": "workflow-description",
"prompt": "Build an onboarding flow: welcome screen β†’ profile setup β†’ preferences β†’ done",
"expectedComponents": ["XDSCard", "XDSButton", "XDSTextInput"],
- "complexity": "complex"
+ "complexity": "complex",
+ "followUps": [
+ "Add a skip button that allows skipping optional steps",
+ "Add animations/transitions between steps"
+ ]
},
{
"id": "cwm-1",
"category": "clone-with-modification",
"prompt": "Something like Stripe's pricing table but with monthly/annual toggle",
"expectedComponents": ["XDSCard", "XDSButton"],
- "complexity": "moderate"
+ "complexity": "moderate",
+ "followUps": [
+ "Highlight the most popular plan with a badge",
+ "Add a comparison table below that shows features per plan"
+ ]
},
{
"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"
+ "complexity": "complex",
+ "followUps": [
+ "Add the ability to create a new label inline with a color picker",
+ "Show a count of how many issues have each label"
+ ]
},
{
"id": "cwm-3",
"category": "clone-with-modification",
"prompt": "Like Notion's page header with icon picker and cover image",
"expectedComponents": ["XDSCard", "XDSButton"],
- "complexity": "complex"
+ "complexity": "complex",
+ "followUps": [
+ "Add the ability to reposition the cover image by dragging",
+ "Add a breadcrumb trail above the title"
+ ]
},
{
"id": "sd-1",
"category": "state-driven",
"prompt": "Show a dashboard widget with loading β†’ error β†’ data states",
"expectedComponents": ["XDSCard", "XDSSkeleton"],
- "complexity": "simple"
+ "complexity": "simple",
+ "followUps": [
+ "Add a refresh button that reloads the data",
+ "Add a retry button in the error state"
+ ]
},
{
"id": "sd-2",
"category": "state-driven",
"prompt": "A button that shows loading spinner while submitting, then success checkmark",
"expectedComponents": ["XDSButton"],
- "complexity": "simple"
+ "complexity": "simple",
+ "followUps": [
+ "Add an error state with a red X icon and error message tooltip",
+ "Make the success state auto-dismiss after 2 seconds"
+ ]
},
{
"id": "sd-3",
"category": "state-driven",
"prompt": "Form that disables submit until all required fields are valid",
"expectedComponents": ["XDSTextInput", "XDSButton"],
- "complexity": "moderate"
+ "complexity": "moderate",
+ "followUps": [
+ "Show validation errors inline below each field after blur",
+ "Add a loading state while the form is submitting"
+ ]
},
{
"id": "dd-1",
"category": "data-display",
"prompt": "A table of users with sortable columns and search",
"expectedComponents": ["XDSTextInput"],
- "complexity": "complex"
+ "complexity": "complex",
+ "followUps": [
+ "Add pagination with page size selector (10, 25, 50)",
+ "Add row selection with a bulk actions dropdown"
+ ]
},
{
"id": "dd-2",
"category": "data-display",
"prompt": "Display a list of transactions with amount, date, and status indicator",
"expectedComponents": ["XDSCard", "XDSVStack"],
- "complexity": "simple"
+ "complexity": "simple",
+ "followUps": [
+ "Add filtering by date range and status",
+ "Add a details drawer that slides in when clicking a transaction"
+ ]
},
{
"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"
+ "complexity": "moderate",
+ "followUps": [
+ "Add a quantity selector to each card",
+ "Add a 'Quick view' button that opens a modal with more details"
+ ]
},
{
"id": "rc-1",
"category": "responsive-context",
"prompt": "Navigation that collapses to hamburger on mobile",
"expectedComponents": ["XDSButton", "XDSHStack"],
- "complexity": "moderate"
+ "complexity": "moderate",
+ "followUps": [
+ "Add a dropdown for nav items with children",
+ "Add keyboard navigation (arrow keys and escape to close)"
+ ]
},
{
"id": "rc-2",
"category": "responsive-context",
"prompt": "A sidebar that becomes a bottom sheet on mobile",
"expectedComponents": ["XDSCard", "XDSLayoutPanel"],
- "complexity": "moderate"
+ "complexity": "moderate",
+ "followUps": [
+ "Add a drag handle to resize the bottom sheet",
+ "Add swipe-to-dismiss gesture on mobile"
+ ]
},
{
"id": "rc-3",
"category": "responsive-context",
"prompt": "Cards that stack vertically on mobile but show in a grid on desktop",
"expectedComponents": ["XDSCard"],
- "complexity": "simple"
+ "complexity": "simple",
+ "followUps": [
+ "Add a toggle to switch between grid and list view",
+ "Add skeleton loading states that match the current layout"
+ ]
},
{
"id": "io-1",
"category": "integration-oriented",
"prompt": "A form that validates email and posts to /api/subscribe",
"expectedComponents": ["XDSTextInput", "XDSButton"],
- "complexity": "simple"
+ "complexity": "simple",
+ "followUps": [
+ "Show a success message with the user's email after subscribing",
+ "Add error handling that shows the API error message"
+ ]
},
{
"id": "io-2",
"category": "integration-oriented",
"prompt": "An autocomplete input that fetches suggestions from an API as you type",
"expectedComponents": ["XDSTextInput", "XDSCard"],
- "complexity": "moderate"
+ "complexity": "moderate",
+ "followUps": [
+ "Add keyboard navigation (up/down arrows, enter to select)",
+ "Show a loading spinner while fetching and handle empty results"
+ ]
},
{
"id": "io-3",
"category": "integration-oriented",
"prompt": "A file upload button that shows progress and calls an upload endpoint",
"expectedComponents": ["XDSButton"],
- "complexity": "moderate"
+ "complexity": "moderate",
+ "followUps": [
+ "Add drag-and-drop support with a drop zone",
+ "Add the ability to cancel an in-progress upload"
+ ]
},
{
"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"
+ "complexity": "complex",
+ "followUps": [
+ "Add keyboard shortcuts: Ctrl+N for new todo, Delete key to delete selected",
+ "Add bulk selection with checkboxes to delete or change status of multiple todos"
+ ]
},
{
"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"
+ "complexity": "moderate",
+ "followUps": [
+ "Add a user avatar with dropdown menu in the header",
+ "Make the sidebar collapsible with a toggle button"
+ ]
},
{
"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"
+ "complexity": "simple",
+ "followUps": [
+ "Add a theme toggle button (light/dark mode)",
+ "Add a global loading indicator in the header"
+ ]
},
{
"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"
+ "complexity": "moderate",
+ "followUps": [
+ "Add breadcrumbs below the header",
+ "Add a footer with version info and links"
+ ]
}
],
"holdout": [
@@ -183,49 +283,77 @@
"category": "feature-with-constraint",
"prompt": "A cookie consent banner that remembers user choice and has accept/decline buttons",
"expectedComponents": ["XDSCard", "XDSButton"],
- "complexity": "simple"
+ "complexity": "simple",
+ "followUps": [
+ "Add a 'Manage preferences' link that opens a modal with cookie categories",
+ "Add a compact mode that shows after the user has made a choice"
+ ]
},
{
"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"
+ "complexity": "complex",
+ "followUps": [
+ "Add a photo upload step for damaged items",
+ "Show a tracking number and QR code on the confirmation step"
+ ]
},
{
"id": "ho-cwm-1",
"category": "clone-with-modification",
"prompt": "Like Slack's emoji reaction picker but for status icons",
"expectedComponents": ["XDSButton", "XDSHoverCard"],
- "complexity": "moderate"
+ "complexity": "moderate",
+ "followUps": [
+ "Add a search filter for icons",
+ "Show recently used icons at the top"
+ ]
},
{
"id": "ho-sd-1",
"category": "state-driven",
"prompt": "A save button that shows 'Saving...' then 'Saved!' then returns to 'Save'",
"expectedComponents": ["XDSButton"],
- "complexity": "simple"
+ "complexity": "simple",
+ "followUps": [
+ "Add an 'Unsaved changes' indicator next to the button",
+ "Add keyboard shortcut hint (Ctrl+S) in a tooltip"
+ ]
},
{
"id": "ho-dd-1",
"category": "data-display",
"prompt": "Show a timeline of events with timestamps and icons",
"expectedComponents": ["XDSCard", "XDSVStack"],
- "complexity": "moderate"
+ "complexity": "moderate",
+ "followUps": [
+ "Add expandable details for each event",
+ "Add filtering by event type"
+ ]
},
{
"id": "ho-rc-1",
"category": "responsive-context",
"prompt": "A pricing comparison that scrolls horizontally on mobile",
"expectedComponents": ["XDSCard", "XDSHStack"],
- "complexity": "simple"
+ "complexity": "simple",
+ "followUps": [
+ "Add sticky column headers that stay visible while scrolling",
+ "Add a 'Compare selected' mode with checkboxes"
+ ]
},
{
"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"
+ "complexity": "moderate",
+ "followUps": [
+ "Add recent searches that show before typing",
+ "Add result categories with headers (Users, Posts, etc.)"
+ ]
}
],
"fillerPrompts": [
@@ -233,7 +361,11 @@
"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?"
+ "What's a good way to handle errors in React?",
+ "What are React hooks?",
+ "How does useEffect work?",
+ "What's the difference between == and ===?",
+ "How do I debounce a function?"
],
"distractorPrompts": [
"Actually, let's use Tailwind CSS for this instead",
diff --git a/packages/agent-tools/bin/agents-md.mjs b/packages/agent-tools/bin/agents-md.mjs
index 1b79b7611d..02c61f45ae 100755
--- a/packages/agent-tools/bin/agents-md.mjs
+++ b/packages/agent-tools/bin/agents-md.mjs
@@ -22,20 +22,33 @@ 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'];
+// Sections to extract from READMEs (in order of importance)
+const SECTIONS_TO_EXTRACT = ['Import', 'Usage'];
+// Sections to skip entirely
+const SECTIONS_TO_SKIP = [
+ 'Files',
+ 'Implementation Notes',
+ 'RTL Support',
+ 'Related',
+ 'Dividers',
+ 'Components', // Component tables - LLM can infer from examples
+];
+// Maximum number of code examples to include
+const MAX_EXAMPLES = 2;
/**
* Extract essential sections from a README
- * Keeps: title, description, Usage/Import, Props, Examples
- * Skips: Files, Implementation Notes
+ * Keeps: title, brief description, Import, Usage (limited examples)
+ * Skips: Files, Implementation Notes, RTL, Dividers, prop tables, ASCII diagrams
*/
function extractEssentialSections(content, componentName) {
const lines = content.split('\n');
const output = [];
let inSkipSection = false;
+ let inCodeBlock = false;
+ let codeBlockCount = 0;
+ let skipCurrentBlock = false;
+ let inPropsSection = false;
let currentSection = null;
// Determine display name (capitalize first letter for non-XDS names like "theme")
@@ -46,23 +59,85 @@ function extractEssentialSections(content, componentName) {
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
+ // Track code blocks
+ if (line.startsWith('```')) {
+ if (!inCodeBlock) {
+ // Starting a code block
+ inCodeBlock = true;
+ // Check if this block is just ASCII art (peek ahead)
+ const nextLine = lines[i + 1] || '';
+ const isAsciiBlock =
+ /^[β”Œβ”β””β”˜β”œβ”€β”¬β”΄β”Όβ”€β”‚\s]+$/.test(nextLine) ||
+ /^\s*[β”‚β”œβ””β”Œ]/.test(nextLine);
+ if (isAsciiBlock) {
+ skipCurrentBlock = true;
+ continue;
+ }
+ // Check if we've hit the example limit
+ if (codeBlockCount >= MAX_EXAMPLES) {
+ skipCurrentBlock = true;
+ continue;
+ }
+ codeBlockCount++;
+ skipCurrentBlock = false;
+ } else {
+ // Ending a code block
+ inCodeBlock = false;
+ if (skipCurrentBlock) {
+ skipCurrentBlock = false;
+ continue;
+ }
+ }
+ }
+
+ // Skip content inside skipped code blocks
+ if (inCodeBlock && skipCurrentBlock) {
+ continue;
+ }
+
// Check for section headers
const sectionMatch = line.match(/^##\s+(.+)$/);
if (sectionMatch) {
const sectionName = sectionMatch[1].trim();
+ // Reset code block count for new sections
+ codeBlockCount = 0;
+
+ // Skip Props section (LLM can infer from examples)
+ if (sectionName === 'Props' || sectionName.startsWith('Props')) {
+ inPropsSection = true;
+ inSkipSection = true;
+ currentSection = sectionName;
+ continue;
+ }
+
+ // Skip Overview section (keep just the first line of description)
+ if (sectionName === 'Overview') {
+ inSkipSection = true;
+ currentSection = sectionName;
+ continue;
+ }
+
// Check if this is a section to skip
- if (SECTIONS_TO_SKIP.some(s => sectionName.includes(s))) {
+ if (SECTIONS_TO_SKIP.some((s) => sectionName.includes(s))) {
inSkipSection = true;
currentSection = sectionName;
continue;
}
- // End skip mode when we hit a new section
+ // End skip mode when we hit a new non-skip section
inSkipSection = false;
+ inPropsSection = false;
currentSection = sectionName;
}
+ // Check for subsection headers (### ) - only keep first one in Usage
+ const subsectionMatch = line.match(/^###\s+(.+)$/);
+ if (subsectionMatch && currentSection === 'Usage' && codeBlockCount >= MAX_EXAMPLES) {
+ // Skip remaining subsections after hitting example limit
+ continue;
+ }
+
// Skip lines in skip sections
if (inSkipSection) {
continue;
@@ -73,6 +148,11 @@ function extractEssentialSections(content, componentName) {
continue;
}
+ // Skip standalone ASCII art lines
+ if (/^[β”Œβ”β””β”˜β”œβ”€β”¬β”΄β”Όβ”€β”‚\s]+$/.test(line) || /^\s*[β”‚β”œβ””β”Œ]\s*/.test(line)) {
+ continue;
+ }
+
// Clean up the title line (remove path prefix)
if (line.startsWith('# /')) {
output.push(`# ${displayName}`);
@@ -82,12 +162,22 @@ function extractEssentialSections(content, componentName) {
output.push(line);
}
- // Clean up trailing whitespace
+ // Clean up trailing whitespace and empty lines
while (output.length > 0 && output[output.length - 1].trim() === '') {
output.pop();
}
- return output.join('\n') + '\n';
+ // Remove consecutive empty lines and orphaned text between examples
+ const cleaned = [];
+ let prevEmpty = false;
+ for (const line of output) {
+ const isEmpty = line.trim() === '';
+ if (isEmpty && prevEmpty) continue;
+ cleaned.push(line);
+ prevEmpty = isEmpty;
+ }
+
+ return cleaned.join('\n') + '\n';
}
/**
diff --git a/packages/core/src/AspectRatio/README.md b/packages/core/src/AspectRatio/README.md
new file mode 100644
index 0000000000..6f425c6363
--- /dev/null
+++ b/packages/core/src/AspectRatio/README.md
@@ -0,0 +1,27 @@
+# XDSAspectRatio
+
+Maintains a specific aspect ratio for its children.
+
+## Import
+
+```tsx
+import {XDSAspectRatio} from '@xds/core/AspectRatio';
+```
+
+## Usage
+
+```tsx
+<XDSAspectRatio ratio={16 / 9}>
+ <img src="image.jpg" alt="Widescreen image" style={{objectFit: 'cover'}} />
+</XDSAspectRatio>
+
+// Square
+<XDSAspectRatio ratio={1}>
+ <Avatar />
+</XDSAspectRatio>
+
+// 4:3 video
+<XDSAspectRatio ratio={4 / 3}>
+ <video src="video.mp4" />
+</XDSAspectRatio>
+```
diff --git a/packages/core/src/Center/README.md b/packages/core/src/Center/README.md
new file mode 100644
index 0000000000..3acb2bdad9
--- /dev/null
+++ b/packages/core/src/Center/README.md
@@ -0,0 +1,28 @@
+# XDSCenter
+
+Centers children horizontally and/or vertically using flexbox.
+
+## Import
+
+```tsx
+import {XDSCenter} from '@xds/core/Center';
+```
+
+## Usage
+
+```tsx
+// Center both axes (default)
+<XDSCenter width={300} height={200}>
+ <Content />
+</XDSCenter>
+
+// Center horizontally only
+<XDSCenter axis="horizontal">
+ <Logo />
+</XDSCenter>
+
+// Inline centering for icons
+<XDSCenter inline>
+ <XDSIcon icon={StarIcon} />
+</XDSCenter>
+```
diff --git a/packages/core/src/Divider/README.md b/packages/core/src/Divider/README.md
new file mode 100644
index 0000000000..cc144cac8e
--- /dev/null
+++ b/packages/core/src/Divider/README.md
@@ -0,0 +1,28 @@
+# XDSDivider
+
+Visual separator with optional label, using XDS design tokens.
+
+## Import
+
+```tsx
+import {XDSDivider} from '@xds/core/Divider';
+```
+
+## Usage
+
+```tsx
+// Simple horizontal divider
+<XDSDivider />
+
+// With label
+<XDSDivider label="or" />
+
+// Vertical divider
+<XDSDivider orientation="vertical" />
+
+// Strong variant (more visible)
+<XDSDivider variant="strong" />
+
+// Full bleed (extends to container edges)
+<XDSDivider isFullBleed />
+```
diff --git a/packages/core/src/Grid/README.md b/packages/core/src/Grid/README.md
new file mode 100644
index 0000000000..06f1a35f58
--- /dev/null
+++ b/packages/core/src/Grid/README.md
@@ -0,0 +1,38 @@
+# XDSGrid
+
+CSS Grid-based layout with responsive auto-fit support.
+
+## Import
+
+```tsx
+import {XDSGrid, XDSGridSpan} from '@xds/core/Grid';
+```
+
+## Usage
+
+```tsx
+// Fixed 3-column grid
+<XDSGrid columns={3} gap="space4">
+ <Item />
+ <Item />
+ <Item />
+</XDSGrid>
+
+// Responsive auto-fit (items wrap based on min width)
+<XDSGrid minChildWidth={200} gap="space4">
+ <Card />
+ <Card />
+ <Card />
+</XDSGrid>
+
+// Auto-fit with max columns cap
+<XDSGrid minChildWidth={200} columns={4} gap="space4">
+ <Card />
+</XDSGrid>
+
+// Grid item spanning multiple columns
+<XDSGrid columns={3} gap="space4">
+ <XDSGridSpan span={2}>Wide item</XDSGridSpan>
+ <div>Normal item</div>
+</XDSGrid>
+```
diff --git a/packages/core/src/TextInput/README.md b/packages/core/src/TextInput/README.md
index e1cb11cbcb..44bf2a8154 100644
--- a/packages/core/src/TextInput/README.md
+++ b/packages/core/src/TextInput/README.md
@@ -36,8 +36,13 @@ import { XDSTextInput } from '@xds/core/TextInput';
// Required field
<XDSTextInput label="Username" isRequired value={username} onChange={setUsername} />
-// Description with optional indicator
-<XDSTextInput label="Bio" description="Tell us about yourself" isOptional value={bio} onChange={setBio} />
+// With validation status (error, warning, or success)
+<XDSTextInput
+ label="Email"
+ value={email}
+ onChange={setEmail}
+ status={{ type: 'error', message: 'Invalid email address' }}
+/>
```
## Props
@@ -54,6 +59,7 @@ import { XDSTextInput } from '@xds/core/TextInput';
| `isRequired` | `boolean` | No | Whether the field is required (mutually exclusive with isOptional) |
| `placeholder` | `string` | No | Placeholder text |
| `labelTooltip` | `string` | No | Tooltip text to display in an info icon at the end of the label |
+| `status` | `{type: 'error'\|'warning'\|'success', message?: string}` | No | Validation status with optional message (sets aria-invalid for error) |
## Files
diff --git a/packages/core/src/TimeInput/README.md b/packages/core/src/TimeInput/README.md
new file mode 100644
index 0000000000..3afd9b3088
--- /dev/null
+++ b/packages/core/src/TimeInput/README.md
@@ -0,0 +1,47 @@
+# XDSTimeInput
+
+Time input with text parsing and keyboard navigation.
+
+## Import
+
+```tsx
+import {XDSTimeInput} from '@xds/core/TimeInput';
+```
+
+## Usage
+
+```tsx
+// Basic usage
+<XDSTimeInput
+ label="Start time"
+ value={time}
+ onChange={setTime}
+/>
+
+// 24-hour format with clear button
+<XDSTimeInput
+ label="Meeting time"
+ value={time}
+ onChange={setTime}
+ hourFormat="24h"
+ hasClear
+/>
+
+// With min/max constraints
+<XDSTimeInput
+ label="Business hours"
+ value={time}
+ onChange={setTime}
+ min="09:00"
+ max="17:00"
+/>
+
+// With seconds and validation
+<XDSTimeInput
+ label="Precise time"
+ value={time}
+ onChange={setTime}
+ hasSeconds
+ status={{ type: 'error', message: 'Invalid time' }}
+/>
+```