Compare commits

..

17 Commits

Author SHA1 Message Date
catlog22
3fd087620b docs(changelog): add v4.3.0 release notes for UI Design Workflow V2
- Self-contained CSS architecture improvements
- Removed placeholder mechanism
- Enhanced agent CSS generation with direct token values
- Simplified workflow with 346 lines removed
- Better style differentiation and design quality

Features:
- generate-v2 command with independent CSS generation
- explore-auto-v2 updated for new architecture
- Agents read design-tokens.json directly
- No more tokens.css or placeholder replacement

Benefits:
- Faster execution (2 fewer intermediate steps)
- Better style diversity and differentiation
- Easier debugging and maintenance
- Self-contained, portable CSS files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 19:32:53 +08:00
catlog22
6e37881588 refactor(ui-design): remove placeholder mechanism and simplify CSS generation workflow
- Agent now directly generates HTML with final CSS references (no placeholders)
- Remove tokens.css dependency - agents create self-contained CSS from design-tokens.json
- Simplify ui-generate-preview-v2.sh (no placeholder replacement logic)
- Update Phase 2.5 validation to check actual href attributes
- Remove Phase 1.6 (token conversion step)
- Improve agent instructions with direct CSS value usage from design tokens

Benefits:
- Simpler workflow with fewer intermediate steps
- More flexible CSS generation - agents can adapt token values based on design_attributes
- Better style differentiation across variants
- Reduced dependencies and potential error points

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 19:29:38 +08:00
catlog22
043a3f05ba refactor(ui-design): optimize layout planning to prevent architecture homogenization
- Replace exa-code with web-search for diverse layout inspiration
- Simplify from keyword pools to direct "common variations" search
- Add selection strategy for agents to pick different structural patterns
- Support unlimited layout variants with natural diversity

Impact: Prevents layout architecture convergence by leveraging web search
for real-world layout variations instead of code examples.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 17:05:11 +08:00
catlog22
6b6367a669 feat: Add ui-generate-preview-v2.sh script for style-centric prototype preview generation
- Implemented a new script to generate compare.html and index.html for UI prototypes.
- Auto-detects styles, layouts, and targets from HTML file patterns.
- Generates an interactive comparison matrix and a simple index of prototypes.
- Includes a detailed PREVIEW.md guide with usage instructions and file structure.
2025-10-10 16:53:53 +08:00
catlog22
d255e633fe refactor(ui-design): remove internal parameter --continue-run for clarity and maintain backward compatibility 2025-10-10 15:22:11 +08:00
catlog22
6b6481dc3f refactor(ui-design): clean up command documentation by removing unused parameters and clarifying usage instructions 2025-10-10 15:12:24 +08:00
catlog22
e0d4bf2aee refactor(ui-design): optimize consolidate workflow - remove MCP calls and fix path inconsistency
## Major Changes

### 1. Remove MCP Calls (Philosophy-Driven Refinement)
- Eliminated all 13 MCP queries (4 per variant + 1 accessibility)
- Replaced with pure AI philosophy-driven token refinement
- Uses design_attributes from extract phase to map to token values
- Performance: ~50% faster execution (~60s vs ~120s)
- Quality: Better variant divergence (no trend pollution)

### 2. Fix Path Naming Inconsistency
- Fixed mismatch: `style-variant-1/` → `style-1/`
- mkdir creates: style-1/, style-2/, style-3/
- Agent now writes to matching directories using loop index {N}
- Added CRITICAL PATH MAPPING section for clarity

## Technical Details

**MCP Removal:**
- Step 1: Trend Research → Load Design Philosophy
- Step 2: Added attribute-to-token mapping rules
- Agent prompt: Removed MCP integration code
- All accessibility validation uses built-in AI knowledge

**Path Fix:**
- Unified on numeric index format: style-{N}/ (N = 1-based loop index)
- Updated 9 path references throughout the file
- Separated variant.id (metadata) from directory names (numeric index)
- Added examples and clarifications for agent implementation

## Impact

- MCP calls: 13 → 0 (-100%)
- Execution time: ~120s → ~60s (-50%)
- Variant divergence: Medium → High
- Path consistency: Broken → Fixed

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 14:39:53 +08:00
catlog22
c0921cd5ff feat(ui-design): add optional layout-specific token extension
- Allow agent to create layout-specific tokens if needed
- Use `--layout-*` prefix for layout-specific CSS variables
- Keep prompt minimal - let agent decide when extension is needed
- Examples: --layout-spacing-navbar-height, --layout-size-sidebar-width

Benefits:
-  Flexible token system (core + layout-specific)
-  Agent autonomy (decides when to extend)
-  Clear naming convention (--layout-* prefix)
-  Minimal workflow changes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 14:25:27 +08:00
catlog22
cb6e44efde refactor(ui-design): optimize workflow phases and token refinement strategy
**generate.md - Fix CSS variable naming mismatch**:
- Move token conversion to Phase 1.6 (before agent generation)
- Add Phase 1.7 to extract actual variable names from tokens.css
- Update Phase 2a agent prompt to read tokens.css directly
- Eliminate variable name guessing - agent uses actual file reference
- Remove redundant token conversion from Phase 2b

Benefits:
-  Eliminates CSS variable name mismatches
-  Single source of truth (tokens.css)
-  More reliable agent generation
-  Easier debugging

**consolidate.md - Replace MCP research with philosophy-driven refinement**:
- Remove variant-specific MCP trend research (4 queries per variant)
- Use design_attributes from extraction phase as refinement rules
- Apply philosophy-driven token generation (no external calls)
- Preserve variant divergence through anti_keywords constraints
- Faster execution (~30-60s saved per variant)

Benefits:
-  Better divergence preservation
-  Faster workflow execution
-  Pure AI-driven refinement
-  Consistent with extraction phase philosophy

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 13:24:48 +08:00
catlog22
e3f8283386 docs(ui-design): eliminate output-then-save ambiguity in workflow documentation
Clarified file writing patterns across UI design workflows to prevent confusion
between "generate content as output then save" vs "direct write to file" approaches.

Changes:
- extract.md: Merged Phase 2 & 3 to unify style synthesis and file write operations
  * Updated phase title to emphasize direct file writing
  * Added explicit note about internal processing without context output
  * Consolidated parse-and-write step into single atomic operation

- imitate-auto.md: Added clarifying comments for orchestrator file transformation
  * Documented that Phase 2 uses orchestrator-level read-process-write pattern
  * Explained this as performance optimization to bypass consolidate phase

The entire UI design workflow now consistently follows clear file operation patterns
with no ambiguous intermediate output steps.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 12:55:41 +08:00
catlog22
a1c1c95bf4 fix(ui-design): use mcp__exa__web_search_exa for design trend research and URL analysis
- Replace mcp__exa__get_code_context_exa with mcp__exa__web_search_exa in consolidate.md
  for trend research queries (colors, typography, layout, contrast, accessibility)
- Add Phase 0.75 URL Content Analysis in imitate-auto.md for screenshot fallback mode
- Use web_search_exa for design pattern extraction from URLs when screenshots unavailable
- Update workflow documentation to reflect new MCP tool usage

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 12:37:34 +08:00
catlog22
4e48803424 fix(ui-design): ensure component templates include CSS placeholders
Fix critical CSS loading issue where component templates were missing
style references due to contradictory instructions.

Changes:
- Require all templates (pages and components) to generate complete HTML5 documents
- Components now use full document structure with isolated body content
- Guarantees <head> tag presence for CSS placeholder injection
- Update validation to enforce <!DOCTYPE html> requirement
- Update documentation to reflect unified template approach

This ensures ui-instantiate-prototypes.sh can reliably inject STRUCTURAL_CSS
and TOKEN_CSS placeholders, fixing component styling issues.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 12:30:17 +08:00
catlog22
36728b6e59 refactor(ui-design-agent): remove script execution details and clarify agent responsibilities
- Remove detailed shell script integration documentation (convert_tokens_to_css.sh, ui-instantiate-prototypes.sh)
- Scripts are orchestrator's responsibility, not agent's
- Simplify Performance Optimization section to focus on architecture concept
- Clarify Layer 1 (agent's creative work) vs Layer 2 (orchestrator's file operations)
- Keep agent documentation focused on design generation, MCP research, and file writing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 11:26:51 +08:00
catlog22
9c1131e384 refactor(ui-design-agent): enhance MCP integration and add detailed shell script documentation
- Remove Code Index MCP integration (focus on design trends only)
- Replace mcp__exa__get_code_context_exa with mcp__exa__web_search_exa for design trend research
- Add detailed shell script integration documentation:
  - convert_tokens_to_css.sh: Token JSON to CSS conversion with usage patterns and error handling
  - ui-instantiate-prototypes.sh: Template instantiation with auto-detection and mode options
- Update MCP use cases to focus on design trends, color/typography, and accessibility patterns
- Clarify that agent uses web search for current design trends, not code implementation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 11:24:40 +08:00
catlog22
a2a608f3ca refactor(ui-design): enhance imitate-auto workflow with key features and interactive confirmation 2025-10-10 11:12:34 +08:00
catlog22
83155ab662 refactor(ui-design-agent): optimize structure and remove version info
**Changes**:
- Merged duplicate Reference section into Design Standards
- Simplified Core Capabilities quality standards
- Consolidated Tool Operations sections
- Removed Version & Changelog section (40 lines)
- Reduced from 693 to 578 lines (16.6% reduction)

**Key improvements**:
- Eliminated content duplication (Token System, Quality Standards)
- Improved document flow and readability
- All technical details and requirements preserved
- Version history now maintained in CHANGELOG.md only

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 10:31:47 +08:00
catlog22
af7ff3a86a refactor(ui-design): enhance execution clarity and file writing process in consolidate command 2025-10-10 10:22:32 +08:00
11 changed files with 2183 additions and 757 deletions

View File

@@ -12,7 +12,6 @@ description: |
Integration points:
- Exa MCP: Design trend research, modern UI patterns, implementation best practices
- Code Index MCP: Codebase pattern discovery, existing implementation analysis
color: orange
---
@@ -33,25 +32,13 @@ You are a specialized **UI Design Agent** that executes design generation tasks
- `layout-strategies.json`: MCP-researched layout variant definitions
- `tokens.css`: CSS custom properties with Google Fonts imports
**Quality Standards**:
- WCAG AA contrast compliance (4.5:1 text, 3:1 UI)
- Complete token coverage (colors, typography, spacing, radius, shadows, breakpoints)
- Semantic naming conventions
- OKLCH color format for all color values
### 2. Layout Strategy Generation
**Invoked by**: `consolidate.md` Phase 2.5
**Input**: Project context from synthesis-specification.md
**Task**: Research and generate adaptive layout strategies
**Task**: Research and generate adaptive layout strategies via Exa MCP (2024-2025 trends)
**Process**:
- Query Exa MCP for modern UI layout trends (2024-2025)
- Extract project type and tech stack context
- Generate 3-5 layout strategies with semantic names
- Document rationale and application guidelines
**Output**: layout-strategies.json with strategy definitions
**Output**: layout-strategies.json with strategy definitions and rationale
### 3. UI Prototype Generation
@@ -70,13 +57,40 @@ You are a specialized **UI Design Agent** that executes design generation tasks
- `{target}-layout-{id}.html`: Style-agnostic HTML structure
- `{target}-layout-{id}.css`: Token-driven structural CSS
**Quality Standards**:
- 🎯 **ADAPTIVE**: Multi-device responsive (375px+, 768px+, 1024px+)
- 🔄 **STYLE-SWITCHABLE**: Runtime theme switching via token swapping
- 🏗️ **SEMANTIC**: HTML5 structure with proper element hierarchy
-**ACCESSIBLE**: ARIA attributes for WCAG AA compliance
- 📱 **MOBILE-FIRST**: Progressive enhancement approach
- 🎨 **TOKEN-DRIVEN**: Zero hardcoded values
**⚠️ CRITICAL: CSS Placeholder Links**
When generating HTML templates, you MUST include these EXACT placeholder links in the `<head>` section:
```html
<link rel="stylesheet" href="{{STRUCTURAL_CSS}}">
<link rel="stylesheet" href="{{TOKEN_CSS}}">
```
**Placeholder Rules**:
1. Use EXACTLY `{{STRUCTURAL_CSS}}` and `{{TOKEN_CSS}}` with double curly braces
2. Place in `<head>` AFTER `<meta>` tags, BEFORE `</head>` closing tag
3. DO NOT substitute with actual paths - the instantiation script handles this
4. DO NOT add any other CSS `<link>` tags
5. These enable runtime style switching for all variants
**Example HTML Template Structure**:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{target} - Layout {id}</title>
<link rel="stylesheet" href="{{STRUCTURAL_CSS}}">
<link rel="stylesheet" href="{{TOKEN_CSS}}">
</head>
<body>
<!-- Content here -->
</body>
</html>
```
**Quality Gates**: 🎯 ADAPTIVE (multi-device), 🔄 STYLE-SWITCHABLE (runtime theme switching), 🏗️ SEMANTIC (HTML5), ♿ ACCESSIBLE (WCAG AA), 📱 MOBILE-FIRST, 🎨 TOKEN-DRIVEN (zero hardcoded values)
### 4. Consistency Validation
@@ -84,11 +98,7 @@ You are a specialized **UI Design Agent** that executes design generation tasks
**Input**: Multiple target prototypes for same style/layout combination
**Task**: Validate cross-target design consistency
**Deliverables**:
- Consistency reports identifying shared component variations
- Token usage verification
- Accessibility compliance checks
- Layout strategy adherence validation
**Deliverables**: Consistency reports, token usage verification, accessibility compliance checks, layout strategy adherence validation
## Design Standards
@@ -215,8 +225,104 @@ You are a specialized **UI Design Agent** that executes design generation tasks
- Use relative units (rem, em, %, vw/vh) over fixed pixels
- Support container queries where appropriate
### Token Reference
**Color Tokens** (OKLCH format mandatory):
- Base: `--background`, `--foreground`, `--card`, `--card-foreground`
- Brand: `--primary`, `--primary-foreground`, `--secondary`, `--secondary-foreground`
- UI States: `--muted`, `--muted-foreground`, `--accent`, `--accent-foreground`, `--destructive`, `--destructive-foreground`
- Elements: `--border`, `--input`, `--ring`
- Charts: `--chart-1` through `--chart-5`
- Sidebar: `--sidebar`, `--sidebar-foreground`, `--sidebar-primary`, `--sidebar-primary-foreground`, `--sidebar-accent`, `--sidebar-accent-foreground`, `--sidebar-border`, `--sidebar-ring`
**Typography Tokens**:
- `--font-sans`: Primary body font (Google Fonts with fallbacks)
- `--font-serif`: Serif font for headings/emphasis
- `--font-mono`: Monospace for code/technical content
**Visual Effect Tokens**:
- Radius: `--radius` (base), `--radius-sm`, `--radius-md`, `--radius-lg`, `--radius-xl`
- Shadows: `--shadow-2xs`, `--shadow-xs`, `--shadow-sm`, `--shadow`, `--shadow-md`, `--shadow-lg`, `--shadow-xl`, `--shadow-2xl`
- Spacing: `--spacing` (base unit, typically 0.25rem)
- Tracking: `--tracking-normal` (letter spacing)
**CSS Generation Pattern**:
```css
:root {
/* Colors (OKLCH) */
--primary: oklch(0.5555 0.15 270);
--background: oklch(1.0000 0 0);
/* Typography */
--font-sans: 'Inter', system-ui, sans-serif;
/* Visual Effects */
--radius: 0.5rem;
--shadow-sm: 0 1px 3px 0 hsl(0 0% 0% / 0.1);
--spacing: 0.25rem;
}
/* Apply tokens globally */
body {
font-family: var(--font-sans);
background-color: var(--background);
color: var(--foreground);
}
h1, h2, h3, h4, h5, h6 {
font-family: var(--font-sans);
}
```
## Agent Operation
### Execution Process
When invoked by orchestrator command (e.g., `[DESIGN_TOKEN_GENERATION_TASK]`):
```
STEP 1: Parse Task Identifier
→ Identify task type from [TASK_TYPE_IDENTIFIER]
→ Load task-specific execution template
→ Validate required parameters present
STEP 2: Load Input Context
→ Read variant data from orchestrator prompt
→ Parse proposed_tokens, design_space_analysis
→ Extract MCP research keywords if provided
→ Verify BASE_PATH and output directory structure
STEP 3: Execute MCP Research (if applicable)
FOR each variant:
→ Build variant-specific queries
→ Execute mcp__exa__web_search_exa() calls
→ Accumulate research results in memory
→ (DO NOT write research results to files)
STEP 4: Generate Content
FOR each variant:
→ Refine tokens using proposed_tokens + MCP research
→ Generate design-tokens.json content
→ Generate style-guide.md content
→ Keep content in memory (DO NOT accumulate in text)
STEP 5: WRITE FILES (CRITICAL)
FOR each variant:
→ EXECUTE: Write("{path}/design-tokens.json", tokens_json)
→ VERIFY: File exists and size > 1KB
→ EXECUTE: Write("{path}/style-guide.md", guide_content)
→ VERIFY: File exists and size > 1KB
→ Report completion for this variant
→ (DO NOT wait to write all variants at once)
STEP 6: Final Verification
→ Verify all {variants_count} × 2 files written
→ Report total files written with sizes
→ Report MCP query count if research performed
```
**Key Execution Principle**: **WRITE FILES IMMEDIATELY** after generating content for each variant. DO NOT accumulate all content and try to output at the end.
### Invocation Model
You are invoked by orchestrator commands to execute specific generation tasks:
@@ -272,15 +378,17 @@ You are invoked by orchestrator commands to execute specific generation tasks:
### Performance Optimization
**Two-Layer Generation**:
- **Layer 1**: Generate style-agnostic templates (creative, expensive)
- **Layer 2**: Instantiate style-specific prototypes (fast file operations)
- **Performance gain**: S× faster (S = style variant count)
**Two-Layer Generation Architecture**:
- **Layer 1 (Your Responsibility)**: Generate style-agnostic layout templates (creative work)
- HTML structure with semantic markup
- Structural CSS with CSS custom property references
- One template per layout variant per target
- **Layer 2 (Orchestrator Responsibility)**: Instantiate style-specific prototypes
- Token conversion (JSON → CSS)
- Template instantiation (L×T templates → S×L×T prototypes)
- Performance: S× faster than generating all combinations individually
**Script Integration**:
- `convert_tokens_to_css.sh`: Token JSON → CSS conversion (~200ms)
- `ui-instantiate-prototypes.sh`: Template instantiation (~5-10s for full matrix)
- Auto-detection of configuration from directory structure
**Your Focus**: Generate high-quality, reusable templates. Orchestrator handles file operations and instantiation.
### Scope & Boundaries
@@ -305,60 +413,35 @@ You are invoked by orchestrator commands to execute specific generation tasks:
**Exa MCP: Design Research & Trends**
*Use Cases*:
1. **Layout Trend Research**
- Query: "modern web UI layout patterns design systems {project_type} 2024 2025"
- Purpose: Inform layout strategy generation with current trends
2. **Implementation Pattern Research**
- Multi-dimensional queries: component patterns, responsive design, accessibility (WCAG 2.2), HTML semantics, CSS architecture
- Purpose: Inform template generation with modern best practices
1. **Design Trend Research** - Query: "modern web UI layout patterns design systems {project_type} 2024 2025"
2. **Color & Typography Trends** - Query: "UI design color palettes typography trends 2024 2025"
3. **Accessibility Patterns** - Query: "WCAG 2.2 accessibility design patterns best practices 2024"
*Best Practices*:
- Use `tokensNum="dynamic"` for token efficiency
- Use `numResults=5` (default) for sufficient coverage
- Include 2024-2025 in search terms for current trends
- Extract context (tech stack, project type) before querying
- Focus on design trends, not technical implementation
*Tool Usage*:
```javascript
// Generic pattern
research_results = mcp__exa__get_code_context_exa(
query="specific topic + context + year range",
tokensNum="dynamic"
)
// Web search for trends
// Design trend research
trend_results = mcp__exa__web_search_exa(
query="UI design trends {domain} 2024",
query="modern UI design color palette trends {domain} 2024 2025",
numResults=5
)
```
**Code Index MCP: Pattern Discovery**
*Use Cases*:
1. **Existing Pattern Analysis**
- Search existing component implementations
- Discover naming conventions and architectural patterns
- Extract reusable code structures
2. **File Discovery & Verification**
- Find generated template files
- Verify output structure completeness
- Validate file organization
*Tool Usage*:
```javascript
// Find patterns
patterns = mcp__code-index__search_code_advanced(
pattern="component.*interface|class.*Component",
file_pattern="*.{tsx,jsx,ts,js}"
// Accessibility research
accessibility_results = mcp__exa__web_search_exa(
query="WCAG 2.2 accessibility contrast patterns best practices 2024",
numResults=5
)
// Discover files
templates = mcp__code-index__find_files(pattern="*template*.{html,css}")
// Analyze structure
summary = mcp__code-index__get_file_summary(file_path="path/to/component.tsx")
// Layout pattern research
layout_results = mcp__exa__web_search_exa(
query="modern web layout design systems responsive patterns 2024",
numResults=5
)
```
### Tool Operations
@@ -390,54 +473,6 @@ summary = mcp__code-index__get_file_summary(file_path="path/to/component.tsx")
✅ Written: style-1/style-guide.md (8.3 KB)
```
**Script Execution**:
```bash
# Token conversion
cat design-tokens.json | ~/.claude/scripts/convert_tokens_to_css.sh > tokens.css
# Prototype instantiation
~/.claude/scripts/ui-instantiate-prototypes.sh {prototypes_dir} \
--session-id {id} \
--mode {page|component}
```
**Agent Delegation Pattern**:
```javascript
Task(ui-design-agent): "
[TASK_TYPE_IDENTIFIER]
Clear task description with context and requirements
## Context
- Key parameters and input files
- Quality standards and constraints
- BASE_PATH: {absolute_path_to_output_directory}
## File Write Instructions
Generate and WRITE files directly using Write() tool:
1. File 1:
Path: {absolute_path}/file1.json
Content: [specification]
2. File 2:
Path: {absolute_path}/file2.md
Content: [specification]
## Instructions
- Use Write() tool for each file with provided absolute paths
- Create directories if needed: Bash('mkdir -p {directory}')
- Verify each write operation succeeds
- Report completion with file paths and sizes
## Expected Final Report
✅ Written: file1.json (12.5 KB)
✅ Written: file2.md (8.3 KB)
DO NOT return file contents as text - write them directly to the file system.
"
```
## Quality Assurance
### Validation Checks
@@ -504,86 +539,50 @@ Task(ui-design-agent): "
- Recovery: Adjust OKLCH lightness (L) channel, regenerate tokens
- Prevention: Test contrast ratios during token generation
## Reference
## Key Reminders
### Token System Reference
### ALWAYS:
**Color Tokens** (OKLCH format mandatory):
- Base: `--background`, `--foreground`, `--card`, `--card-foreground`
- Brand: `--primary`, `--primary-foreground`, `--secondary`, `--secondary-foreground`
- UI States: `--muted`, `--muted-foreground`, `--accent`, `--accent-foreground`, `--destructive`, `--destructive-foreground`
- Elements: `--border`, `--input`, `--ring`
- Charts: `--chart-1` through `--chart-5`
- Sidebar: `--sidebar`, `--sidebar-foreground`, `--sidebar-primary`, `--sidebar-primary-foreground`, `--sidebar-accent`, `--sidebar-accent-foreground`, `--sidebar-border`, `--sidebar-ring`
**File Writing**:
- ✅ Use Write() tool for EVERY output file - this is your PRIMARY responsibility
- ✅ Write files IMMEDIATELY after generating content for each variant/target
- ✅ Verify each Write() operation succeeds before proceeding to next file
- ✅ Use EXACT paths provided by orchestrator without modification
- ✅ Report completion with file paths and sizes after each write
**Typography Tokens**:
- `--font-sans`: Primary body font (Google Fonts with fallbacks)
- `--font-serif`: Serif font for headings/emphasis
- `--font-mono`: Monospace for code/technical content
**Task Execution**:
- ✅ Parse task identifier ([DESIGN_TOKEN_GENERATION_TASK], etc.) first
- ✅ Execute MCP research when design_space_analysis is provided
- ✅ Follow the 6-step execution process sequentially
- ✅ Maintain variant independence - research and write separately for each
- ✅ Validate outputs against quality gates (WCAG AA, token completeness, OKLCH format)
**Visual Effect Tokens**:
- Radius: `--radius` (base), `--radius-sm`, `--radius-md`, `--radius-lg`, `--radius-xl`
- Shadows: `--shadow-2xs`, `--shadow-xs`, `--shadow-sm`, `--shadow`, `--shadow-md`, `--shadow-lg`, `--shadow-xl`, `--shadow-2xl`
- Spacing: `--spacing` (base unit, typically 0.25rem)
- Tracking: `--tracking-normal` (letter spacing)
**Quality Standards**:
- ✅ Apply all design standards automatically (WCAG AA, OKLCH, semantic naming)
- ✅ Include Google Fonts imports in CSS with fallback stacks
- ✅ Generate complete token coverage (colors, typography, spacing, radius, shadows, breakpoints)
- ✅ Use mobile-first responsive design with token-based breakpoints
- ✅ Implement semantic HTML5 with ARIA attributes
**CSS Generation Pattern**:
```css
:root {
/* Colors (OKLCH) */
--primary: oklch(0.5555 0.15 270);
--background: oklch(1.0000 0 0);
### NEVER:
/* Typography */
--font-sans: 'Inter', system-ui, sans-serif;
**File Writing**:
- ❌ Return file contents as text with labeled sections (e.g., "## File 1: design-tokens.json\n{content}")
- ❌ Accumulate all variant content and try to output at once
- ❌ Skip Write() operations and expect orchestrator to write files
- ❌ Modify provided paths or use relative paths
- ❌ Continue to next variant before completing current variant's file writes
/* Visual Effects */
--radius: 0.5rem;
--shadow-sm: 0 1px 3px 0 hsl(0 0% 0% / 0.1);
--spacing: 0.25rem;
}
**Task Execution**:
- ❌ Mix multiple targets into a single template (respect target independence)
- ❌ Skip MCP research when design_space_analysis is provided
- ❌ Generate variant N+1 before variant N's files are written
- ❌ Return research results as files (keep in memory for token refinement)
- ❌ Assume default values without checking orchestrator prompt
/* Apply tokens globally */
body {
font-family: var(--font-sans);
background-color: var(--background);
color: var(--foreground);
}
h1, h2, h3, h4, h5, h6 {
font-family: var(--font-sans);
}
```
### Version & Changelog
**Version**: 4.2.0
**Last Updated**: 2025-10-09
**Changelog**:
- **4.2.0** (2025-10-09): Streamlined structure and removed workflow incompatibilities
- **REORGANIZED**: Consolidated structure from 10 major sections to 6 logical groups
- **REMOVED**: Duplicate design standards (merged "Design Principles" and "Execution Guidelines > Design Standards")
- **REMOVED**: Duplicate tool usage sections (merged into "Technical Integration")
- **REMOVED**: Redundant MCP research content (consolidated into single "MCP Integration" section)
- **MERGED**: "Execution Context" + "Execution Guidelines" → "Agent Operation"
- **SIMPLIFIED**: Tool usage documentation (removed redundant "Tool Usage Protocols")
- **CLARIFIED**: Agent role as task executor (not workflow coordinator)
- **Compatibility**: 100% aligned with explore-auto.md and generate.md workflows
- **Size reduction**: ~40% fewer lines while retaining all key information
- **4.1.0** (2025-10-09): Integrated design.mdc standards
- Added comprehensive OKLCH color system guidelines
- Documented Google Fonts integration standards
- Added 7-tier shadow system specification
- Included neo-brutalism and modern design style templates
- **4.0.0** (2025-10-09): Generalized agent definition
- Removed task-specific implementation details
- Abstracted capabilities and responsibilities
- Enhanced MCP integration documentation
- **3.0.0** (2025-10-09): Task-focused architecture
- Added consolidate.md and generate.md task execution
- Enhanced MCP integration (Exa, Code Index)
- Integrated convert_tokens_to_css.sh and ui-instantiate-prototypes.sh
**Quality Violations**:
- ❌ Use hardcoded colors/fonts/spacing instead of tokens
- ❌ Generate tokens without OKLCH format for colors
- ❌ Skip WCAG AA contrast validation
- ❌ Omit Google Fonts imports or fallback stacks
- ❌ Create incomplete token categories

View File

@@ -2,18 +2,6 @@
name: consolidate
description: Consolidate style variants into independent design systems and plan layout strategies
usage: /workflow:ui-design:consolidate [--base-path <path>] [--session <id>] [--variants <count>] [--layout-variants <count>]
argument-hint: "[--base-path \".workflow/WFS-xxx/design-run-xxx\"] [--variants 3] [--layout-variants 3]"
parameters:
- name: --variants
type: number
default: all available variants from style-cards.json
description: "Number of style variants to consolidate (1-N). Processes first N variants from style-cards.json. Creates style-N directories."
- name: --session
type: string
description: "Workflow session ID (e.g., WFS-auth). Finds latest design run in session directory."
- name: --base-path
type: string
description: "Custom base path for input/output. Overrides --session if provided."
examples:
- /workflow:ui-design:consolidate --base-path ".workflow/WFS-auth/design-run-20250109-143022" --variants 3
- /workflow:ui-design:consolidate --session WFS-auth --variants 2
@@ -89,7 +77,7 @@ IF exists(design_space_path):
design_space_analysis = Read(design_space_path)
REPORT: "📊 Loaded design space analysis with {len(design_space_analysis.divergent_directions)} variant directions"
ELSE:
REPORT: "⚠️ No design space analysis found - trend research will be skipped"
REPORT: "⚠️ No design space analysis found - will refine tokens from proposed_tokens only"
```
### Phase 4: Design System Synthesis (Agent Execution)
@@ -100,20 +88,35 @@ REPORT: "🤖 Using agent for separate design system generation..."
# Create output directories
Bash(mkdir -p "{base_path}/style-consolidation/style-{{1..{variants_count}}}")
# Prepare agent task prompt
# Prepare agent task prompt with clear task identifier
agent_task_prompt = """
Generate {variants_count} independent production-ready design systems with external trend research and WRITE them to the file system.
[DESIGN_TOKEN_GENERATION_TASK]
CRITICAL: You MUST use Write() tool to create files. DO NOT return file contents as text.
## Task Summary
Generate {variants_count} independent design systems using philosophy-driven refinement and WRITE files directly (NO MCP calls).
## Context
SESSION: {session_id}
MODE: Separate design system generation with MCP trend research
MODE: Separate design system generation with philosophy-driven refinement (NO MCP)
BASE_PATH: {base_path}
VARIANTS TO PROCESS: {variants_count}
## Variant Data
{FOR each variant IN selected_variants:
CRITICAL PATH MAPPING:
- Variant 1 (id: {variant.id}) → Output directory: style-1/
- Variant 2 (id: {variant.id}) → Output directory: style-2/
- Variant N (id: {variant.id}) → Output directory: style-N/
Use loop index (1-based) for directory names, NOT variant.id.
{FOR each variant IN selected_variants with index N (1-based):
---
Variant ID: {variant.id} | Name: {variant.name}
VARIANT INDEX: {N} (use this for directory: style-{N}/)
Variant ID: {variant.id} (metadata only, DO NOT use in paths)
Name: {variant.name}
Description: {variant.description}
Design Philosophy: {variant.design_philosophy}
Proposed Tokens: {JSON.stringify(variant.proposed_tokens, null, 2)}
@@ -123,81 +126,85 @@ VARIANTS TO PROCESS: {variants_count}
{IF design_context: DESIGN CONTEXT (from brainstorming): {design_context}}
{IF design_space_analysis:
## Design Space Analysis (for MCP Research)
## Design Space Analysis (for Philosophy-Driven Refinement)
{JSON.stringify(design_space_analysis, null, 2)}
Note: Each variant has search_keywords and anti_keywords for trend research.
Note: Each variant has design_attributes and anti_keywords for token refinement.
Use philosophy_name and design_attributes to guide token generation WITHOUT external research.
}
## Task
For EACH variant (1 to {variants_count}):
1. **Perform Variant-Specific Trend Research** (if design space analysis available)
2. **Refine design tokens** using research insights
1. **Load variant's design philosophy and attributes** (from design_space_analysis)
2. **Refine design tokens** using philosophy-driven strategy (NO external research)
3. **Generate and WRITE 2 files** to the file system
## Step 1: Variant-Specific Trend Research (MCP)
## Step 1: Load Design Philosophy (No MCP Calls)
IF design_space_analysis is provided, FOR EACH variant:
IF design_space_analysis is provided:
FOR EACH variant:
1. **Extract Design Direction**: Load philosophy_name, design_attributes, search_keywords, anti_keywords
2. **Use as Refinement Guide**: Apply philosophy and attributes to token generation
3. **Enforce Constraints**: Avoid characteristics listed in anti_keywords
4. **Maintain Divergence**: Ensure tokens differ from other variants based on attributes
1. **Extract Research Parameters** from design space analysis:
- philosophy_name: The variant's design philosophy
- search_keywords: Keywords for trend research
- anti_keywords: Patterns to avoid
ELSE:
Refine tokens based solely on variant's proposed_tokens and design_philosophy from style-cards.json
2. **Build Variant-Specific Queries**:
```javascript
queries = [
`{philosophy_name} UI design color palettes {search_keywords[:3]} 2024 2025`,
`{philosophy_name} typography trends {search_keywords[:3]} web design 2024`,
`{philosophy_name} layout patterns {search_keywords[:3]} design systems 2024`,
`design systems {philosophy_name} NOT {anti_keywords[:2]}`
]
```
## Philosophy-Driven Refinement Strategy
3. **Execute MCP Searches**:
```javascript
trend_research = {
colors: mcp__exa__get_code_context_exa(query=queries[0], tokensNum=2000),
typography: mcp__exa__get_code_context_exa(query=queries[1], tokensNum=2000),
layout: mcp__exa__get_code_context_exa(query=queries[2], tokensNum=2000),
contrast: mcp__exa__get_code_context_exa(query=queries[3], tokensNum=2000)
}
```
**Core Principles**:
- Use variant's design_attributes as primary guide (color saturation, visual weight, formality, organic/geometric, innovation, density)
- Apply anti_keywords as explicit constraints during token selection
- Ensure WCAG AA accessibility using built-in AI knowledge (4.5:1 text, 3:1 UI)
- Preserve maximum contrast between variants from extraction phase
4. **Shared Accessibility Research** (execute once, apply to all variants):
```javascript
accessibility_guidelines = mcp__exa__get_code_context_exa(
query="WCAG 2.2 accessibility color contrast ARIA best practices 2024",
tokensNum=1500
)
```
5. **Use Research Results** to inform token refinement:
- Color token refinement guided by `trend_research.colors`
- Typography refinement guided by `trend_research.typography`
- Layout spacing informed by `trend_research.layout`
- Contrast validation using `trend_research.contrast` and `accessibility_guidelines`
IF design_space_analysis is NOT provided:
- Skip trend research
- Refine tokens based solely on variant's existing philosophy and proposed tokens
**Refinement Process** (Apply to each variant):
1. **Colors**: Generate palette based on saturation attribute
- "monochrome" → low chroma values (oklch L 0.00-0.02 H)
- "vibrant" → high chroma values (oklch L 0.20-0.30 H)
2. **Typography**: Select font families matching formality level
- "playful" → rounded, friendly fonts
- "luxury" → serif, elegant fonts
3. **Spacing**: Apply density attribute
- "spacious" → larger spacing scale (e.g., "4": "1.5rem")
- "compact" → smaller spacing scale (e.g., "4": "0.75rem")
4. **Shadows**: Match visual weight
- "minimal" → subtle shadows with low opacity
- "bold" → strong shadows with higher spread
5. **Border Radius**: Align with organic/geometric attribute
- "organic" → larger radius values (xl: "1.5rem")
- "brutalist" → minimal radius (xl: "0.125rem")
6. **Innovation**: Influence overall token adventurousness
- "timeless" → conservative, proven values
- "experimental" → unconventional token combinations
## Step 2: Refinement Rules (apply to each variant)
1. **Complete Token Coverage**: Ensure all categories present (colors, typography, spacing, etc.)
2. **Fill Gaps**: Generate missing tokens based on variant's philosophy and trend research
2. **Fill Gaps**: Generate missing tokens based on variant's philosophy and design_attributes
3. **Maintain Style Identity**: Preserve unique characteristics from proposed tokens
4. **Semantic Naming**: Use clear names (e.g., "brand-primary" not "color-1")
5. **Accessibility**: Validate WCAG AA contrast using accessibility guidelines (4.5:1 text, 3:1 UI)
5. **Accessibility**: Validate WCAG AA contrast using built-in AI knowledge (4.5:1 text, 3:1 UI)
6. **OKLCH Format**: All colors use oklch(L C H / A) format
7. **Design Philosophy**: Expand variant's design philosophy using trend insights
8. **Trend Integration**: Incorporate modern trends from MCP research while maintaining variant identity
7. **Design Philosophy**: Expand variant's design philosophy based on its attributes
8. **Divergence Preservation**: Apply anti_keywords to prevent convergence with other variants
## Step 3: File Write Instructions
For EACH variant {variant_id} (1 to {variants_count}), WRITE these 2 files:
## Step 3: FILE WRITE OPERATIONS (CRITICAL)
### File 1: Design Tokens
**Path**: {base_path}/style-consolidation/style-{variant_id}/design-tokens.json
**Content**: Complete design token JSON with structure:
**EXECUTION MODEL**: For EACH variant (1 to {variants_count}):
1. Load design philosophy and attributes
2. Refine tokens using philosophy-driven strategy
3. **IMMEDIATELY Write() files - DO NOT accumulate, DO NOT return as text**
### Required Write Operations Per Variant
For variant with loop index {N} (e.g., 1st variant = N=1, 2nd variant = N=2), execute these Write() operations:
#### Write Operation 1: Design Tokens
**Path**: `{base_path}/style-consolidation/style-{N}/design-tokens.json`
**Method**: `Write(path, JSON.stringify(tokens, null, 2))`
**Example**: For 1st variant → `{base_path}/style-consolidation/style-1/design-tokens.json`
**Content Structure**:
```json
{
"colors": {
@@ -215,9 +222,11 @@ For EACH variant {variant_id} (1 to {variants_count}), WRITE these 2 files:
}
```
### File 2: Style Guide
**Path**: {base_path}/style-consolidation/style-{variant_id}/style-guide.md
**Content**: Markdown documentation with structure:
#### Write Operation 2: Style Guide
**Path**: `{base_path}/style-consolidation/style-{N}/style-guide.md`
**Method**: `Write(path, guide_markdown_content)`
**Example**: For 2nd variant → `{base_path}/style-consolidation/style-2/style-guide.md`
**Content Structure**:
```markdown
# Design System Style Guide - {variant.name}
@@ -241,42 +250,63 @@ For EACH variant {variant_id} (1 to {variants_count}), WRITE these 2 files:
- Focus indicators are clearly visible
```
## Write Operation Instructions
- Use Write() tool for each file with the absolute paths provided above
- Verify each write operation succeeds
- Report completion with file paths and sizes
- DO NOT return file contents as text
### Execution Checklist (Per Variant)
## Example Write Operations
For each variant from 1 to {variants_count} (use loop index N):
- [ ] Extract variant's philosophy, design_attributes, and anti_keywords
- [ ] Apply philosophy-driven refinement strategy to proposed_tokens
- [ ] Generate complete token set following refinement rules
- [ ] **EXECUTE**: `Write("{base_path}/style-consolidation/style-{N}/design-tokens.json", tokens_json)`
- Example: 1st variant → `style-1/design-tokens.json`
- [ ] **EXECUTE**: `Write("{base_path}/style-consolidation/style-{N}/style-guide.md", guide_content)`
- Example: 1st variant → `style-1/style-guide.md`
- [ ] Verify both files written successfully
### Verification After Each Write
```javascript
// For variant 1
Write("{base_path}/style-consolidation/style-1/design-tokens.json", JSON.stringify(tokens, null, 2))
Write("{base_path}/style-consolidation/style-1/style-guide.md", guide_content)
// For variant 2
Write("{base_path}/style-consolidation/style-2/design-tokens.json", JSON.stringify(tokens, null, 2))
Write("{base_path}/style-consolidation/style-2/style-guide.md", guide_content)
```
// Immediately after Write() for each file (use loop index N):
Bash(`ls -lh "{base_path}/style-consolidation/style-{N}/"`)
// Example: For 1st variant → ls -lh ".../style-1/"
// Confirm file exists and has reasonable size (>1KB)
## Expected Final Report
Report which files were written and their sizes:
After completing all {variants_count} variants, report:
```
✅ Written: {base_path}/style-consolidation/style-1/design-tokens.json (12.5 KB)
✅ Written: {base_path}/style-consolidation/style-1/style-guide.md (8.3 KB)
✅ Written: {base_path}/style-consolidation/style-2/design-tokens.json (11.8 KB)
Written: {base_path}/style-consolidation/style-2/style-guide.md (7.9 KB)
... (for all {variants_count} variants)
✅ Variant 1 ({variant_name}):
- design-tokens.json: 12.5 KB | {token_count} tokens
- style-guide.md: 8.3 KB
Variant 2 ({variant_name}):
- design-tokens.json: 11.8 KB | {token_count} tokens
- style-guide.md: 7.9 KB
... (for all variants)
Summary: {variants_count} design systems generated with philosophy-driven refinement (zero MCP calls)
```
## Critical Requirements
- Generate files for ALL {variants_count} variants
- Use sequential IDs: style-1, style-2, ..., style-{variants_count}
- Each variant must be complete and independent
- Maintain consistent structure across all variants
- Write files directly using Write() tool - do NOT return contents as text
## KEY REMINDERS (CRITICAL)
**ALWAYS:**
- Use Write() tool for EVERY file - this is your PRIMARY responsibility
- Write files immediately after generating content for each variant
- Verify each Write() operation succeeds before proceeding
- Use loop index (N) for directory names: `{base_path}/style-consolidation/style-{N}/...`
- 1st variant → `style-1/`, 2nd variant → `style-2/`, etc.
- DO NOT use variant.id in paths (metadata only)
- Apply philosophy-driven refinement strategy for each variant
- Maintain variant divergence using design_attributes and anti_keywords
- Report completion with file paths and sizes
**NEVER:**
- Return file contents as text with labeled sections
- Accumulate all content and try to output at once
- Skip Write() operations and expect orchestrator to write files
- Use relative paths or modify provided paths
- Use external research or MCP calls (pure AI refinement only)
- Generate variant N+1 before completing variant N writes
"""
# Execute agent task
# Dispatch to ui-design-agent with task prompt
Task(subagent_type="ui-design-agent", description="Generate {variants_count} separate design systems", prompt=agent_task_prompt)
REPORT: "✅ Agent task dispatched for {variants_count} design systems"
@@ -286,14 +316,14 @@ REPORT: "✅ Agent task dispatched for {variants_count} design systems"
```bash
REPORT: "📝 Verifying agent file creation for {variants_count} design systems..."
# Verify each variant's files were created by agent
FOR variant_id IN range(1, variants_count + 1):
tokens_path = "{base_path}/style-consolidation/style-{variant_id}/design-tokens.json"
guide_path = "{base_path}/style-consolidation/style-{variant_id}/style-guide.md"
# Verify each variant's files were created by agent (use numeric index)
FOR N IN range(1, variants_count + 1):
tokens_path = "{base_path}/style-consolidation/style-{N}/design-tokens.json"
guide_path = "{base_path}/style-consolidation/style-{N}/style-guide.md"
# Verify files exist
VERIFY: exists(tokens_path), "Design tokens not created by agent for style-{variant_id}"
VERIFY: exists(guide_path), "Style guide not created by agent for style-{variant_id}"
VERIFY: exists(tokens_path), "Design tokens not created by agent for style-{N}"
VERIFY: exists(guide_path), "Style guide not created by agent for style-{N}"
# Optional: Validate JSON structure
TRY:
@@ -305,9 +335,9 @@ FOR variant_id IN range(1, variants_count + 1):
tokens_size = get_file_size(tokens_path)
guide_size = get_file_size(guide_path)
REPORT: " ✅ style-{variant_id}/ verified ({tokens_size} KB tokens, {guide_size} KB guide)"
REPORT: " ✅ style-{N}/ verified ({tokens_size} KB tokens, {guide_size} KB guide)"
CATCH error:
ERROR: "Validation failed for style-{variant_id}: {error}"
ERROR: "Validation failed for style-{N}: {error}"
REPORT: " ⚠️ Files exist but validation failed - review agent output"
REPORT: "✅ All {variants_count} design systems verified"
@@ -328,7 +358,7 @@ TodoWrite({todos: [
{content: "Load session and style cards", status: "completed", activeForm: "Loading style cards"},
{content: "Select variants for consolidation", status: "completed", activeForm: "Selecting variants"},
{content: "Load design context and space analysis", status: "completed", activeForm: "Loading context"},
{content: "Perform variant-specific trend research", status: "completed", activeForm: "Researching design trends"},
{content: "Apply philosophy-driven refinement", status: "completed", activeForm: "Refining design tokens"},
{content: "Generate design systems via agent", status: "completed", activeForm: "Generating design systems"},
{content: "Process agent results and write files", status: "completed", activeForm: "Writing output files"}
]});
@@ -339,10 +369,11 @@ TodoWrite({todos: [
✅ Design system consolidation complete for session: {session_id}
{IF design_space_analysis:
🔍 Trend Research Performed:
- {variants_count} × 4 variant-specific MCP queries ({variants_count * 4} total)
- 1 shared accessibility research query
- Each variant refined with independent trend guidance
🎨 Philosophy-Driven Refinement:
- {variants_count} design systems generated from AI-analyzed philosophies
- Zero MCP calls (pure AI token refinement)
- Divergence preserved from extraction phase design_attributes
- Each variant maintains unique style identity via anti_keywords
}
Generated {variants_count} independent design systems:
@@ -398,22 +429,22 @@ Layout planning is now handled in the generate phase for each specific target.
## Key Features
1. **Variant-Specific Trend Research** 🆕 - Agent performs independent MCP queries for each variant (4 queries per variant); Uses design space analysis keywords from extraction phase; Each variant researches its specific design philosophy; Shared accessibility research applied to all variants; Eliminates convergence by maintaining variant-specific research
2. **Agent-Driven Architecture** - Uses ui-design-agent for multi-file generation and MCP research; Parallel generation of N independent design systems with external trend integration; Structured output parsing with labeled sections; Agent handles both research and synthesis
3. **Separate Design Systems (Matrix-Ready)** - Generates N independent design systems (one per variant); Each variant maintains unique style identity enhanced by trend research; Provides style foundation for style × layout matrix exploration in generate phase
4. **Token Refinement with Trend Integration** 🆕 - Reads `proposed_tokens` from style cards; Loads design space analysis for research parameters; Agent performs MCP trend research per variant; Refines tokens using research insights while maintaining style identity
5. **Complete Design System Output** - design-tokens.json (CSS tokens per variant); style-guide.md (documentation per variant with trend insights)
6. **Production-Ready Quality** - WCAG AA accessibility validation with MCP research; OKLCH color format for perceptual uniformity; Semantic token naming; Complete token coverage; Modern trends integration
7. **Streamlined Workflow** - Sequential phases with clear responsibilities; Agent handles MCP research, token refinement, and file generation; Reproducible with deterministic structure; Context-aware (integrates brainstorming and design space analysis)
8. **Clear Separation of Concerns** - Consolidation focuses on style systems with trend research; Extraction focuses on Claude-native analysis; Layout planning delegated to generate phase for target-specific optimization
1. **Philosophy-Driven Refinement** - Pure AI token refinement based on design_space_analysis from extraction phase; Uses variant-specific philosophies and design_attributes as refinement rules; Preserves maximum contrast without external trend pollution; Zero MCP calls = faster execution + better divergence preservation
2. **Agent-Driven Architecture** - Uses ui-design-agent for multi-file generation; Processes N variants with philosophy-guided synthesis; Structured output with deterministic token generation; Agent applies design attributes directly to token values
3. **Separate Design Systems (Matrix-Ready)** - Generates N independent design systems (one per variant); Each variant maintains unique style identity from extraction phase; Provides style foundation for style × layout matrix exploration in generate phase
4. **Token Refinement with AI Guidance** - Reads `proposed_tokens` from style cards; Loads design_space_analysis for philosophy and attributes; Applies attributes to token generation (saturation → chroma, density → spacing, etc.); Refines tokens while maintaining variant divergence through anti_keywords
5. **Complete Design System Output** - design-tokens.json (CSS tokens per variant); style-guide.md (documentation per variant with philosophy explanation)
6. **Production-Ready Quality** - WCAG AA accessibility validation using built-in AI knowledge (4.5:1 text, 3:1 UI); OKLCH color format for perceptual uniformity; Semantic token naming; Complete token coverage
7. **Streamlined Workflow** - Sequential phases with clear responsibilities; Agent handles philosophy-driven token refinement and file generation; Reproducible with deterministic structure; Context-aware (integrates brainstorming and design space analysis); ~30-60s faster without MCP overhead
8. **Divergence Preservation** - Strictly follows design_space_analysis constraints from extraction; Applies anti_keywords to prevent variant convergence; Maintains maximum variant contrast through attribute-driven generation; No external research = pure philosophical consistency
## Integration Points
- **Input**:
- `style-cards.json` from `/workflow:ui-design:extract` (with `proposed_tokens`)
- `design-space-analysis.json` from extraction phase (with search keywords for MCP research)
- `design-space-analysis.json` from extraction phase (with philosophy and design_attributes)
- `--variants` parameter (default: all variants)
- **Output**: Style Systems: `style-consolidation/style-{n}/design-tokens.json` and `style-guide.md` for each variant (enhanced with trend research)
- **Output**: Style Systems: `style-consolidation/style-{N}/design-tokens.json` and `style-guide.md` for each variant (refined with philosophy-driven approach), where N is the variant index (1, 2, 3...)
- **Context**: Optional `synthesis-specification.md` or `ui-designer/analysis.md`
- **Auto Integration**: Automatically triggered by `/workflow:ui-design:explore-auto` workflow
- **Next Command**: `/workflow:ui-design:generate --style-variants N --targets "..." --layout-variants M` performs target-specific layout planning

View File

@@ -0,0 +1,390 @@
---
name: explore-auto-v2
description: Exploratory UI design workflow with style-centric batch generation
usage: /workflow:ui-design:explore-auto-v2 [--prompt "<desc>"] [--images "<glob>"] [--targets "<list>"] [--target-type "page|component"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--batch-plan]
examples:
- /workflow:ui-design:explore-auto-v2 --prompt "Generate 3 style variants for modern blog: home, article, author"
- /workflow:ui-design:explore-auto-v2 --prompt "SaaS dashboard and settings with 2 layout options"
- /workflow:ui-design:explore-auto-v2 --images "refs/*.png" --prompt "E-commerce: home, product, cart" --style-variants 3 --layout-variants 3
- /workflow:ui-design:explore-auto-v2 --session WFS-auth --images "refs/*.png"
- /workflow:ui-design:explore-auto-v2 --targets "navbar,hero" --target-type "component" --style-variants 3 --layout-variants 2
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*), Task(conceptual-planning-agent)
---
# UI Design Auto Workflow Command
## Overview & Execution Model
**Fully autonomous orchestrator**: Executes all design phases sequentially from style extraction to design integration, with optional batch planning.
**Unified Target System**: Generates `style_variants × layout_variants × targets` prototypes, where targets can be:
- **Pages** (full-page layouts): home, dashboard, settings, etc.
- **Components** (isolated UI elements): navbar, card, hero, form, etc.
- **Mixed**: Can combine both in a single workflow
**Autonomous Flow** (⚠️ CONTINUOUS EXECUTION - DO NOT STOP):
1. User triggers: `/workflow:ui-design:explore-auto-v2 [params]`
2. Phase 0c: Target confirmation → User confirms → **IMMEDIATELY triggers Phase 1**
3. Phase 1 (style-extract) → **WAIT for completion** → Auto-continues
4. Phase 2 (style-consolidate) → **WAIT for completion** → Auto-continues
5. **Phase 3 (ui-generate-v2)****WAIT for completion** → Auto-continues
6. Phase 4 (design-update) → **WAIT for completion** → Auto-continues
7. Phase 5 (batch-plan, optional) → Reports completion
**Phase Transition Mechanism**:
- **Phase 0c (User Interaction)**: User confirms targets → IMMEDIATELY triggers Phase 1
- **Phase 1-5 (Autonomous)**: `SlashCommand` is BLOCKING - execution pauses until completion
- Upon each phase completion: Automatically process output and execute next phase
- No additional user interaction after Phase 0c confirmation
**Auto-Continue Mechanism**: TodoWrite tracks phase status. Upon each phase completion, you MUST immediately construct and execute the next phase command. No user intervention required. The workflow is NOT complete until reaching Phase 4 (or Phase 5 if --batch-plan).
**Target Type Detection**: Automatically inferred from prompt/targets, or explicitly set via `--target-type`.
## Core Rules
1. **Start Immediately**: TodoWrite initialization → Phase 1 execution
2. **No Preliminary Validation**: Sub-commands handle their own validation
3. **Parse & Pass**: Extract data from each output for next phase
4. **Default to All**: When selecting variants/prototypes, use ALL generated items
5. **Track Progress**: Update TodoWrite after each phase
6. **⚠️ CRITICAL: DO NOT STOP** - This is a continuous multi-phase workflow. After each SlashCommand completes, you MUST wait for completion, then immediately execute the next phase. Workflow is NOT complete until Phase 4 (or Phase 5 if --batch-plan).
## Parameter Requirements
**Optional Parameters** (all have smart defaults):
- `--targets "<list>"`: Comma-separated targets (pages/components) to generate (inferred from prompt/session if omitted)
- `--target-type "page|component|auto"`: Explicitly set target type (default: `auto` - intelligent detection)
- `--session <id>`: Workflow session ID (standalone mode if omitted)
- `--images "<glob>"`: Reference image paths (default: `design-refs/*`)
- `--prompt "<description>"`: Design style and target description
- `--style-variants <count>`: Style variants (default: inferred from prompt or 3, range: 1-5)
- `--layout-variants <count>`: Layout variants per style (default: inferred or 3, range: 1-5)
- `--batch-plan`: Auto-generate implementation tasks after design-update
**Legacy Parameters** (maintained for backward compatibility):
- `--pages "<list>"`: Alias for `--targets` with `--target-type page`
- `--components "<list>"`: Alias for `--targets` with `--target-type component`
**Input Rules**:
- Must provide at least one: `--images` or `--prompt` or `--targets`
- Multiple parameters can be combined for guided analysis
- If `--targets` not provided, intelligently inferred from prompt/session
**Supported Target Types**:
- **Pages** (full layouts): home, dashboard, settings, profile, login, etc.
- **Components** (UI elements):
- Navigation: navbar, header, menu, breadcrumb, tabs, sidebar
- Content: hero, card, list, table, grid, timeline
- Input: form, search, filter, input-group
- Feedback: modal, alert, toast, badge, progress
- Media: gallery, carousel, video-player, image-card
- Other: footer, pagination, dropdown, tooltip, avatar
**Intelligent Prompt Parsing**: Extracts variant counts from natural language:
- "Generate **3 style variants**" → `--style-variants 3`
- "**2 layout options**" → `--layout-variants 2`
- "Create **4 styles** with **2 layouts each**" → `--style-variants 4 --layout-variants 2`
- Explicit flags override prompt inference
## Execution Modes
**Matrix Mode** (style-centric):
- Generates `style_variants × layout_variants × targets` prototypes
- **Phase 1**: `style_variants` style options with design_attributes (extract)
- **Phase 2**: `style_variants` independent design systems (consolidate)
- **Phase 3**: Style-centric batch generation (generate-v2)
- Sub-phase 1: `targets × layout_variants` target-specific layout plans
- **Sub-phase 2**: `S` style-centric agents (each handles `L×T` combinations)
- Sub-phase 3: `style_variants × layout_variants × targets` final prototypes
- Performance: Efficient parallel execution with S agents
- Quality: HTML structure adapts to design_attributes
- Pages: Full-page layouts with complete structure
- Components: Isolated elements with minimal wrapper
**Integrated vs. Standalone**:
- `--session` flag determines session integration or standalone execution
## 6-Phase Execution
### Phase 0a: Intelligent Prompt Parsing
```bash
# Parse variant counts from prompt or use explicit/default values
IF --prompt AND (NOT --style-variants OR NOT --layout-variants):
style_variants = regex_extract(prompt, r"(\d+)\s*style") OR --style-variants OR 3
layout_variants = regex_extract(prompt, r"(\d+)\s*layout") OR --layout-variants OR 3
ELSE:
style_variants = --style-variants OR 3
layout_variants = --layout-variants OR 3
VALIDATE: 1 <= style_variants <= 5, 1 <= layout_variants <= 5
```
### Phase 0b: Run Initialization & Directory Setup
```bash
run_id = "run-$(date +%Y%m%d-%H%M%S)"
base_path = --session ? ".workflow/WFS-{session}/design-${run_id}" : ".workflow/.design/${run_id}"
Bash(mkdir -p "${base_path}/{style-extraction,style-consolidation,prototypes}")
Write({base_path}/.run-metadata.json): {
"run_id": "${run_id}", "session_id": "${session_id}", "timestamp": "...",
"workflow": "ui-design:auto-v2",
"version": "2.0",
"architecture": "style-centric-batch-generation",
"parameters": { "style_variants": ${style_variants}, "layout_variants": ${layout_variants},
"targets": "${inferred_target_list}", "target_type": "${target_type}",
"prompt": "${prompt_text}", "images": "${images_pattern}" },
"status": "in_progress",
"performance_mode": "optimized"
}
```
### Phase 0c: Unified Target Inference with Intelligent Type Detection
```bash
# Priority: --pages/--components (legacy) → --targets → --prompt analysis → synthesis → default
target_list = []; target_type = "auto"; target_source = "none"
# Step 1-2: Explicit parameters (legacy or unified)
IF --pages: target_list = split(--pages); target_type = "page"; target_source = "explicit_legacy"
ELSE IF --components: target_list = split(--components); target_type = "component"; target_source = "explicit_legacy"
ELSE IF --targets:
target_list = split(--targets); target_source = "explicit"
target_type = --target-type != "auto" ? --target-type : detect_target_type(target_list)
# Step 3: Prompt analysis (Claude internal analysis)
ELSE IF --prompt:
analysis_result = analyze_prompt("{prompt_text}") # Extract targets, types, purpose
target_list = analysis_result.targets
target_type = analysis_result.primary_type OR detect_target_type(target_list)
target_source = "prompt_analysis"
# Step 4: Session synthesis
ELSE IF --session AND exists(synthesis-specification.md):
target_list = extract_targets_from_synthesis(); target_type = "page"; target_source = "synthesis"
# Step 5: Fallback
IF NOT target_list: target_list = ["home"]; target_type = "page"; target_source = "default"
# Validate and clean
validated_targets = [normalize(t) for t in target_list if is_valid(t)]
IF NOT validated_targets: validated_targets = ["home"]; target_type = "page"
IF --target-type != "auto": target_type = --target-type
# Interactive confirmation
DISPLAY_CONFIRMATION(target_type, target_source, validated_targets):
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
"{emoji} {LABEL} CONFIRMATION (v2.0 Style-Centric)"
"Type: {target_type} | Source: {target_source}"
"Targets ({count}): {', '.join(validated_targets)}"
"Performance: {style_variants} agent calls (vs {layout_variants * len(validated_targets)} in v1.0)"
"Options: 'continue/yes' | 'targets: a,b' | 'skip: x' | 'add: y' | 'type: page|component'"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
user_input = WAIT_FOR_USER_INPUT()
# Process user modifications
MATCH user_input:
"continue|yes|ok" → proceed
"targets: ..."validated_targets = parse_new_list()
"skip: ..."validated_targets = remove_items()
"add: ..."validated_targets = add_items()
"type: ..."target_type = extract_type()
default → proceed with current list
STORE: inferred_target_list, target_type, target_inference_source
# ⚠️ CRITICAL: User confirmation complete, IMMEDIATELY initialize TodoWrite and execute Phase 1
# This is the only user interaction point in the workflow
# After this point, all subsequent phases execute automatically without user intervention
```
**Helper Function: detect_target_type()**
```bash
detect_target_type(target_list):
page_keywords = ["home", "dashboard", "settings", "profile", "login", "signup", "auth", ...]
component_keywords = ["navbar", "header", "footer", "hero", "card", "button", "form", ...]
page_matches = count_matches(target_list, page_keywords + ["page", "screen", "view"])
component_matches = count_matches(target_list, component_keywords + ["component", "widget"])
RETURN "component" IF component_matches > page_matches ELSE "page"
```
### Phase 1: Style Extraction
```bash
command = "/workflow:ui-design:extract --base-path \"{base_path}\" " +
(--images ? "--images \"{images}\" " : "") +
(--prompt ? "--prompt \"{prompt}\" " : "") +
"--variants {style_variants} --mode explore"
SlashCommand(command)
# Output: {style_variants} style cards with design_attributes
# SlashCommand blocks until phase complete
# Upon completion, IMMEDIATELY execute Phase 2 (auto-continue)
```
### Phase 2: Style Consolidation
```bash
command = "/workflow:ui-design:consolidate --base-path \"{base_path}\" " +
"--variants {style_variants}"
SlashCommand(command)
# Output: {style_variants} independent design systems with tokens.css
# SlashCommand blocks until phase complete
# Upon completion, IMMEDIATELY execute Phase 3 (auto-continue)
```
### Phase 3: Style-Centric Matrix UI Generation
```bash
targets_string = ",".join(inferred_target_list)
command = "/workflow:ui-design:generate-v2 --base-path \"{base_path}\" " +
"--targets \"{targets_string}\" --target-type \"{target_type}\" " +
"--style-variants {style_variants} --layout-variants {layout_variants}"
total = style_variants × layout_variants × len(inferred_target_list)
agent_calls = style_variants
REPORT: "🚀 Phase 3: {type_icon} {targets_string} | Matrix: {s}×{l}×{n} = {total} prototypes"
REPORT: " → Agent calls: {agent_calls} style-centric agents"
REPORT: " → Layout planning: {len(inferred_target_list)}×{layout_variants} target-specific layouts"
REPORT: " → Style-centric generation: Each of {style_variants} agents handles {layout_variants}×{len(inferred_target_list)} combinations"
SlashCommand(command)
# SlashCommand blocks until phase complete
# Upon completion, IMMEDIATELY execute Phase 4 (auto-continue)
# Output:
# - {target}-layout-{l}.json (target-specific layout plans)
# - {target}-style-{s}-layout-{l}.html (final prototypes with style-aware structure)
# - compare.html (interactive matrix view)
# - PREVIEW.md (usage instructions)
```
### Phase 4: Design System Integration
```bash
command = "/workflow:ui-design:update" + (--session ? " --session {session_id}" : "")
SlashCommand(command)
# SlashCommand blocks until phase complete
# Upon completion:
# - If --batch-plan flag present: IMMEDIATELY execute Phase 5 (auto-continue)
# - If no --batch-plan: Workflow complete, display final report
```
### Phase 5: Batch Task Generation (Optional)
```bash
IF --batch-plan:
FOR target IN inferred_target_list:
task_desc = "Implement {target} {target_type} based on design system"
SlashCommand("/workflow:plan --agent \"{task_desc}\"")
```
## TodoWrite Pattern
```javascript
// Initialize IMMEDIATELY after Phase 0c user confirmation to track multi-phase execution
TodoWrite({todos: [
{"content": "Execute style extraction", "status": "in_progress", "activeForm": "Executing..."},
{"content": "Execute style consolidation", "status": "pending", "activeForm": "Executing..."},
{"content": "Execute style-centric UI generation", "status": "pending", "activeForm": "Executing..."},
{"content": "Execute design integration", "status": "pending", "activeForm": "Executing..."}
]})
// ⚠️ CRITICAL: After EACH SlashCommand completion (Phase 1-5), you MUST:
// 1. SlashCommand blocks and returns when phase is complete
// 2. Update current phase: status → "completed"
// 3. Update next phase: status → "in_progress"
// 4. IMMEDIATELY execute next phase SlashCommand (auto-continue)
// This ensures continuous workflow tracking and prevents premature stopping
```
## Key Features
- **🚀 Performance**: Style-centric batch generation with S agent calls
- **🎨 Style-Aware**: HTML structure adapts to design_attributes
- **✅ Perfect Consistency**: Each style by single agent
- **📦 Autonomous**: No user intervention required between phases
- **🧠 Intelligent**: Parses natural language, infers targets/types
- **🔄 Reproducible**: Deterministic flow with isolated run directories
- **🎯 Flexible**: Supports pages, components, or mixed targets
## Examples
### 1. Page Mode (Prompt Inference)
```bash
/workflow:ui-design:explore-auto-v2 --prompt "Modern blog: home, article, author"
# Result: 27 prototypes (3×3×3)
```
### 2. Custom Matrix with Session
```bash
/workflow:ui-design:explore-auto-v2 --session WFS-ecommerce --images "refs/*.png" --style-variants 2 --layout-variants 2
# Result: 2×2×N prototypes
```
### 3. Component Mode
```bash
/workflow:ui-design:explore-auto-v2 --targets "navbar,hero" --target-type "component" --style-variants 3 --layout-variants 2
# Result: 12 prototypes (3×2×2) - components with minimal wrapper
```
### 4. Intelligent Parsing + Batch Planning
```bash
/workflow:ui-design:explore-auto-v2 --prompt "Create 4 styles with 2 layouts for dashboard and settings" --batch-plan
# Result: 16 prototypes (4×2×2) + auto-generated tasks
```
### 5. Large Scale
```bash
/workflow:ui-design:explore-auto-v2 --targets "home,dashboard,settings,profile" --style-variants 3 --layout-variants 3
# Result: 36 prototypes (3×3×4)
```
## Completion Output
```
✅ UI Design Explore-Auto Workflow Complete!
Architecture: Style-Centric Batch Generation
Run ID: {run_id} | Session: {session_id or "standalone"}
Type: {icon} {target_type} | Matrix: {s}×{l}×{n} = {total} prototypes
Phase 1: {s} style variants with design_attributes (extract)
Phase 2: {s} design systems with tokens.css (consolidate)
Phase 3: Style-centric batch generation (generate-v2)
- {n}×{l} target-specific layout plans
- {s} style-centric agents (each handled {l}×{n} combinations)
- {s}×{l}×{n} = {total} final prototypes with style-aware structure
Phase 4: Brainstorming artifacts updated
[Phase 5: {n} implementation tasks created] # if --batch-plan
Agent Execution:
✅ Style-centric agents: {s} agents total
✅ Each agent handles: {l}×{n} combinations
Design Quality:
✅ Style-Aware Structure: HTML adapts to design_attributes
✅ Style Consistency: PERFECT (each style by single agent)
✅ Token-Driven Styling: 100% var() usage
📂 {base_path}/
├── style-extraction/ ({s} style cards + design-space-analysis.json)
├── style-consolidation/ ({s} design systems with tokens.css)
├── prototypes/
│ ├── _templates/ ({n}×{l} layout JSON files)
│ └── ... ({total} final prototypes)
└── .run-metadata.json
🌐 Preview: {base_path}/prototypes/compare.html
- Interactive {s}×{l} matrix view
- Side-by-side comparison
- Target-specific layouts with style-aware structure
- Toggle between {n} targets
{icon} Targets: {', '.join(targets)} (type: {target_type})
- Each target has {l} custom-designed layouts
- Each style × target × layout has unique HTML structure (not just CSS!)
- Layout plans stored as structured JSON
Next: [/workflow:execute] OR [Open compare.html → Select → /workflow:plan]
```

View File

@@ -2,7 +2,6 @@
name: explore-auto
description: Exploratory UI design workflow - Generate and compare multiple style × layout combinations (3×3 matrix exploration)
usage: /workflow:ui-design:explore-auto [--prompt "<desc>"] [--images "<glob>"] [--targets "<list>"] [--target-type "page|component"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--batch-plan]
argument-hint: "[--prompt \"Modern SaaS with 3 styles\"] [--images \"refs/*.png\"] [--targets \"dashboard,auth,navbar,hero\"] [--target-type \"auto\"] [--session WFS-xxx] [--style-variants 3] [--layout-variants 3]"
examples:
- /workflow:ui-design:explore-auto --prompt "Generate 3 style variants for modern blog: home, article, author"
- /workflow:ui-design:explore-auto --prompt "SaaS dashboard and settings with 2 layout options"
@@ -25,15 +24,15 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
- **Components** (isolated UI elements): navbar, card, hero, form, etc.
- **Mixed**: Can combine both in a single workflow
**Autonomous Flow**:
**Autonomous Flow** (⚠️ CONTINUOUS EXECUTION - DO NOT STOP):
1. User triggers: `/workflow:ui-design:explore-auto [params]`
2. Phase 1 (style-extract) → Auto-continues
3. Phase 2 (style-consolidate) → Auto-continues
4. Phase 3 (ui-generate) → Auto-continues with unified target list
5. Phase 4 (design-update) → Auto-continues
2. Phase 1 (style-extract) → **WAIT for completion** Auto-continues
3. Phase 2 (style-consolidate) → **WAIT for completion** Auto-continues
4. Phase 3 (ui-generate) → **WAIT for completion** Auto-continues with unified target list
5. Phase 4 (design-update) → **WAIT for completion** Auto-continues
6. Phase 5 (batch-plan, optional) → Reports completion
**Auto-Continue Mechanism**: TodoWrite tracks phase status. Upon completion, coordinator constructs next command and executes immediately. No user intervention required.
**Auto-Continue Mechanism**: TodoWrite tracks phase status. Upon each phase completion, you MUST immediately construct and execute the next phase command. No user intervention required. The workflow is NOT complete until reaching Phase 4 (or Phase 5 if --batch-plan).
**Target Type Detection**: Automatically inferred from prompt/targets, or explicitly set via `--target-type`.
@@ -44,6 +43,7 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
3. **Parse & Pass**: Extract data from each output for next phase
4. **Default to All**: When selecting variants/prototypes, use ALL generated items
5. **Track Progress**: Update TodoWrite after each phase
6. **⚠️ CRITICAL: DO NOT STOP** - This is a continuous multi-phase workflow. After each SlashCommand completes, you MUST wait for completion, then immediately execute the next phase. Workflow is NOT complete until Phase 4 (or Phase 5 if --batch-plan).
## Parameter Requirements
@@ -202,15 +202,21 @@ detect_target_type(target_list):
command = "/workflow:ui-design:extract --base-path \"{base_path}\" " +
(--images ? "--images \"{images}\" " : "") +
(--prompt ? "--prompt \"{prompt}\" " : "") +
"--variants {style_variants}"
SlashCommand(command) # → Phase 2
"--variants {style_variants} --mode explore"
SlashCommand(command)
# WAIT for extract command to complete, then IMMEDIATELY continue to Phase 2
# DO NOT STOP - Phase 2 must execute automatically
```
### Phase 2: Style Consolidation
```bash
command = "/workflow:ui-design:consolidate --base-path \"{base_path}\" " +
"--variants {style_variants}"
SlashCommand(command) # → Phase 3
SlashCommand(command)
# WAIT for consolidate command to complete, then IMMEDIATELY continue to Phase 3
# DO NOT STOP - Phase 3 must execute automatically
# Output: style_variants independent design systems (design tokens and style guides)
```
@@ -222,10 +228,13 @@ command = "/workflow:ui-design:generate --base-path \"{base_path}\" " +
"--style-variants {style_variants} --layout-variants {layout_variants}"
total = style_variants × layout_variants × len(inferred_target_list)
REPORT: "🚀 Phase 3: {type_icon} {targets_string} | Matrix: {s}×{l} | Total: {total} prototypes"
REPORT: "🚀 Phase 3: {type_icon} {targets_string} | Matrix: {s}×{l}×{n} = {total} prototypes"
REPORT: " → Layout planning: {len(inferred_target_list)}×{layout_variants} target-specific layouts"
SlashCommand(command) # → Phase 4
SlashCommand(command)
# WAIT for generate command to complete, then IMMEDIATELY continue to Phase 4
# DO NOT STOP - Phase 4 must execute automatically
# Output:
# - {target}-layout-{l}.json (target-specific layout plans)
# - {target}-style-{s}-layout-{l}.html (final prototypes)
@@ -235,7 +244,11 @@ SlashCommand(command) # → Phase 4
### Phase 4: Design System Integration
```bash
command = "/workflow:ui-design:update" + (--session ? " --session {session_id}" : "")
SlashCommand(command) # → Phase 5 if --batch-plan, else complete
SlashCommand(command)
# WAIT for update command to complete
# If --batch-plan flag present: IMMEDIATELY continue to Phase 5
# If no --batch-plan: Workflow complete, display final report
```
### Phase 5: Batch Task Generation (Optional)
@@ -248,13 +261,19 @@ IF --batch-plan:
## TodoWrite Pattern
```javascript
// Initialize at workflow start to track multi-phase execution
TodoWrite({todos: [
{"content": "Execute style extraction", "status": "in_progress", "activeForm": "Executing..."},
{"content": "Execute style consolidation", "status": "pending", "activeForm": "Executing..."},
{"content": "Execute UI generation", "status": "pending", "activeForm": "Executing..."},
{"content": "Execute design integration", "status": "pending", "activeForm": "Executing..."}
]})
// Update after each phase: current → completed, next → in_progress
// ⚠️ CRITICAL: After EACH phase completion, you MUST:
// 1. Update current phase: status → "completed"
// 2. Update next phase: status → "in_progress"
// 3. Continue to execute next phase immediately
// This ensures continuous workflow tracking and prevents premature stopping
```
## Key Features
@@ -300,7 +319,7 @@ TodoWrite({todos: [
✅ UI Design Explore-Auto Workflow Complete!
Run ID: {run_id} | Session: {session_id or "standalone"}
Type: {icon} {target_type} | Matrix: {s}×{l} ({total} prototypes)
Type: {icon} {target_type} | Matrix: {s}×{l}×{n} = {total} prototypes
Phase 1: {s} style variants (extract)
Phase 2: {s} design systems (consolidate)

View File

@@ -2,24 +2,6 @@
name: extract
description: Extract design style from reference images or text prompts using Claude's analysis
usage: /workflow:ui-design:extract [--base-path <path>] [--session <id>] [--images "<glob>"] [--prompt "<desc>"] [--variants <count>]
argument-hint: "[--base-path \".workflow/WFS-xxx/design-run-xxx\"] [--session WFS-xxx] [--images \"refs/*.png\"] [--prompt \"Modern minimalist\"] [--variants 3]"
parameters:
- name: --variants
type: number
default: 1
description: "Number of design variants to extract (1-5). Each variant will be maximally contrasting. Generates style-cards.json with variant-N IDs."
- name: --images
type: string
description: "Glob pattern for reference images (e.g., 'refs/*.png'). Supports PNG, JPG, WebP."
- name: --prompt
type: string
description: "Text description of desired style (e.g., 'Modern minimalist blog'). Can be combined with --images."
- name: --session
type: string
description: "Workflow session ID (e.g., WFS-auth). Creates design run in session directory."
- name: --base-path
type: string
description: "Custom base path for output. Overrides --session if provided."
examples:
- /workflow:ui-design:extract --images "design-refs/*.png" --variants 3
- /workflow:ui-design:extract --prompt "Modern minimalist blog, dark theme" --variants 3
@@ -85,16 +67,36 @@ CREATE: {base_path}/style-extraction/
### Phase 0.5: AI-Driven Design Space Divergence
```bash
# Step 1: Load project context
# Determine extraction mode
extraction_mode = --mode OR "auto"
IF extraction_mode == "auto":
extraction_mode = (variants_count == 1) ? "imitate" : "explore"
REPORT: "🔍 Auto-detected mode: {extraction_mode} (variants_count={variants_count})"
# Branch: Skip or Execute divergence analysis
IF extraction_mode == "imitate":
REPORT: "🎯 IMITATE MODE: High-fidelity single style extraction"
REPORT: " → Skipping design space divergence analysis"
REPORT: " → Proceeding to Phase 2 for direct style synthesis"
design_space_analysis = null
# Skip to Phase 2
GOTO Phase 2
# ELSE: REQUIRED execution path for explore mode
# ⚠️ CRITICAL: The following steps (Step 1-3) MUST be executed when extraction_mode == "explore"
# Step 1: Load project context (explore mode only)
project_context = ""
IF exists({base_path}/.brainstorming/synthesis-specification.md):
project_context = Read(synthesis-specification.md)
ELSE IF exists({base_path}/.brainstorming/ui-designer/analysis.md):
project_context = Read(ui-designer/analysis.md)
REPORT: "🎨 Analyzing design space to generate maximally contrasting directions..."
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🎨 EXPLORE MODE: Analyzing design space (REQUIRED)"
REPORT: " → Generating {variants_count} maximally contrasting directions"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# Step 2: AI-driven divergent direction generation
# Step 2: AI-driven divergent direction generation (REQUIRED)
divergence_prompt = """
Analyze user requirements and generate {variants_count} MAXIMALLY CONTRASTING design directions.
@@ -135,7 +137,7 @@ RULES: Output ONLY valid JSON, maximize inter-variant distance, ensure each vari
occupies distinct aesthetic region, avoid overlapping attributes
"""
# Execute AI analysis
# Execute AI analysis (REQUIRED in explore mode)
divergent_directions = parse_json(Claude_Native_Analysis(divergence_prompt))
REPORT: "✅ Generated {variants_count} contrasting design directions:"
@@ -144,22 +146,30 @@ FOR direction IN divergent_directions.divergent_directions:
design_space_analysis = divergent_directions
# Step 3: Save design space analysis for consolidation phase
Write({file_path: "{base_path}/style-extraction/design-space-analysis.json",
# Step 3: Save design space analysis for consolidation phase (REQUIRED)
# ⚠️ CRITICAL: This file MUST be generated in explore mode for downstream consolidation
output_file_path = "{base_path}/style-extraction/design-space-analysis.json"
Write({file_path: output_file_path,
content: JSON.stringify(design_space_analysis, null, 2)})
REPORT: "💾 Saved design space analysis to design-space-analysis.json"
# Verification step (REQUIRED)
VERIFY: file_exists(output_file_path) == true
REPORT: "✅ Verified: design-space-analysis.json exists ({file_size(output_file_path)} bytes)"
```
### Phase 2: Variant-Specific Style Synthesis (Claude Native Analysis)
### Phase 2: Variant-Specific Style Synthesis & Direct File Write
**Analysis Prompt Template**:
```
Generate {variants_count} design style proposals, each guided by its pre-analyzed design direction.
Generate {variants_count} design style proposals{IF extraction_mode == "explore": , each guided by its pre-analyzed design direction}.
INPUT MODE: {input_mode}
{IF input_mode IN ["image", "hybrid"]: VISUAL REFERENCES: {list of loaded images}}
{IF input_mode IN ["text", "hybrid"]: TEXT GUIDANCE: "{prompt_guidance}"}
{IF extraction_mode == "explore":
DESIGN SPACE ANALYSIS: {design_space_analysis summary}
VARIANT-SPECIFIC DESIGN DIRECTIONS:
@@ -171,20 +181,29 @@ SEARCH KEYWORDS: {direction.search_keywords}
ANTI-PATTERNS (avoid): {direction.anti_keywords}
RATIONALE: {direction.rationale}
---}
}
TASK: Generate {variants_count} design style variants where EACH variant:
TASK: Generate {variants_count} design style variant{IF variants_count > 1: s} where {IF extraction_mode == "explore": EACH variant}:
{IF extraction_mode == "explore":
1. Strictly follows its pre-defined design philosophy and attributes
2. Maintains maximum contrast with other variants' attributes
3. Incorporates its design direction and avoids its anti-patterns
}
{IF extraction_mode == "imitate":
1. Provides high-fidelity replication of reference design
2. Focuses on accurate extraction of visual characteristics
}
4. Uses OKLCH color space for all color values
5. Includes complete, production-ready design token proposals
6. Applies WCAG AA accessibility guidelines (4.5:1 text, 3:1 UI)
{IF extraction_mode == "explore":
CRITICAL RULES FOR CONTRAST:
- Variant-1 should feel completely different from Variant-2/3
- Use each variant's specific attribute scores (e.g., "monochrome" vs "vibrant")
- Each variant should embody its unique design direction
- If Variant-1 is "minimal/geometric", Variant-2 must be "bold/organic" or similar contrast
}
OUTPUT FORMAT: JSON matching this structure:
{"extraction_metadata": {"session_id": "...", "input_mode": "...", "timestamp": "...", "variants_count": N},
@@ -203,27 +222,31 @@ OUTPUT FORMAT: JSON matching this structure:
// Repeat for ALL {variants_count} variants
]}
RULES: Each variant must strictly adhere to pre-defined attributes; maximize visual contrast;
RULES: {IF extraction_mode == "explore": Each variant must strictly adhere to pre-defined attributes; maximize visual contrast;}
{IF extraction_mode == "imitate": Focus on high-fidelity replication;}
all colors in OKLCH format; complete token structures; semantic naming;
WCAG AA accessibility (4.5:1 text, 3:1 UI)
```
### Phase 3: Parse & Write Output
**Execution & File Write**:
```bash
style_cards_data = parse_json(claude_response)
Write({file_path: "{base_path}/style-extraction/style-cards.json", content: style_cards_data})
# Execute Claude Native Analysis (internal processing, no context output)
style_cards_json = Claude_Native_Analysis(synthesis_prompt)
# Write directly to file
Write({file_path: "{base_path}/style-extraction/style-cards.json", content: style_cards_json})
REPORT: "💾 Saved {variants_count} style variants to style-cards.json"
```
### Phase 4: Completion
### Phase 3: Completion
```javascript
TodoWrite({todos: [
{content: "Validate inputs and create directories", status: "completed", activeForm: "Validating inputs"},
{content: "Analyze design space for maximum contrast", status: "completed", activeForm: "Analyzing design space"},
{content: `Generate ${variants_count} divergent design directions`, status: "completed", activeForm: "Generating directions"},
{content: "Save design space analysis for consolidation", status: "completed", activeForm: "Saving design space analysis"},
{content: `Generate ${variants_count} contrasting style variants`, status: "completed", activeForm: "Generating variants"}
{content: extraction_mode == "explore" ? "Analyze design space for maximum contrast" : "Skip design space analysis (imitate mode)", status: "completed", activeForm: extraction_mode == "explore" ? "Analyzing design space" : "Skipping analysis"},
{content: extraction_mode == "explore" ? `Generate ${variants_count} divergent design directions (REQUIRED)` : "Prepare for high-fidelity extraction", status: "completed", activeForm: extraction_mode == "explore" ? "Generating directions" : "Preparing extraction"},
{content: extraction_mode == "explore" ? `Write and verify design-space-analysis.json (REQUIRED)` : "Skip design space output", status: "completed", activeForm: extraction_mode == "explore" ? "Writing and verifying file" : "Skipping output"},
{content: `Generate and write ${variants_count} ${extraction_mode == "explore" ? "contrasting" : "high-fidelity"} style variant${variants_count > 1 ? "s" : ""} to file`, status: "completed", activeForm: "Generating and writing variants"}
]});
```
@@ -231,25 +254,33 @@ TodoWrite({todos: [
```
✅ Style extraction complete for session: {session_id}
Mode: {extraction_mode == "imitate" ? "🎯 IMITATE (high-fidelity)" : "🎨 EXPLORE (contrast analysis)"}
Input mode: {input_mode}
{IF image mode: Images analyzed: {count}}
{IF prompt mode: Prompt: "{truncated_prompt}"}
{IF extraction_mode == "explore":
🎨 Design Space Analysis:
- Generated {variants_count} MAXIMALLY CONTRASTING design directions
- Min pairwise contrast distance: {design_space_analysis.contrast_verification.min_pairwise_distance}
- Strategy: {design_space_analysis.contrast_verification.strategy}
}
{IF extraction_mode == "imitate":
🎯 Imitation Mode:
- High-fidelity single style extraction
- Design space divergence skipped for faster execution
}
Generated {variants_count} style variant(s):
Generated {variants_count} style variant{variants_count > 1 ? "s" : ""}:
{FOR each card: - {card.name} ({card.id}) - {card.design_philosophy}}
📂 Outputs:
- {base_path}/style-extraction/style-cards.json
- {base_path}/style-extraction/design-space-analysis.json
{IF extraction_mode == "explore": - {base_path}/style-extraction/design-space-analysis.json}
Next: /workflow:ui-design:consolidate --session {session_id} --variants {variants_count} [--layout-variants <count>]
Note: When called from /workflow:ui-design:auto, consolidation is triggered automatically.
Note: When called from /workflow:ui-design:{extraction_mode == "imitate" ? "imitate" : "explore"}-auto, consolidation is triggered automatically.
```
## Output Structure
@@ -257,13 +288,13 @@ Note: When called from /workflow:ui-design:auto, consolidation is triggered auto
```
.workflow/WFS-{session}/design-{run_id}/style-extraction/
├── style-cards.json # Complete style variants with token proposals
└── design-space-analysis.json # Design directions for consolidation phase
└── design-space-analysis.json # Design directions (explore mode only)
OR (standalone mode):
.workflow/.design/{run_id}/style-extraction/
├── style-cards.json
└── design-space-analysis.json
└── design-space-analysis.json # Only in explore mode
```
### style-cards.json Format

View File

@@ -0,0 +1,546 @@
---
name: generate-v2
description: Generate UI prototypes using target-style-centric batch generation
usage: /workflow:ui-design:generate-v2 [--targets "<list>"] [--target-type "page|component"] [--base-path <path>] [--session <id>] [--style-variants <count>] [--layout-variants <count>]
examples:
- /workflow:ui-design:generate-v2 --session WFS-auth --targets "dashboard,settings" --style-variants 3 --layout-variants 3
- /workflow:ui-design:generate-v2 --base-path ".workflow/WFS-auth/design-run-20250109-143022" --targets "home,pricing"
- /workflow:ui-design:generate-v2 --targets "navbar,hero,card" --target-type "component" --style-variants 2 --layout-variants 2
allowed-tools: TodoWrite(*), Read(*), Write(*), Task(ui-design-agent), Bash(*)
---
# UI Generation Command (Target-Style-Centric Architecture)
**Executor**: → @ui-design-agent
**Parallel Generation**: Phase 2 → @ui-design-agent (T×S tasks, each handling L layouts)
## Overview
Generate production-ready UI prototypes (HTML/CSS) using **target-style-centric batch generation**. Each agent handles all layout variants for one target × one style combination, ensuring component isolation and focused generation.
## Core Philosophy
- **Target-Style-Centric**: Each of T×S agents generates L layouts for one target × one style
- **Component Isolation**: Tasks completely independent, preventing cross-component interference
- **Style-Aware Structure**: HTML DOM adapts based on design_attributes (density, visual_weight, etc.)
- **Performance Optimized**: T×S agent calls with highly focused scope per agent
- **Layout Inspiration**: Simple text-based research replaces complex JSON planning
- **Self-Contained CSS**: Agent reads design-tokens.json and creates independent CSS (no token.css reference)
- **Production-Ready**: Semantic HTML5, ARIA attributes, responsive design
## Execution Protocol
### Phase 1: Path Resolution & Context Loading
```bash
# 1. Determine base path
IF --base-path: base_path = {provided_base_path}
ELSE IF --session: base_path = find_latest_path_matching(".workflow/WFS-{session}/design-*")
ELSE: base_path = find_latest_path_matching(".workflow/.design/*")
# 2. Determine style variant count and layout variant count
style_variants = --style-variants OR auto_detect_from_consolidation()
layout_variants = --layout-variants OR 3
VALIDATE: 1 <= style_variants <= 5
VALIDATE: 1 <= layout_variants <= 5
# Validate against actual style directories
actual_style_count = count_directories({base_path}/style-consolidation/style-*)
IF actual_style_count == 0:
ERROR: "No style directories found"; SUGGEST: "Run /workflow:ui-design:consolidate first"; EXIT 1
IF style_variants > actual_style_count:
WARN: "⚠️ Requested {style_variants}, but only {actual_style_count} exist"
REPORT: " Available styles: {list_directories}"; style_variants = actual_style_count
REPORT: "✅ Validated style variants: {style_variants}"
# 3. Enhanced target list parsing with type detection
target_list = []; target_type = "page" # Default
# Priority 1: Unified --targets parameter
IF --targets:
raw_targets = {--targets value}
target_list = split_and_clean(raw_targets, delimiters=[",", ";", "、"])
target_list = [t.strip().lower().replace(" ", "-") for t in target_list if t.strip()]
target_type = --target-type provided ? {--target-type} : detect_target_type(target_list)
REPORT: "🎯 Using provided targets ({target_type}): {', '.join(target_list)}"
# Priority 2: Legacy --pages parameter
ELSE IF --pages:
raw_targets = {--pages value}
target_list = split_and_clean(raw_targets, delimiters=[",", ";", "、"])
target_list = [t.strip().lower().replace(" ", "-") for t in target_list if t.strip()]
target_type = "page"
REPORT: "📋 Using provided pages (legacy): {', '.join(target_list)}"
# Priority 3: Extract from synthesis-specification.md
ELSE IF --session:
synthesis_spec = Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md)
target_list = extract_targets_from_synthesis(synthesis_spec); target_type = "page"
REPORT: "📋 Extracted from synthesis: {', '.join(target_list)}"
# Priority 4: Detect from existing prototypes or default
ELSE:
target_list = detect_from_prototypes({base_path}/prototypes/) OR ["home"]; target_type = "page"
REPORT: "📋 Detected/default targets: {', '.join(target_list)}"
# 4. Validate target names
validated_targets = [t for t in target_list if regex_match(t, r"^[a-z0-9][a-z0-9_-]*$")]
invalid_targets = [t for t in target_list if t not in validated_targets]
IF invalid_targets: REPORT: "⚠️ Skipped invalid target names: {', '.join(invalid_targets)}"
VALIDATE: validated_targets not empty, "No valid targets found"
target_list = validated_targets
STORE: target_list, target_type
# 5. Verify design systems exist
FOR style_id IN range(1, style_variants + 1):
VERIFY: exists({base_path}/style-consolidation/style-{style_id}/design-tokens.json)
# 6. Load design space analysis (for style-aware generation)
design_space_path = "{base_path}/style-extraction/design-space-analysis.json"
IF exists(design_space_path):
design_space_analysis = Read(design_space_path)
REPORT: "📊 Loaded design space analysis with style attributes"
ELSE:
WARN: "⚠️ No design space analysis found - will use basic style generation"
design_space_analysis = null
# 7. Load requirements (if integrated mode)
IF --session:
synthesis_spec = Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md)
ELSE:
synthesis_spec = null
```
### Phase 1.5: Target Layout Inspiration
```bash
REPORT: "💡 Gathering layout inspiration for {len(target_list)} targets..."
CREATE: {base_path}/prototypes/_inspirations/
# For each target, gather layout inspiration via MCP search
FOR target IN target_list:
REPORT: " Researching '{target}' ({target_type}) layout patterns..."
# MCP search for layout patterns
search_query = f"common {target} {target_type} layout patterns variations best practices"
search_results = mcp__exa__web_search_exa(
query=search_query,
numResults=5
)
# Extract key layout patterns from search results
inspiration_content = f"""Layout Inspiration for '{target}' ({target_type})
Generated: {current_timestamp()}
Search Query: {search_query}
## Layout Patterns Identified
From web research, {layout_variants} distinct layout approaches:
Layout 1: [First structural pattern identified from search]
- Key characteristics: ...
- Structure approach: ...
Layout 2: [Second structural pattern]
- Key characteristics: ...
- Structure approach: ...
Layout 3: [Third structural pattern]
- Key characteristics: ...
- Structure approach: ...
## Reference Links
{format_search_results_urls(search_results)}
## Implementation Notes
- Each layout should be STRUCTURALLY DIFFERENT (not just CSS variations)
- Consider {target_type}-specific patterns (navigation, content areas, interactions)
- Adapt structure based on design_attributes in Phase 2
"""
# Write simple inspiration file
inspiration_file = f"{base_path}/prototypes/_inspirations/{target}-layout-ideas.txt"
Write(inspiration_file, inspiration_content)
REPORT: f" ✓ Created: {target}-layout-ideas.txt"
REPORT: f"✅ Phase 1.5 complete: Gathered inspiration for {len(target_list)} targets"
```
### Phase 2: Target-Style-Centric Batch Generation
**Strategy**: T×S target-style-centric agents, each generating L layouts for one target × one style.
**Performance**: T×S agent calls with component isolation
```bash
REPORT: "🎨 Phase 2: Launching {len(target_list)}×{style_variants}={len(target_list) * style_variants} target-style agents..."
REPORT: " Each agent generates {layout_variants} layouts for one component"
CREATE: {base_path}/prototypes/
# Launch ONE agent task PER TARGET × STYLE combination (parallel execution)
FOR target IN target_list:
# Load layout inspiration for this target
inspiration_path = f"{base_path}/prototypes/_inspirations/{target}-layout-ideas.txt"
FOR style_id IN range(1, style_variants + 1):
# Load style-specific context
style_tokens_path = f"{base_path}/style-consolidation/style-{style_id}/design-tokens.json"
style_guide_path = f"{base_path}/style-consolidation/style-{style_id}/style-guide.md"
# Extract design attributes for this style (if available)
IF design_space_analysis AND style_id <= len(design_space_analysis.divergent_directions):
design_attributes = design_space_analysis.divergent_directions[style_id - 1]
philosophy_name = design_attributes.philosophy_name
attributes_summary = JSON.stringify({
density: design_attributes.design_attributes.density,
visual_weight: design_attributes.design_attributes.visual_weight,
formality: design_attributes.design_attributes.formality,
organic_vs_geometric: design_attributes.design_attributes.organic_vs_geometric,
innovation: design_attributes.design_attributes.innovation
})
ELSE:
design_attributes = null
philosophy_name = f"Style {style_id}"
attributes_summary = "No design attributes available"
Task(ui-design-agent): """
[TARGET_STYLE_UI_GENERATION]
## 🎯 Mission
Generate {layout_variants} layout variants for: {target} × Style-{style_id} ({philosophy_name})
Output: {layout_variants × 2} files ({layout_variants} HTML + {layout_variants} CSS)
## 🎨 Style Context
PHILOSOPHY: {philosophy_name}
{IF design_attributes:
DESIGN_ATTRIBUTES: {attributes_summary}
Key impacts:
- density → DOM nesting depth, whitespace scale
- visual_weight → wrapper layers, border/shadow strength
- formality → semantic structure choices
- organic_vs_geometric → alignment, edge treatment
- innovation → layout adventurousness
}
## 📂 Input Resources
**Design System**:
- Design Tokens (JSON): {style_tokens_path}
- Style Guide: {style_guide_path}
**Layout Inspiration**: {inspiration_path}
Contains {layout_variants} distinct structural patterns
**Target**: {target} ({target_type})
## 🔄 Generation Steps (for each layout 1..{layout_variants})
**1. Read Inspiration**
- Load: {inspiration_path}
- Apply layout N pattern
**2. Read Design Tokens**
- Load: {style_tokens_path}
- Parse JSON structure and extract all design token values
- Understand token categories: colors, typography, spacing, shadows, borders, etc.
**3. Generate HTML Structure**
- Complete HTML5 document (<!DOCTYPE>, <html>, <head>, <body>)
- Semantic elements: <header>, <nav>, <main>, <section>, <article>, <footer>
- ARIA attributes: aria-label, role, aria-labelledby
- Responsive meta: <meta name="viewport" content="width=device-width, initial-scale=1">
- Include CSS reference: <link rel="stylesheet" href="{target}-style-{style_id}-layout-N.css">
- Example: For dashboard-style-1-layout-2.html, use <link rel="stylesheet" href="dashboard-style-1-layout-2.css">
{IF design_attributes:
**⚠️ Adapt DOM based on design_attributes:**
- density='spacious' → Flatter hierarchy
Example: <main><section class="card"></section></main>
- density='compact' → Deeper nesting
Example: <main><div class="grid"><div class="card-wrapper"><section></section></div></div></main>
- visual_weight='heavy' → Extra wrapper divs for layered effects
Example: <div class="border-container"><div class="content-wrapper">...</div></div>
- visual_weight='minimal' → Direct structure, minimal wrappers
Example: <section class="card">...</section>
- organic_vs_geometric → Affects alignment patterns and edge structure
}
**4. Generate Self-Contained CSS**
⚠️ Use design token values DIRECTLY from step 2 - create complete, independent CSS
**Required Token Usage** (from design-tokens.json):
- Colors: Use color values for backgrounds, text, borders
- Typography: Use font-family, font-size, font-weight, line-height values
- Spacing: Use spacing scale for margins, padding, gaps
- Borders: Use border-radius, border-width values
- Shadows: Use box-shadow values
- Breakpoints: Use breakpoint values for @media queries
{IF design_attributes:
**Apply design_attributes to token selection:**
- density='spacious' → Select larger spacing tokens
- density='compact' → Select smaller spacing tokens
- visual_weight='heavy' → Use stronger shadows, add borders
- visual_weight='minimal' → Use subtle/no shadows
- formality → Affects typography choices and structure
- organic_vs_geometric → Affects border-radius and alignment
}
**CSS Structure**:
- Complete styling: colors, typography, layout, spacing, effects
- Responsive design: Mobile-first with breakpoint-based @media
- Self-contained: No external dependencies or var() references
**5. Write Files IMMEDIATELY**
- Output paths:
- HTML: {base_path}/prototypes/{target}-style-{style_id}-layout-N.html
- CSS: {base_path}/prototypes/{target}-style-{style_id}-layout-N.css
- Write after generating each layout (do NOT accumulate)
- Do NOT return content as text
## ✅ Success Criteria
- [ ] Generated exactly {layout_variants × 2} files
- [ ] All HTML includes correct CSS file reference (matching filename pattern)
- [ ] All CSS uses design token values directly (self-contained, no var() references)
- [ ] CSS fully embodies the style's design tokens (colors, typography, spacing, effects)
- [ ] {IF design_attributes: 'HTML structure adapts to design_attributes' ELSE: 'HTML follows layout inspiration'}
- [ ] Layouts are structurally distinct (different grids/regions, not just CSS tweaks)
- [ ] Files written to filesystem (not returned as text)
## 📋 Completion
Report: "{target} × Style-{style_id} ({philosophy_name}): {layout_variants × 2} files created"
"""
REPORT: "⏳ Phase 2: Waiting for {len(target_list) * style_variants} target-style agents to complete..."
REPORT: " Expected total files: {style_variants × layout_variants × len(target_list) × 2}"
```
### Phase 2.5: Verify Agent File Creation
```bash
REPORT: "📝 Phase 2.5: Verifying target-style generation..."
total_expected = style_variants × layout_variants × len(target_list) × 2
total_found = 0
FOR target IN target_list:
FOR style_id IN range(1, style_variants + 1):
agent_files_found = 0
FOR layout_id IN range(1, layout_variants + 1):
html_file = f"{target}-style-{style_id}-layout-{layout_id}.html"
css_file = f"{target}-style-{style_id}-layout-{layout_id}.css"
html_path = f"{base_path}/prototypes/{html_file}"
css_path = f"{base_path}/prototypes/{css_file}"
# Verify files exist
IF exists(html_path) AND exists(css_path):
# Validate content
html_content = Read(html_path)
css_content = Read(css_path)
# Basic validation
VALIDATE: "<!DOCTYPE html>" in html_content, f"Invalid HTML: {html_file}"
VALIDATE: f'href="{css_file}"' in html_content, f"Missing or incorrect CSS reference in: {html_file}"
VALIDATE: len(css_content) > 100, f"CSS file too small (likely incomplete): {css_file}"
html_size = get_file_size(html_path)
css_size = get_file_size(css_path)
agent_files_found += 2
total_found += 2
REPORT: f" ✓ {html_file} ({html_size} KB) + {css_file} ({css_size} KB)"
ELSE:
ERROR: f" ✗ Missing files: {target}-style-{style_id}-layout-{layout_id}.*"
REPORT: f" {target} × style-{style_id}: {agent_files_found}/{layout_variants * 2} files verified"
IF total_found == total_expected:
REPORT: f"✅ Phase 2.5 complete: Verified all {total_expected} files"
ELSE:
ERROR: f"⚠️ Only {total_found}/{total_expected} files found - some agents may have failed"
```
### Phase 3: Generate Preview Files
```bash
REPORT: "🌐 Phase 3: Generating preview files..."
prototypes_dir = f"{base_path}/prototypes"
# Template-based preview generation script
# - Uses: ~/.claude/workflows/_template-compare-matrix.html
# - Auto-detects: S, L, T from file patterns
# - Generates: compare.html, index.html, PREVIEW.md
Bash(~/.claude/scripts/ui-generate-preview-v2.sh "{prototypes_dir}")
# Verify preview files generated
preview_files = [
f"{base_path}/prototypes/compare.html",
f"{base_path}/prototypes/index.html",
f"{base_path}/prototypes/PREVIEW.md"
]
all_present = True
FOR file_path IN preview_files:
IF exists(file_path):
REPORT: f" ✓ Generated: {basename(file_path)}"
ELSE:
WARN: f" ✗ Missing: {basename(file_path)}"
all_present = False
IF all_present:
REPORT: "✅ Phase 3 complete: All preview files generated"
ELSE:
WARN: "⚠️ Some preview files missing - script may need attention"
```
### Phase 4: Completion
```javascript
TodoWrite({todos: [
{content: "Resolve paths and load design systems", status: "completed", activeForm: "Loading design systems"},
{content: `Gather layout inspiration for ${target_list.length} targets`, status: "completed", activeForm: "Gathering inspiration"},
{content: `Launch ${target_list.length}×${style_variants}=${target_list.length * style_variants} target-style agents (each handling ${layout_variants} layouts)`, status: "completed", activeForm: "Running target-style generation"},
{content: `Verify ${style_variants * layout_variants * target_list.length * 2} generated files`, status: "completed", activeForm: "Verifying files"},
{content: "Generate preview files (compare.html, index.html)", status: "completed", activeForm: "Generating previews"}
]});
```
**Completion Message**:
```
✅ Target-Style-Centric UI Generation Complete!
Architecture: Target-Style-Centric Batch Generation
Configuration:
- Style Variants: {style_variants}
- Layout Variants: {layout_variants} (inspiration-based)
- Target Type: {target_type_icon} {target_type}
- Targets: {target_list}
- Total Prototypes: {style_variants * layout_variants * len(target_list)}
Agent Execution:
✅ Target-style agents: T×S = {len(target_list)}×{style_variants} = {len(target_list) * style_variants} agents
✅ Each agent handles: L = {layout_variants} layouts for one component
✅ Component isolation: Tasks completely independent
Design Quality:
✅ Style-Aware Structure: {IF design_space_analysis: 'YES - HTML adapts to design_attributes' ELSE: 'Standard semantic structure'}
✅ Focused generation: Each agent handles single target × single style
✅ Self-Contained CSS: Direct design token usage (no var() dependencies)
Output Files:
- Layout Inspirations: {len(target_list)} simple text files
- HTML Prototypes: {style_variants * layout_variants * len(target_list)} files
- CSS Files: {style_variants * layout_variants * len(target_list)} files
- Preview Files: compare.html, index.html, PREVIEW.md
Generated Structure:
📂 {base_path}/prototypes/
├── _inspirations/
│ └── {target}-layout-ideas.txt ({len(target_list)} inspiration files)
├── {target}-style-{s}-layout-{l}.html ({style_variants * layout_variants * len(target_list)} prototypes)
├── {target}-style-{s}-layout-{l}.css
├── compare.html (interactive S×L×T matrix)
├── index.html (quick navigation)
└── PREVIEW.md (usage instructions)
🌐 Interactive Preview:
1. Matrix View: Open compare.html (recommended)
2. Quick Index: Open index.html
3. Instructions: See PREVIEW.md
{IF design_space_analysis:
🎨 Style-Aware Generation Active:
Each style's prototypes use structure adapted to design_attributes:
- Density affects container nesting and whitespace
- Visual weight affects wrapper layers and border structure
- Same layout × same target × different style = DIFFERENT HTML trees!
}
Next: /workflow:ui-design:update {--session flag if applicable}
Note: When called from /workflow:ui-design:explore-auto, design-update is triggered automatically.
**Dynamic Values**: target_type_icon: "📄" for page, "🧩" for component
```
## Output Structure
```
{base_path}/prototypes/
├── _inspirations/ # Layout inspiration only
│ └── {target}-layout-ideas.txt # Simple inspiration text
├── {target}-style-{s}-layout-{l}.html # Final prototypes (S×L×T)
├── {target}-style-{s}-layout-{l}.css
├── compare.html # Interactive matrix
├── index.html # Navigation page
└── PREVIEW.md # Instructions
{base_path}/style-consolidation/
├── style-1/ (design-tokens.json, style-guide.md)
├── style-2/ (same structure)
└── style-{S}/ (same structure)
```
## Error Handling
### Pre-execution Checks
- **No design systems found**: Error - Run `/workflow:ui-design:consolidate` first
- **Invalid target names**: Extract from synthesis-specification.md or error with validation message
- **Missing design-space-analysis.json**: WARN only - generation continues with basic structure
- **Unsupported target type**: Error if target_type not in ["page", "component"]
### Phase-Specific Errors
- **Agent execution errors (Phase 2)**: Report details, identify which target × style agent failed
- **Invalid design-tokens.json**: Check JSON format and structure
- **Missing files (Phase 2.5)**: Indicates agent failed to write - review agent output logs
- **MCP search errors (Phase 1.5)**: Check network connectivity, retry search
- **Preview generation errors (Phase 3)**: Check script exists, permissions
### Recovery Strategies
- **Partial generation**: If some target-style agents succeed, you still have those prototypes
- **Retry single combination**: Can re-run targeting failed target × style combination
- **Missing design_attributes**: Generation works without them - just less style-aware
- **Permission errors**: Run `chmod +x ~/.claude/scripts/ui-generate-preview-v2.sh`
## Key Features
1. **🚀 Target-Style-Centric Batch Generation**
Each agent handles L layouts for one target × one style with component isolation
2. **🎯 Component Isolation**
Tasks completely independent, preventing cross-component interference
3. **🎨 Style-Aware Structure Adaptation**
HTML DOM adapts based on design_attributes (density, visual_weight, organic_vs_geometric)
4. **⚡ Performance Optimized**
Parallel execution of T×S agents with highly focused scope per agent
5. **💡 Simplified Layout Inspiration**
Simple text-based research replaces complex JSON planning
6. **🔧 Focused Agent Scope**
Each agent generates only L layouts, reducing complexity and improving quality
7. **🎯 Self-Contained CSS Generation**
Agents read design-tokens.json and create independent CSS with direct token values (no var() references)
8. **🌐 Interactive Visualization**
Full-featured compare.html with matrix grid
9. **✅ Production-Ready Output**
Semantic HTML5, ARIA attributes, WCAG 2.2 compliant
## Integration Points
- **Input**: Per-style design-tokens.json; design-space-analysis.json (optional); targets + layout-variants
- **Output**: S×L×T HTML/CSS prototypes with self-contained styling for `/workflow:ui-design:update`
- **Auto Integration**: Triggered by `/workflow:ui-design:explore-auto`
- **Backward Compatibility**: Works without design-space-analysis.json

View File

@@ -2,30 +2,12 @@
name: generate
description: Generate UI prototypes in matrix mode (style × layout combinations) for pages or components
usage: /workflow:ui-design:generate [--targets "<list>"] [--target-type "page|component"] [--base-path <path>] [--session <id>] [--style-variants <count>] [--layout-variants <count>]
argument-hint: "[--targets \"dashboard,auth,navbar,hero\"] [--target-type \"page\"] [--base-path \".workflow/WFS-xxx/design-run-xxx\"] [--style-variants 3] [--layout-variants 3]"
parameters:
- name: --style-variants
type: number
default: 3
description: "Number of style variants to generate prototypes for (1-5). Auto-validates against actual style-* directories. ⚠️ Recommend omitting to use auto-detection."
- name: --layout-variants
type: number
default: auto-detected from layout-strategies.json
description: "Number of layout variants. Default: loaded from consolidation output. Can override for manual testing."
- name: --targets
type: string
description: "Comma-separated list of targets (pages or components) to generate"
- name: --target-type
type: string
default: page
description: "Type of targets: 'page' (full layout) or 'component' (isolated element)"
examples:
- /workflow:ui-design:generate --base-path ".workflow/WFS-auth/design-run-20250109-143022" --targets "dashboard,settings" --target-type "page" --style-variants 3 --layout-variants 3
- /workflow:ui-design:generate --session WFS-auth --targets "home,pricing" --target-type "page" --style-variants 2 --layout-variants 2
- /workflow:ui-design:generate --base-path "./.workflow/.design/run-20250109-150533" # ✅ Recommended: auto-detect variants
- /workflow:ui-design:generate --targets "navbar,hero,card" --target-type "component" --style-variants 3 --layout-variants 2
- /workflow:ui-design:generate --pages "home,dashboard" --style-variants 2 --layout-variants 2 # Legacy syntax
executor: → @ui-design-agent
allowed-tools: TodoWrite(*), Read(*), Write(*), Task(ui-design-agent), Bash(*)
---
@@ -44,7 +26,7 @@ Generate production-ready UI prototypes (HTML/CSS) in `style × layout` matrix m
- **Token-Driven**: All styles reference per-style design-tokens.json; no hardcoded values
- **Production-Ready**: Semantic HTML5, ARIA attributes, responsive design
- **Template-Based**: Decouples HTML structure from CSS styling for optimal performance
- **Adaptive Wrapper**: Full-page structure for pages, minimal wrapper for components
- **Adaptive Wrapper**: All templates use complete HTML5 documents; body content adapts (full page structure for pages, isolated component for components)
## Execution Protocol
@@ -137,120 +119,44 @@ FOR target IN target_list:
Task(ui-design-agent): "
[TARGET_LAYOUT_PLANNING]
Generate a concrete, actionable layout plan for a specific target and WRITE it to the file system.
## Context
TARGET: {target}
TARGET_TYPE: {target_type}
LAYOUT_ID: {layout_id}
TARGET: {target} | TARGET_TYPE: {target_type} | LAYOUT_ID: {layout_id}/{layout_variants}
BASE_PATH: {base_path}
{IF --session: PROJECT_REQUIREMENTS: Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md)}
{IF --session: PROJECT_REQUIREMENTS: .workflow/WFS-{session}/.brainstorming/synthesis-specification.md}
## Task
Research, design, and WRITE a modern, innovative layout plan specifically for '{target}'.
Research {target} {target_type} layout variations → Select approach #{layout_id} → Generate layout plan JSON
## Research Phase (Use MCP Tools)
1. Search for modern {target_type} layout patterns:
mcp__exa__get_code_context_exa(
query=\"modern {target} {target_type} layout design patterns 2024 2025\",
tokensNum=\"dynamic\"
)
2. Search for {target}-specific UI best practices
## Research
mcp__exa__web_search_exa(
query=\"common {target} {target_type} layout patterns variations best practices 2024\",
numResults=5
)
Identify multiple structural patterns → Select DISTINCT approach #{layout_id}
## Layout Planning Rules
## Output
Write(\"{base_path}/prototypes/_templates/{target}-layout-{layout_id}.json\", layout_plan_json)
**For PAGES (target_type='page')**:
- Define macro-layout: main regions (header, sidebar, main, footer)
- Specify grid/flexbox structure for content organization
- Define responsive breakpoints and behavior
- Include navigation and page-level components
**For COMPONENTS (target_type='component')**:
- Define micro-layout: internal element arrangement
- Specify alignment, spacing, and element sizing
- Focus on component-specific structure (no header/footer)
- Optimize for reusability and composition
## File Write Instructions
Generate layout plan JSON and WRITE it using Write() tool:
**Path**: {base_path}/prototypes/_templates/{target}-layout-{layout_id}.json
**Content** - JSON with this EXACT structure:
## JSON Structure
```json
{
\"id\": \"layout-{layout_id}\",
\"target\": \"{target}\",
\"target_type\": \"{target_type}\",
\"name\": \"Descriptive name (2-4 words)\",
\"description\": \"Detailed description (2-3 sentences explaining structure, use cases, and unique aspects)\",
\"structure\": {
// For pages, include:
\"type\": \"sidebar-main\" | \"centered\" | \"asymmetric\" | \"grid-dashboard\",
\"regions\": [\"header\", \"sidebar\", \"main\", \"footer\"],
\"grid\": {
\"columns\": 12,
\"rows\": \"auto\",
\"gap\": \"var(--spacing-6)\"
},
\"sidebar\": {
\"position\": \"left\" | \"right\",
\"width\": \"250px\",
\"fixed\": true,
\"collapsible\": true
},
\"responsive\": {
\"mobile\": {\"columns\": 1, \"sidebar\": \"hidden\"},
\"tablet\": {\"columns\": 6, \"sidebar\": \"overlay\"},
\"desktop\": {\"columns\": 12, \"sidebar\": \"fixed\"}
},
// For components, include:
\"arrangement\": \"flex-column\" | \"flex-row\" | \"grid\",
\"alignment\": \"center\" | \"start\" | \"end\" | \"stretch\",
\"spacing\": \"compact\" | \"normal\" | \"relaxed\",
\"element_order\": [\"icon\", \"title\", \"description\", \"action\"]
"id": "layout-{layout_id}",
"target": "{target}",
"target_type": "{target_type}",
"name": "Descriptive name (2-4 words)",
"description": "2-3 sentences",
"structure": {
// IF page: type, regions, grid, sidebar, responsive
// IF component: arrangement, alignment, spacing, element_order
},
\"semantic_hints\": [
\"dashboard\",
\"data-visualization\",
\"navigation-sidebar\",
\"card-based\"
],
\"accessibility_features\": [
\"skip-navigation\",
\"landmark-regions\",
\"keyboard-navigation\",
\"screen-reader-optimized\"
],
\"research_references\": [
\"URL or description of research source 1\",
\"URL or description of research source 2\"
]
"semantic_hints": [...],
"accessibility_features": [...],
"research_references": [...]
}
```
## Write Operation Instructions
- Use Write() tool with the absolute path provided above
- Create directory if needed: Bash('mkdir -p {base_path}/prototypes/_templates')
- Verify write operation succeeds
## Example Write Operation
```javascript
Write(\"{base_path}/prototypes/_templates/{target}-layout-{layout_id}.json\", JSON.stringify(layout_plan, null, 2))
```
## Completion
Report successful file creation with path confirmation.
## Critical Requirements
- ✅ Layout plan is ONLY for '{target}' - tailor to this specific target's needs
- ✅ Consider {target_type} type (page vs component) when designing structure
- ✅ Research modern patterns using MCP tools before designing
- ✅ Provide concrete, implementable structure (not abstract descriptions)
- ✅ Different layout IDs should explore meaningfully different approaches
- ✅ Use semantic naming and clear documentation
- ✅ Write file directly using Write() tool - do NOT return contents as text
## Requirements
- Research-informed, structurally DIFFERENT from other layout IDs
- Write file directly (not text output)
"
# Wait for all agent tasks to complete
@@ -288,33 +194,63 @@ FOR target IN target_list:
REPORT: f"✅ Phase 1.5 complete: Verified {len(target_list) × layout_variants} target-specific layout files"
```
### Phase 1.6: Token Variable Name Extraction
### Phase 1.6: Convert Design Tokens to CSS
```bash
REPORT: "📋 Extracting design token variable names..."
tokens_json_path = "{base_path}/style-consolidation/style-1/design-tokens.json"
VERIFY: exists(tokens_json_path), "Design tokens not found. Run /workflow:ui-design:consolidate first."
REPORT: "🎨 Converting design tokens to CSS variables..."
design_tokens = Read(tokens_json_path)
# Check for jq dependency
IF NOT command_exists("jq"):
ERROR: "jq is not installed or not in PATH. The conversion script requires jq."
REPORT: "Please install jq: macOS: brew install jq | Linux: apt-get install jq | Windows: https://stedolan.github.io/jq/download/"
EXIT 1
# Extract all available token categories and variable names
token_reference = {
"colors": {"brand": list(keys), "surface": list(keys), "semantic": list(keys), "text": list(keys), "border": list(keys)},
"typography": {"font_family": list(keys), "font_size": list(keys), "font_weight": list(keys), "line_height": list(keys), "letter_spacing": list(keys)},
"spacing": list(keys), "border_radius": list(keys), "shadows": list(keys), "breakpoints": list(keys)
}
# Convert design tokens to CSS for each style variant
FOR style_id IN range(1, style_variants + 1):
tokens_json_path = "{base_path}/style-consolidation/style-${style_id}/design-tokens.json"
tokens_css_path = "{base_path}/style-consolidation/style-${style_id}/tokens.css"
script_path = "~/.claude/scripts/convert_tokens_to_css.sh"
# Generate complete variable name lists for Agent prompt
color_vars = []; FOR category, keys: FOR key: color_vars.append(f"--color-{category}-{key}")
typography_vars = []; FOR category, keys: FOR key: typography_vars.append(f"--{category.replace('_', '-')}-{key}")
spacing_vars = [f"--spacing-{key}" for key in token_reference.spacing]
radius_vars = [f"--border-radius-{key}" for key in token_reference.border_radius]
shadow_vars = [f"--shadow-{key}" for key in token_reference.shadows]
breakpoint_vars = [f"--breakpoint-{key}" for key in token_reference.breakpoints]
# Verify input file exists
VERIFY: exists(tokens_json_path), f"Design tokens not found for style-{style_id}"
all_token_vars = color_vars + typography_vars + spacing_vars + radius_vars + shadow_vars + breakpoint_vars
# Execute conversion: cat input.json | script.sh > output.css
Bash(cat "${tokens_json_path}" | "${script_path}" > "${tokens_css_path}")
REPORT: f"✅ Extracted {len(all_token_vars)} design token variables from design-tokens.json"
# Verify output was generated
IF exit_code == 0 AND exists(tokens_css_path):
file_size = get_file_size(tokens_css_path)
REPORT: f" ✓ Generated tokens.css for style-{style_id} ({file_size} KB)"
ELSE:
ERROR: f"Failed to generate tokens.css for style-{style_id}"
EXIT 1
REPORT: f"✅ Phase 1.6 complete: Converted {style_variants} design token files to CSS"
```
### Phase 1.7: Extract Token Variable Names from CSS
```bash
REPORT: "📋 Extracting actual CSS variable names from tokens.css..."
tokens_css_path = "{base_path}/style-consolidation/style-1/tokens.css"
VERIFY: exists(tokens_css_path), "tokens.css not found. Phase 1.6 may have failed."
tokens_css_content = Read(tokens_css_path)
# Extract all CSS variable names from the generated file
# Pattern: --variable-name: value;
all_token_vars = extract_css_variables(tokens_css_content) # Regex: r'--([a-z0-9-_]+):'
# Categorize variables for better Agent understanding
color_vars = [v for v in all_token_vars if v.startswith('--color-')]
typography_vars = [v for v in all_token_vars if v.startswith(('--font-', '--line-height-', '--letter-spacing-'))]
spacing_vars = [v for v in all_token_vars if v.startswith('--spacing-')]
radius_vars = [v for v in all_token_vars if v.startswith('--border-radius-')]
shadow_vars = [v for v in all_token_vars if v.startswith('--shadow-')]
breakpoint_vars = [v for v in all_token_vars if v.startswith('--breakpoint-')]
REPORT: f"✅ Extracted {len(all_token_vars)} actual CSS variables from tokens.css"
REPORT: f" Colors: {len(color_vars)} | Typography: {len(typography_vars)} | Spacing: {len(spacing_vars)}"
```
### Phase 2: Optimized Matrix UI Generation
@@ -343,188 +279,62 @@ FOR layout_id IN range(1, layout_variants + 1):
Task(ui-design-agent): "
[UI_LAYOUT_TEMPLATE_GENERATION]
🚨 **CRITICAL: TARGET INDEPENDENCE REQUIREMENT** 🚨
You are generating a template for EXACTLY ONE target: '{target}'.
- Do NOT include content from other targets in the workflow
- This template is for '{target}' ONLY - treat it as a standalone UI entity
- Even if '{target}' might coexist with other targets in a final application,
your task is to create an INDEPENDENT, REUSABLE template for '{target}' alone
🚨 TARGET INDEPENDENCE: Generate template for EXACTLY ONE target: '{target}' (standalone, reusable)
Generate a **style-agnostic** layout template for a specific {target_type} and layout strategy.
🎯 **CRITICAL REQUIREMENTS**:
✅ **ADAPTIVE**: Multi-device responsive design (mobile, tablet, desktop)
✅ **STYLE-SWITCHABLE**: Support runtime theme/style switching via CSS variables
✅ **TOKEN-DRIVEN**: 100% CSS variable usage, zero hardcoded values
✅ **INDEPENDENT**: Template for '{target}' only, no other targets included
✅ **RESEARCH-INFORMED**: Use MCP tools to research modern UI patterns as needed
## Context
LAYOUT_ID: {layout_id} | TARGET: {target} | TARGET_TYPE: {target_type}
BASE_PATH: {base_path}
{IF --session: Requirements: .workflow/WFS-{session}/.brainstorming/synthesis-specification.md}
{IF --session: REQUIREMENTS: .workflow/WFS-{session}/.brainstorming/synthesis-specification.md}
**Target Type Details**:
{IF target_type == "page":
- Type: Full-page layout | Wrapper: Complete HTML document (<html>, <head>, <body>)
- Navigation: Include header/navigation | Footer: Include page footer
- Content: Complete page content structure
}
{ELSE IF target_type == "component":
- Type: Isolated UI component | Wrapper: Minimal container for demonstration
- Navigation: Exclude header/footer | Container: Simple wrapper (e.g., <div class=\"component-container\">)
- Content: Focus solely on component design
}
## Layout Plan to Implement
**Path**: {layout_json_path}
**Plan**: {JSON.stringify(layout_plan, null, 2)}
## Task
Generate TWO files that work together as a reusable template.
Generate TWO template files implementing the layout plan:
- HTML: {base_path}/prototypes/_templates/{target}-layout-{layout_id}.html
- CSS: {base_path}/prototypes/_templates/{target}-layout-{layout_id}.css
### File 1: HTML Template (`{target}-layout-{layout_id}.html`)
**Structure Requirements**:
- Semantic HTML5 elements with ARIA attributes
- Complete {target_type} wrapper (full document for pages, minimal for components)
- Zero hardcoded styles, colors, or spacing
- Responsive structure ready for mobile/tablet/desktop
**⚠️ CRITICAL: CSS Placeholder Links**
You MUST include these EXACT placeholder links in the `<head>` section:
```html
<link rel=\"stylesheet\" href=\"{{STRUCTURAL_CSS}}\">
<link rel=\"stylesheet\" href=\"{{TOKEN_CSS}}\">
```
**Placeholder Rules**:
1. Use EXACTLY `{{STRUCTURAL_CSS}}` and `{{TOKEN_CSS}}` with double curly braces
2. Place in `<head>` AFTER `<meta>` tags, BEFORE `</head>` closing tag
3. DO NOT substitute with actual paths - the script handles this
4. DO NOT add any other CSS `<link>` tags
5. These enable runtime style switching for all variants
**Complete HTML Template Examples**:
{IF target_type == \"page\":
```html
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"UTF-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
<title>{target} - Layout {layout_id}</title>
## HTML Requirements
- Complete HTML5 document (<!DOCTYPE>, <html>, <head>, <body>)
- Semantic elements + ARIA attributes
- Body content:
* IF page → Full structure (header, nav, main, footer)
* IF component → Isolated element in presentation wrapper
- ⚠️ CRITICAL CSS placeholders in <head>:
<link rel=\"stylesheet\" href=\"{{STRUCTURAL_CSS}}\">
<link rel=\"stylesheet\" href=\"{{TOKEN_CSS}}\">
</head>
<body>
<header><nav aria-label=\"Main navigation\"><!-- Nav content --></nav></header>
<main><!-- Page content --></main>
<footer><!-- Footer content --></footer>
</body>
</html>
```
}
{ELSE IF target_type == \"component\":
```html
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"UTF-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
<title>{target} Component - Layout {layout_id}</title>
<link rel=\"stylesheet\" href=\"{{STRUCTURAL_CSS}}\">
<link rel=\"stylesheet\" href=\"{{TOKEN_CSS}}\">
</head>
<body>
<div class=\"component-container\">
<!-- Component content only -->
</div>
</body>
</html>
```
}
## CSS Requirements - Token Reference
### File 2: CSS Template (`{target}-layout-{layout_id}.css`)
- 🎨 **TOKEN-DRIVEN STYLING**: ALL values use `var()` for dynamic theme switching
- 🔄 **RUNTIME SWITCHABLE**: `background-color: var(--color-surface-background);`
- 🚫 **ZERO LITERALS**: NO hardcoded values (#4F46E5, 16px, Arial)
- 📐 **SEMANTIC NAMING**: BEM or descriptive class naming
- 📱 **MOBILE-FIRST**: Responsive design using token-based breakpoints
- {IF target_type == "component": "Focus styles on component only, minimal global styles"}
**1. Read tokens.css**
Read(\"{base_path}/style-consolidation/style-1/tokens.css\")
Extract all CSS variable names (pattern: lines with \" --\" in \":root {}\")
## Layout Plan (Target-Specific)
Implement the following pre-defined layout plan for this target:
**2. Available Tokens**
- Colors: {', '.join(color_vars[:5])}... ({len(color_vars)} total)
- Typography: {', '.join(typography_vars[:5])}... ({len(typography_vars)} total)
- Spacing: {', '.join(spacing_vars[:5])}... ({len(spacing_vars)} total)
- Radius: {', '.join(radius_vars[:3])}... ({len(radius_vars)} total)
- Shadows: {', '.join(shadow_vars)}
**Layout JSON Path**: {layout_json_path}
**Layout Plan**:
```json
{JSON.stringify(layout_plan, null, 2)}
```
**3. Variable Usage Rules**
- ✅ Use ONLY variables from tokens.css (exact names)
- ✅ Format: var(--exact-name-from-file)
- ❌ NO invented/guessed variable names
- ❌ NO hardcoded values (colors, fonts, spacing)
**Critical**: Your job is to IMPLEMENT this exact layout plan, not to redesign it.
- Follow the structure defined in the 'structure' field
- Use semantic hints for appropriate HTML elements
- Respect the target_type (page vs component) wrapper requirements
- Apply the specified responsive behavior
**4. Optional Extension**
If core tokens insufficient → Create `{target}-layout-{layout_id}-tokens.css` with `--layout-*` prefix
Examples: `--layout-spacing-navbar-height`, `--layout-size-sidebar-width`
## Token Usage Requirements (STRICT - USE EXACT NAMES)
**CSS Scope**: Structural layout only (Flexbox, Grid, positioning)
**Responsive**: Mobile-first approach
**CRITICAL**: You MUST use ONLY the variable names listed below.
DO NOT invent variable names like --color-background-base, --radius-md, --transition-base, etc.
**Available Variables** ({len(all_token_vars)} total):
- Color variables ({len(color_vars)}): --color-brand-primary, --color-surface-background, --color-text-primary, etc.
- Typography variables ({len(typography_vars)}): --font-family-heading, --font-size-base, --font-weight-bold, etc.
- Spacing variables ({len(spacing_vars)}): --spacing-0, --spacing-1, ..., --spacing-24
- Border radius ({len(radius_vars)}): --border-radius-none, --border-radius-sm, ..., --border-radius-full
- Shadows ({len(shadow_vars)}): --shadow-sm, --shadow-md, --shadow-lg, --shadow-xl
- Breakpoints ({len(breakpoint_vars)}): --breakpoint-sm, --breakpoint-md, --breakpoint-lg, etc.
**STRICT RULES**:
1. Use ONLY the variables listed above - NO custom variable names
2. If you need a value not in the list, use the closest semantic match
3. For missing tokens (like transitions), use literal CSS values: `transition: all 0.2s ease;`
4. NO hardcoded colors, fonts, or spacing (e.g., #4F46E5, 16px, Arial)
5. All `var()` references must match exact variable names above
## File Write Instructions
Generate TWO template files and WRITE them using Write() tool:
### File 1: HTML Template
**Path**: {base_path}/prototypes/_templates/{target}-layout-{layout_id}.html
**Content**: Reusable HTML structure with CSS placeholders
### File 2: CSS Template
**Path**: {base_path}/prototypes/_templates/{target}-layout-{layout_id}.css
**Content**: Structural CSS using var() for all values
## Write Operation Instructions
- Use Write() tool for both files with absolute paths provided above
- Create directory if needed: Bash('mkdir -p {base_path}/prototypes/_templates')
- Verify each write operation succeeds
## Example Write Operations
```javascript
## Write Operations
Write(\"{base_path}/prototypes/_templates/{target}-layout-{layout_id}.html\", html_content)
Write(\"{base_path}/prototypes/_templates/{target}-layout-{layout_id}.css\", css_content)
```
## Completion
Report successful file creation for both HTML and CSS templates with path confirmation.
🎯 **CRITICAL QUALITY GATES**:
✅ **ADAPTIVE**: Works on mobile (375px), tablet (768px), desktop (1024px+)
✅ **STYLE-SWITCHABLE**: Change {{TOKEN_CSS}} link → instant theme switching
✅ **TOKEN-ONLY**: 100% var() usage, inspectable with \"Search for: #|px|rem\" → 0 matches in values
✅ **REUSABLE**: Same HTML/CSS structure works for ALL style variants
✅ **FILE-WRITTEN**: Files written directly to file system, not returned as text
**Wrapper Strategy**:
{IF target_type == "page": Use complete HTML document structure with navigation and footer.}
{ELSE: Use minimal wrapper with component container only.}
DO NOT return file contents as text - write them directly using Write() tool.
Report completion with file paths. Write files directly (not text output).
"
REPORT: "⏳ Phase 2a: Waiting for agents to complete template generation..."
@@ -556,7 +366,7 @@ FOR layout_id IN range(1, layout_variants + 1):
# Basic validation checks
VALIDATE: len(html_content) > 100, f"HTML template too short: {html_label}"
VALIDATE: len(css_content) > 50, f"CSS template too short: {css_label}"
VALIDATE: "<!DOCTYPE html>" in html_content OR "<div" in html_content, f"Invalid HTML structure: {html_label}"
VALIDATE: "<!DOCTYPE html>" in html_content, f"Invalid HTML structure: {html_label}"
VALIDATE: "var(--" in css_content, f"Missing CSS variables: {css_label}"
html_size = get_file_size(html_path)
@@ -574,35 +384,16 @@ REPORT: "✅ Phase 2a.5 complete: Verified {layout_variants * len(target_list) *
```bash
REPORT: "🚀 Phase 2b: Instantiating prototypes from templates..."
# Step 1: Convert design tokens to CSS for each style
REPORT: " Converting design tokens to CSS variables..."
# Check for jq dependency
IF NOT command_exists("jq"):
ERROR: "jq is not installed or not in PATH. The conversion script requires jq."
REPORT: "Please install jq: macOS: brew install jq | Linux: apt-get install jq | Windows: https://stedolan.github.io/jq/download/"
EXIT 1
# Convert design tokens to CSS for each style variant
# Verify tokens.css files exist (should be created in Phase 1.6)
FOR style_id IN range(1, style_variants + 1):
tokens_json_path = "{base_path}/style-consolidation/style-${style_id}/design-tokens.json"
tokens_css_path = "{base_path}/style-consolidation/style-${style_id}/tokens.css"
script_path = "~/.claude/scripts/convert_tokens_to_css.sh"
VERIFY: exists(tokens_css_path), f"tokens.css missing for style-{style_id}. Phase 1.6 may have failed."
# Verify input file exists
IF NOT exists(tokens_json_path): REPORT: " ✗ ERROR: Input file not found"; CONTINUE
REPORT: " Verified {style_variants} tokens.css files exist"
# Execute conversion: cat input.json | script.sh > output.css
Bash(cat "${tokens_json_path}" | "${script_path}" > "${tokens_css_path}")
# Verify output was generated
IF exit_code == 0 AND exists(tokens_css_path):
REPORT: " ✓ Generated tokens.css for style-${style_id}"
ELSE:
REPORT: " ✗ ERROR: Failed to generate tokens.css for style-${style_id}"
# Step 2: Use ui-instantiate-prototypes.sh script for instantiation
prototypes_dir = "{base_path}/prototypes"; targets_csv = ','.join(target_list)
# Use ui-instantiate-prototypes.sh script for instantiation
prototypes_dir = "{base_path}/prototypes"
targets_csv = ','.join(target_list)
session_id = --session provided ? {session_id} : "standalone"
# Execute instantiation script with target type
@@ -656,32 +447,22 @@ FOR style_id IN range(1, style_variants + 1):
Task(@ui-design-agent): "
[CROSS_PAGE_CONSISTENCY_VALIDATION]
Validate design consistency across multiple {target_type}s for Style-{style_id} Layout-{layout_id}
🎯 **VALIDATION FOCUS**:
✅ **ADAPTIVE CONSISTENCY**: Same responsive behavior across all pages
✅ **STYLE-SWITCHING**: Verify token references enable uniform theme switching
✅ **CROSS-PAGE HARMONY**: Shared components use identical CSS variables
## Context
STYLE_ID: {style_id} | LAYOUT_ID: {layout_id} | TARGETS: {target_list} | TARGET_TYPE: {target_type}
STYLE: {style_id} | LAYOUT: {layout_id} | TARGETS: {target_list} | TYPE: {target_type}
BASE_PATH: {base_path}
## Input Files
FOR each target: {base_path}/prototypes/{target}-style-{style_id}-layout-{layout_id}.html/css
## Input
{base_path}/prototypes/{target}-style-{style_id}-layout-{layout_id}.html/css (all targets)
## Validation Tasks
1. **Shared Component Consistency**: Check header/nav/footer structure matches
2. **Token Usage Consistency**: Verify same design-tokens file, no hardcoded values
3. **Accessibility Consistency**: ARIA attributes, heading hierarchy, landmark roles
4. **Layout Strategy Adherence**: Layout-{layout_id} strategy applied consistently
## Validate
1. Shared components (header/nav/footer)
2. Token usage (no hardcoded values)
3. Accessibility (ARIA, headings, landmarks)
4. Layout strategy consistency
## Output
Generate consistency report markdown file at:
{base_path}/prototypes/consistency-report-s{style_id}-l{layout_id}.md
Write({base_path}/prototypes/consistency-report-s{style_id}-l{layout_id}.md, validation_report)
Include validation results, issues found, and recommendations.
Focus on truly shared elements. Page-specific content variations are acceptable.
Focus on shared elements. Page-specific variations acceptable.
"
# Aggregate consistency reports
@@ -704,9 +485,9 @@ Run `/workflow:ui-design:update` once all issues are resolved.
TodoWrite({todos: [
{content: "Resolve paths and load design systems", status: "completed", activeForm: "Loading design systems"},
{content: `Plan ${target_list.length}×${layout_variants} target-specific layouts`, status: "completed", activeForm: "Planning layouts"},
{content: "Extract design token variable names", status: "completed", activeForm: "Extracting token variables"},
{content: `Generate ${layout_variants}×${target_list.length} layout templates using target-specific plans`, status: "completed", activeForm: "Generating templates"},
{content: "Convert design tokens to CSS variables", status: "completed", activeForm: "Converting tokens"},
{content: `Convert ${style_variants} design token files to CSS`, status: "completed", activeForm: "Converting tokens to CSS"},
{content: "Extract CSS variable names from tokens.css", status: "completed", activeForm: "Extracting variable names"},
{content: `Generate ${layout_variants}×${target_list.length} layout templates (agent reads tokens.css)`, status: "completed", activeForm: "Generating templates"},
{content: `Instantiate ${style_variants}×${layout_variants}×${target_list.length} prototypes using script`, status: "completed", activeForm: "Running script"},
{content: "Verify preview files generation", status: "completed", activeForm: "Verifying files"}
]});
@@ -748,7 +529,7 @@ Generated Structure:
2. Quick Index: Open index.html
3. Instructions: See PREVIEW.md
{IF target_type == "component": Note: Components are rendered with minimal wrapper for isolated comparison.}
{IF target_type == "component": Note: Components use complete HTML5 documents with isolated body content for better comparison and styling.}
Next: /workflow:ui-design:update {--session flag if applicable}
@@ -812,7 +593,7 @@ After generation, ensure:
- [ ] File naming follows `{target}-style-{s}-layout-{l}` convention
- [ ] compare.html loads correctly with all prototypes
- [ ] Template files are reusable and style-agnostic
- [ ] Appropriate wrapper used (full-page for pages, minimal for components)
- [ ] All templates use complete HTML5 documents with appropriate body content (full structure for pages, isolated component for components)
## Key Features

View File

@@ -2,7 +2,6 @@
name: imitate-auto
description: Imitation-focused UI design workflow - Rapidly replicate a single design style from URL or images (skip exploration, direct to implementation)
usage: /workflow:ui-design:imitate-auto [--url "<url>"] [--images "<glob>"] [--prompt "<desc>"] [--targets "<list>"] [--target-type "page|component"] [--session <id>]
argument-hint: "[--url \"https://example.com\"] [--images \"refs/*.png\"] [--prompt \"Imitate dark mode style\"] [--targets \"dashboard,settings\"] [--target-type \"page\"]"
examples:
- /workflow:ui-design:imitate-auto --url "https://linear.app" --targets "home,features,pricing"
- /workflow:ui-design:imitate-auto --images "refs/design.png" --prompt "Imitate this minimalist design for dashboard and settings"
@@ -25,12 +24,22 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
- **Reference-Driven**: Requires URL or images as primary input
- **Auto-Screenshot**: Supports Playwright/Chrome with manual upload fallback
**Streamlined Flow**: Phase 0 (init) → 0.5 (screenshot) → 1 (extraction) → 2 (token adapt) → 3 (generate) → 4 (integrate)
**Streamlined Flow**: Phase 0 (init) → 0.5 (screenshot) → 0.75 (URL analysis if needed) → 1 (extraction) → 2 (token adapt) → 3 (generate) → 4 (integrate)
**Performance**: ~2-3× faster than explore-auto for single-style scenarios
**Ideal For**: MVP development, high-fidelity prototyping, design replication, studying successful patterns
## Key Features
- **Fast-Track Imitation**: ~2-3× faster than explore-auto by bypassing consolidation phase
- **Reference-Driven**: Requires URL or images as primary design source for accurate replication
- **Auto-Screenshot Capability**: Intelligent fallback (Playwright → Chrome → Manual upload) for URL-based workflows
- **Single-Style Focus**: Always generates 1 style × 1 layout × N targets for streamlined execution
- **Consolidation Bypass**: Direct design token extraction saves 30-60s per workflow
- **Interactive Confirmation**: User validates inferred targets before execution to prevent mistakes
- **Flexible Target Types**: Supports both full-page layouts and isolated UI components
## Core Rules
1. **Start Immediately**: TodoWrite initialization → Phase 0 execution
@@ -41,13 +50,45 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
## Parameter Requirements
**Required** (at least one): `--url "<url>"` OR `--images "<glob>"`
**Required Parameters** (at least one must be provided):
- `--url "<url>"`: Reference website URL for style imitation (supports auto-screenshot)
- `--images "<glob>"`: Reference image paths (e.g., `refs/*.png`, `design-refs/*.jpg`)
**Optional**: `--targets "<list>"`, `--target-type "page|component"`, `--session <id>`, `--prompt "<desc>"`
**Optional Parameters** (all have smart defaults):
- `--targets "<list>"`: Comma-separated targets (pages/components) to generate
- Examples: `"home,dashboard"`, `"navbar,hero,card"`
- If omitted: inferred from `--prompt` or defaults to `["home"]`
- `--target-type "page|component"`: Explicitly set target type
- `page`: Full-page layouts with complete structure
- `component`: Isolated UI elements with minimal wrapper
- Default: intelligent detection based on target names
- `--session <id>`: Workflow session ID (e.g., `WFS-ecommerce`)
- If provided: integrates with session brainstorming artifacts
- If omitted: runs in standalone mode
- `--prompt "<description>"`: Design guidance and target hints
- Used for target inference and style extraction refinement
- Examples: `"Imitate dark mode for dashboard"`, `"Focus on minimalist design"`
**Legacy**: `--pages "<list>"` (alias for `--targets` with type=page)
**Legacy Parameters** (maintained for backward compatibility):
- `--pages "<list>"`: Alias for `--targets` with `--target-type page`
**Not Supported**: `--style-variants`, `--layout-variants`, `--batch-plan`
**Not Supported** (use `/workflow:ui-design:explore-auto` instead):
- `--style-variants`, `--layout-variants`, `--batch-plan`
**Input Rules**:
- Must provide at least one: `--url` OR `--images`
- Multiple parameters can be combined for guided imitation
- If `--targets` not provided, intelligently inferred from prompt or defaults to `["home"]`
- URL and images can be used together (screenshot + additional references)
**Supported Target Types**:
- **Pages** (full layouts): home, dashboard, settings, profile, login, pricing, etc.
- **Components** (UI elements):
- Navigation: navbar, header, menu, sidebar, tabs
- Content: hero, card, list, table, gallery
- Input: form, search, filter, button
- Feedback: modal, alert, toast, badge
- Other: footer, dropdown, avatar, pagination
## 5-Phase Execution
@@ -90,12 +131,45 @@ IF NOT validated_targets: validated_targets = ["home"]; target_type = "page"
type_emoji = "📄" IF target_type == "page" ELSE "🧩"
type_label = "pages" IF target_type == "page" ELSE "components"
REPORT: "📋 Imitate mode: {len(validated_targets)} {type_label} with single style"
# Interactive confirmation
DISPLAY_CONFIRMATION(target_type, target_source, validated_targets):
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
"⚡ IMITATE MODE CONFIRMATION"
"Type: {target_type} | Source: {target_source}"
"Targets ({count}): {', '.join(validated_targets)}"
"Reference: {url_value OR images_pattern}"
"Options: 'continue/yes' | 'targets: a,b' | 'skip: x' | 'add: y' | 'type: page|component'"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
user_input = WAIT_FOR_USER_INPUT()
# Process user modifications
MATCH user_input:
"continue|yes|ok" → proceed
"targets: ..."validated_targets = parse_new_list()
"skip: ..."validated_targets = remove_items()
"add: ..."validated_targets = add_items()
"type: ..."target_type = extract_type()
default → proceed with current list
REPORT: "✅ Confirmed: {len(validated_targets)} {type_label} with single style"
REPORT: " {type_emoji} Targets: {', '.join(validated_targets)} | Type: {target_type} | Reference: {url_value OR images_pattern}"
STORE: run_id, base_path, inferred_target_list = validated_targets, target_type
```
**Helper Function: detect_target_type()**
```bash
detect_target_type(target_list):
page_keywords = ["home", "dashboard", "settings", "profile", "login", "signup", "auth", "pricing", "about", "contact", ...]
component_keywords = ["navbar", "header", "footer", "hero", "card", "button", "form", "modal", "alert", "dropdown", ...]
page_matches = count_matches(target_list, page_keywords + ["page", "screen", "view"])
component_matches = count_matches(target_list, component_keywords + ["component", "widget", "element"])
RETURN "component" IF component_matches > page_matches ELSE "page"
```
### Phase 0.5: URL Screenshot Capture (Auto-Fallback)
**Condition**: Only if `--url` provided
@@ -143,6 +217,26 @@ ELSE:
REPORT: " Using provided images (--images parameter)"
```
### Phase 0.75: URL Content Analysis (Fallback Mode)
**Condition**: Only if `screenshot_mode == "url_only"`
```bash
url_analysis_content = ""
IF screenshot_mode == "url_only":
REPORT: "🔍 Analyzing URL content (no screenshot available)"
# Fetch URL design patterns using MCP web search
url_analysis_content = mcp__exa__web_search_exa(
query="site:{url_value} design style color scheme layout",
numResults=3
)
STORE: url_analysis_data = url_analysis_content
REPORT: "✅ URL content analysis complete"
```
### Phase 1: Single Style Extraction
```bash
@@ -155,15 +249,16 @@ images_flag = screenshot_mode == "with_screenshots" ? "--images \"{base_path}/sc
url_flag = screenshot_mode == "url_only" ? "--url \"{url_value}\"" : ""
# Construct optimized extraction prompt
enhanced_prompt = "Extract a single, high-fidelity design system that accurately imitates the visual style from {source_desc}. {prompt_text}"
# Construct optimized extraction prompt with URL analysis data
url_context = screenshot_mode == "url_only" ? "URL analysis data: {url_analysis_data}" : ""
enhanced_prompt = "Extract a single, high-fidelity design system that accurately imitates the visual style from {source_desc}. {url_context} {prompt_text}"
# Force single variant
command = "/workflow:ui-design:extract --base-path \"{base_path}\" {url_flag} {images_flag} --prompt \"{enhanced_prompt}\" --variants 1"
# Force single variant with imitate mode
command = "/workflow:ui-design:extract --base-path \"{base_path}\" {url_flag} {images_flag} --prompt \"{enhanced_prompt}\" --mode imitate"
REPORT: "🚀 Phase 1: Style Extraction | Source: {source_desc} | Mode: Single style (imitation-optimized)"
REPORT: "🚀 Phase 1: Style Extraction | Source: {source_desc} | Mode: imitate (high-fidelity)"
SlashCommand(command)
SlashCommand(command) # → Phase 2
```
### Phase 2: Fast Token Adaptation (Bypass Consolidate)
@@ -171,6 +266,8 @@ SlashCommand(command)
```bash
REPORT: "🚀 Phase 2: Fast token adaptation (bypassing consolidate)"
# Note: Orchestrator directly reads and transforms files here (not delegating to agent)
# This is a performance optimization to bypass the full consolidate phase
style_cards = Read({base_path}/style-extraction/style-cards.json)
style_card = style_cards.style_cards[0]
@@ -178,7 +275,7 @@ design_tokens = style_card.proposed_tokens
philosophy = style_card.design_philosophy
style_name = style_card.name
# Write design-tokens.json directly
# Write design-tokens.json directly (orchestrator-level file transformation)
Write({base_path}/style-consolidation/style-1/design-tokens.json, JSON.stringify(design_tokens, null, 2))
# Create minimal style-guide.md
@@ -217,18 +314,19 @@ command = "/workflow:ui-design:generate --base-path \"{base_path}\" --targets \"
REPORT: "🚀 Phase 3: Generating {len(inferred_target_list)} {type_label}"
REPORT: " {type_emoji} Targets: {targets_string} | Mode: 1×1 (imitation-optimized)"
SlashCommand(command)
SlashCommand(command) # → Phase 4
# Result: Prototypes: {target}-style-1-layout-1.html, Total: len(inferred_target_list), Type: {target_type}
# Output: Prototypes: {target}-style-1-layout-1.html, Total: len(inferred_target_list), Type: {target_type}
```
### Phase 4: Design System Integration
```bash
IF --session:
SlashCommand("/workflow:ui-design:update --session {session_id}")
SlashCommand("/workflow:ui-design:update --session {session_id}") # → Complete
ELSE:
REPORT: " Standalone mode: Skipping integration | Prototypes at: {base_path}/prototypes/"
# → Complete (standalone)
```
## TodoWrite Pattern
@@ -238,6 +336,7 @@ ELSE:
TodoWrite({todos: [
{"content": "Initialize run directory and infer targets", "status": "in_progress", "activeForm": "Initializing"},
{"content": "Capture screenshots from URL (if provided)", "status": "pending", "activeForm": "Capturing screenshots"},
{"content": "Analyze URL content (fallback mode)", "status": "pending", "activeForm": "Analyzing URL content"},
{"content": "Extract single design style from reference", "status": "pending", "activeForm": "Extracting style"},
{"content": "Adapt tokens (bypass consolidate)", "status": "pending", "activeForm": "Adapting tokens"},
{"content": "Generate single-style prototypes", "status": "pending", "activeForm": "Generating prototypes"},
@@ -298,10 +397,11 @@ TodoWrite({todos: [
/workflow:ui-design:imitate-auto --url "https://stripe.com/pricing" --targets "pricing"
# 0.5: Playwright failed → Chrome failed → User prompted → types 'ready' → ✅ continues OR 'skip' → ⚠️ URL only
# Continues: 1 → 2 → 3 → 4
# If skip: 0.75 (MCP URL analysis) → 1 → 2 → 3 → 4
# If ready: 1 → 2 → 3 → 4
```
## Final Completion Message
## Completion Output
```
✅ UI Design Imitation Complete!
@@ -310,7 +410,8 @@ Mode: Single Style Replication | Run ID: {run_id} | Session: {session_id or "sta
Phase 0 - Initialization: {target_count} {target_type}(s) prepared
Phase 0.5 - Screenshot Capture: {screenshot_status}
{IF success: ✅ Captured via {method} | ELSE: ⚠️ URL analysis only}
{IF success: ✅ Captured via {method} | ELSE: ⚠️ URL analysis fallback activated}
Phase 0.75 - URL Content Analysis: {IF url_only: ✅ Design patterns analyzed via MCP | ELSE: ⏭️ Skipped (screenshots available)}
Phase 1 - Style Extraction: Single style extracted
Phase 2 - Token Adaptation: Bypassed consolidate (⚡ {time_saved}s saved)
Phase 3 - Prototype Generation: {target_count} {target_type} prototypes created

View File

@@ -2,7 +2,6 @@
name: update
description: Update brainstorming artifacts with finalized design system references
usage: /workflow:ui-design:update --session <session_id> [--selected-prototypes "<list>"]
argument-hint: "--session WFS-session-id [--selected-prototypes \"dashboard-variant-1,auth-variant-2\"]"
examples:
- /workflow:ui-design:update --session WFS-auth
- /workflow:ui-design:update --session WFS-dashboard --selected-prototypes "dashboard-variant-1"

View File

@@ -0,0 +1,391 @@
#!/bin/bash
#
# UI Generate Preview v2.0 - Template-Based Preview Generation
# Purpose: Generate compare.html and index.html using template substitution
# Template: ~/.claude/workflows/_template-compare-matrix.html
#
# Usage: ui-generate-preview-v2.sh <prototypes_dir> [--template <path>]
#
set -e
# Color output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Default template path
TEMPLATE_PATH="$HOME/.claude/workflows/_template-compare-matrix.html"
# Parse arguments
prototypes_dir="${1:-.}"
shift || true
while [[ $# -gt 0 ]]; do
case $1 in
--template)
TEMPLATE_PATH="$2"
shift 2
;;
*)
echo -e "${RED}Unknown option: $1${NC}"
exit 1
;;
esac
done
if [[ ! -d "$prototypes_dir" ]]; then
echo -e "${RED}Error: Directory not found: $prototypes_dir${NC}"
exit 1
fi
cd "$prototypes_dir" || exit 1
echo -e "${GREEN}📊 Auto-detecting matrix dimensions...${NC}"
# Auto-detect styles, layouts, targets from file patterns
# Pattern: {target}-style-{s}-layout-{l}.html
styles=$(find . -maxdepth 1 -name "*-style-*-layout-*.html" | \
sed 's/.*-style-\([0-9]\+\)-.*/\1/' | sort -un)
layouts=$(find . -maxdepth 1 -name "*-style-*-layout-*.html" | \
sed 's/.*-layout-\([0-9]\+\)\.html/\1/' | sort -un)
targets=$(find . -maxdepth 1 -name "*-style-*-layout-*.html" | \
sed 's/\.\///; s/-style-.*//' | sort -u)
S=$(echo "$styles" | wc -l)
L=$(echo "$layouts" | wc -l)
T=$(echo "$targets" | wc -l)
echo -e " Detected: ${GREEN}${S}${NC} styles × ${GREEN}${L}${NC} layouts × ${GREEN}${T}${NC} targets"
if [[ $S -eq 0 ]] || [[ $L -eq 0 ]] || [[ $T -eq 0 ]]; then
echo -e "${RED}Error: No prototype files found matching pattern {target}-style-{s}-layout-{l}.html${NC}"
exit 1
fi
# ============================================================================
# Generate compare.html from template
# ============================================================================
echo -e "${YELLOW}🎨 Generating compare.html from template...${NC}"
if [[ ! -f "$TEMPLATE_PATH" ]]; then
echo -e "${RED}Error: Template not found: $TEMPLATE_PATH${NC}"
exit 1
fi
# Build pages/targets JSON array
PAGES_JSON="["
first=true
for target in $targets; do
if [[ "$first" == true ]]; then
first=false
else
PAGES_JSON+=", "
fi
PAGES_JSON+="\"$target\""
done
PAGES_JSON+="]"
# Generate metadata
RUN_ID="run-$(date +%Y%m%d-%H%M%S)"
SESSION_ID="standalone"
TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u +"%Y-%m-%d")
# Replace placeholders in template
cat "$TEMPLATE_PATH" | \
sed "s|{{run_id}}|${RUN_ID}|g" | \
sed "s|{{session_id}}|${SESSION_ID}|g" | \
sed "s|{{timestamp}}|${TIMESTAMP}|g" | \
sed "s|{{style_variants}}|${S}|g" | \
sed "s|{{layout_variants}}|${L}|g" | \
sed "s|{{pages_json}}|${PAGES_JSON}|g" \
> compare.html
echo -e "${GREEN} ✓ Generated compare.html from template${NC}"
# ============================================================================
# Generate index.html
# ============================================================================
echo -e "${YELLOW}📋 Generating index.html...${NC}"
cat > index.html << 'EOF'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UI Prototypes Index</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 40px 20px;
background: #f5f5f5;
}
h1 { margin-bottom: 10px; color: #333; }
.subtitle { color: #666; margin-bottom: 30px; }
.cta {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
border-radius: 8px;
margin-bottom: 30px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.cta h2 { margin-bottom: 10px; }
.cta a {
display: inline-block;
background: white;
color: #667eea;
padding: 10px 20px;
border-radius: 6px;
text-decoration: none;
font-weight: 600;
margin-top: 10px;
}
.cta a:hover { background: #f8f9fa; }
.style-section {
background: white;
padding: 20px;
border-radius: 8px;
margin-bottom: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.style-section h2 {
color: #495057;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 2px solid #e9ecef;
}
.target-group {
margin-bottom: 20px;
}
.target-group h3 {
color: #6c757d;
font-size: 16px;
margin-bottom: 10px;
}
.link-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 10px;
}
.prototype-link {
padding: 12px 16px;
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 6px;
text-decoration: none;
color: #495057;
display: flex;
justify-content: space-between;
align-items: center;
transition: all 0.2s;
}
.prototype-link:hover {
background: #e9ecef;
border-color: #667eea;
transform: translateX(2px);
}
.prototype-link .label { font-weight: 500; }
.prototype-link .icon { color: #667eea; }
</style>
</head>
<body>
<h1>🎨 UI Prototypes Index</h1>
<p class="subtitle">Generated __S__×__L__×__T__ = __TOTAL__ prototypes</p>
<div class="cta">
<h2>📊 Interactive Comparison</h2>
<p>View all styles and layouts side-by-side in an interactive matrix</p>
<a href="compare.html">Open Matrix View →</a>
</div>
<h2>📂 All Prototypes</h2>
__CONTENT__
</body>
</html>
EOF
# Build content HTML
CONTENT=""
for style in $styles; do
CONTENT+="<div class='style-section'>"$'\n'
CONTENT+="<h2>Style ${style}</h2>"$'\n'
for target in $targets; do
target_capitalized="$(echo ${target:0:1} | tr '[:lower:]' '[:upper:]')${target:1}"
CONTENT+="<div class='target-group'>"$'\n'
CONTENT+="<h3>${target_capitalized}</h3>"$'\n'
CONTENT+="<div class='link-grid'>"$'\n'
for layout in $layouts; do
html_file="${target}-style-${style}-layout-${layout}.html"
if [[ -f "$html_file" ]]; then
CONTENT+="<a href='${html_file}' class='prototype-link' target='_blank'>"$'\n'
CONTENT+="<span class='label'>Layout ${layout}</span>"$'\n'
CONTENT+="<span class='icon'>↗</span>"$'\n'
CONTENT+="</a>"$'\n'
fi
done
CONTENT+="</div></div>"$'\n'
done
CONTENT+="</div>"$'\n'
done
# Calculate total
TOTAL_PROTOTYPES=$((S * L * T))
# Replace placeholders (using a temp file for complex replacement)
{
echo "$CONTENT" > /tmp/content_tmp.txt
sed "s|__S__|${S}|g" index.html | \
sed "s|__L__|${L}|g" | \
sed "s|__T__|${T}|g" | \
sed "s|__TOTAL__|${TOTAL_PROTOTYPES}|g" | \
sed -e "/__CONTENT__/r /tmp/content_tmp.txt" -e "/__CONTENT__/d" > /tmp/index_tmp.html
mv /tmp/index_tmp.html index.html
rm -f /tmp/content_tmp.txt
}
echo -e "${GREEN} ✓ Generated index.html${NC}"
# ============================================================================
# Generate PREVIEW.md
# ============================================================================
echo -e "${YELLOW}📝 Generating PREVIEW.md...${NC}"
cat > PREVIEW.md << EOF
# UI Prototypes Preview Guide
Generated: $(date +"%Y-%m-%d %H:%M:%S")
## 📊 Matrix Dimensions
- **Styles**: ${S}
- **Layouts**: ${L}
- **Targets**: ${T}
- **Total Prototypes**: $((S*L*T))
## 🌐 How to View
### Option 1: Interactive Matrix (Recommended)
Open \`compare.html\` in your browser to see all prototypes in an interactive matrix view.
**Features**:
- Side-by-side comparison of all styles and layouts
- Switch between targets using the dropdown
- Adjust grid columns for better viewing
- Direct links to full-page views
- Selection system with export to JSON
- Fullscreen mode for detailed inspection
### Option 2: Simple Index
Open \`index.html\` for a simple list of all prototypes with direct links.
### Option 3: Direct File Access
Each prototype can be opened directly:
- Pattern: \`{target}-style-{s}-layout-{l}.html\`
- Example: \`dashboard-style-1-layout-1.html\`
## 📁 File Structure
\`\`\`
prototypes/
├── compare.html # Interactive matrix view
├── index.html # Simple navigation index
├── PREVIEW.md # This file
EOF
for style in $styles; do
for target in $targets; do
for layout in $layouts; do
echo "├── ${target}-style-${style}-layout-${layout}.html" >> PREVIEW.md
echo "├── ${target}-style-${style}-layout-${layout}.css" >> PREVIEW.md
done
done
done
cat >> PREVIEW.md << 'EOF2'
```
## 🎨 Style Variants
EOF2
for style in $styles; do
cat >> PREVIEW.md << EOF3
### Style ${style}
EOF3
style_guide="../style-consolidation/style-${style}/style-guide.md"
if [[ -f "$style_guide" ]]; then
head -n 10 "$style_guide" | tail -n +2 >> PREVIEW.md 2>/dev/null || echo "Design philosophy and tokens" >> PREVIEW.md
else
echo "Design system ${style}" >> PREVIEW.md
fi
echo "" >> PREVIEW.md
done
cat >> PREVIEW.md << 'EOF4'
## 🎯 Targets
EOF4
for target in $targets; do
target_capitalized="$(echo ${target:0:1} | tr '[:lower:]' '[:upper:]')${target:1}"
echo "- **${target_capitalized}**: ${L} layouts × ${S} styles = $((L*S)) variations" >> PREVIEW.md
done
cat >> PREVIEW.md << 'EOF5'
## 💡 Tips
1. **Comparison**: Use compare.html to see how different styles affect the same layout
2. **Navigation**: Use index.html for quick access to specific prototypes
3. **Selection**: Mark favorites in compare.html using star icons
4. **Export**: Download selection JSON for implementation planning
5. **Inspection**: Open browser DevTools to inspect HTML structure and CSS
6. **Sharing**: All files are standalone - can be shared or deployed directly
## 📝 Next Steps
1. Review prototypes in compare.html
2. Select preferred style × layout combinations
3. Export selections as JSON
4. Provide feedback for refinement
5. Use selected designs for implementation
---
Generated by /workflow:ui-design:generate-v2 (Style-Centric Architecture)
EOF5
echo -e "${GREEN} ✓ Generated PREVIEW.md${NC}"
# ============================================================================
# Completion Summary
# ============================================================================
echo ""
echo -e "${GREEN}✅ Preview generation complete!${NC}"
echo -e " Files created: compare.html, index.html, PREVIEW.md"
echo -e " Matrix: ${S} styles × ${L} layouts × ${T} targets = $((S*L*T)) prototypes"
echo ""
echo -e "${YELLOW}🌐 Next Steps:${NC}"
echo -e " 1. Open compare.html for interactive matrix view"
echo -e " 2. Open index.html for simple navigation"
echo -e " 3. Read PREVIEW.md for detailed usage guide"
echo ""

View File

@@ -5,6 +5,144 @@ All notable changes to Claude Code Workflow (CCW) will be documented in this fil
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [4.3.0] - 2025-10-10
### 🎨 UI Design Workflow V2 - Self-Contained CSS Architecture
This release introduces a major architectural improvement to the UI Design Workflow, removing the placeholder mechanism and enabling agents to generate fully self-contained CSS files directly from design tokens.
#### Changed
**UI Design Workflow V2 Commands**:
- **`/workflow:ui-design:generate-v2`**: Enhanced prototype generation with self-contained CSS
- Agents now read `design-tokens.json` and generate independent CSS files
- CSS contains direct token values (e.g., `#3b82f6`) instead of `var()` references
- HTML files reference CSS directly: `<link rel="stylesheet" href="page-style-1-layout-2.css">`
- No more placeholder mechanism or post-processing steps
- **`/workflow:ui-design:explore-auto-v2`**: Updated to use new generation architecture
- Automatic coordination with `generate-v2` command
- Streamlined workflow without placeholder replacement
**Removed Dependencies**:
-**No more `tokens.css`**: Eliminated intermediate CSS variable files
-**No more Phase 1.6**: Removed token-to-CSS conversion step
-**No more placeholder replacement**: Scripts no longer process `{{STYLE_CSS}}` placeholders
**Agent Instructions Enhanced**:
- Agents receive `design-tokens.json` as primary design system reference
- Direct CSS generation instructions with token value extraction guidance
- Better adaptation to `design_attributes` (density, visual_weight, formality, etc.)
- Example instruction: "Use color values for backgrounds, typography values for fonts"
**Script Simplification** (`ui-generate-preview-v2.sh`):
- Removed placeholder replacement logic (32 lines removed)
- Focus solely on preview file generation (compare.html, index.html, PREVIEW.md)
- Cleaner, more focused responsibility
#### Improved
**Style Differentiation**:
- 🎨 **Better Style Diversity**: Agents can now freely adapt token values based on design philosophy
- 🎯 **Stronger Visual Identity**: Each style variant can use different color spaces, typography scales
- 💡 **Design-Aware Selection**: Agents intelligently select tokens matching design_attributes
**Workflow Simplicity**:
- 📉 **Reduced Complexity**: 346 lines of code removed (net reduction)
-**Fewer Steps**: Eliminated intermediate conversion and replacement phases
- 🔧 **Easier Debugging**: All styling visible directly in generated CSS files
- 📝 **Clearer Agent Tasks**: Agents have single, focused responsibility
**CSS Generation Quality**:
- 🎨 **Fully Embodies Design**: CSS directly reflects design token values
- 🔄 **No External Dependencies**: Each CSS file is completely self-contained
- 📊 **Better Adaptation**: Agents can adjust values based on layout context
- 🎯 **Style-Specific Implementation**: Same layout + different style = truly different CSS
#### Technical Details
**Before (v4.2.x)**:
```html
<!-- Agent generates HTML with placeholders -->
<link rel="stylesheet" href="{{TOKEN_CSS}}">
<link rel="stylesheet" href="{{STRUCTURAL_CSS}}">
<!-- Phase 1.6: Convert design-tokens.json → tokens.css -->
<!-- Phase 3a: Replace placeholders with actual paths -->
```
**After (v4.3.0)**:
```html
<!-- Agent generates HTML with direct reference -->
<link rel="stylesheet" href="dashboard-style-1-layout-2.css">
<!-- CSS contains direct values from design-tokens.json -->
.button { background: #3b82f6; font-size: 16px; }
```
**Workflow Comparison**:
```
Old Flow:
Phase 1.5: Inspiration → Phase 1.6: Token Conversion → Phase 2: Agent Gen →
Phase 3a: Replace Placeholders → Phase 3b: Preview
New Flow:
Phase 1.5: Inspiration → Phase 2: Agent Gen (reads tokens.json directly) →
Phase 3: Preview
```
#### Benefits
**Developer Experience**:
- 🚀 **Faster Execution**: Removed 2 intermediate processing steps
- 📁 **Simpler Output**: No more tokens.css files to manage
- 🔍 **Easier Inspection**: All styling visible in prototype CSS files
- 🎯 **Clearer Intent**: Direct mapping from design tokens to CSS
**Design Quality**:
- 🎨 **Richer Style Variations**: Agents can adapt token usage creatively
- 💪 **Stronger Differentiation**: Each style truly looks different
- 🎯 **Context-Aware Styling**: Agents adjust tokens based on layout needs
-**Better Design Expression**: No constraints from CSS variable structure
**Maintainability**:
- 📉 **Less Code**: 346 lines removed (5 files modified)
- 🔧 **Fewer Moving Parts**: Removed token conversion and placeholder systems
- 📝 **Clearer Responsibilities**: Scripts focus on single purpose
- 🧪 **Easier Testing**: Self-contained files easier to validate
#### Files Changed
**Commands Updated**:
- `.claude/commands/workflow/ui-design/generate-v2.md`: Removed Phase 1.6 and Phase 3a, updated agent instructions
- `.claude/commands/workflow/ui-design/explore-auto-v2.md`: Updated to work with new architecture
- `.claude/commands/workflow/ui-design/generate.md`: Documentation updates
- `.claude/commands/workflow/ui-design/extract.md`: Documentation updates
**Scripts Modified**:
- `.claude/scripts/ui-generate-preview-v2.sh`: Removed placeholder replacement (32 lines)
**Total Impact**:
- 5 files changed
- 471 insertions, 817 deletions
- Net: -346 lines (31% reduction in UI generation code)
#### Migration Notes
**No Breaking Changes** for users:
- ✅ V2 commands are separate from V1 (`generate-v2` vs `generate`)
- ✅ Existing workflows continue to work unchanged
- ✅ New commands are opt-in
**For New Projects**:
- Use `/workflow:ui-design:generate-v2` for better style differentiation
- Use `/workflow:ui-design:explore-auto-v2` for automatic workflow
**Design Token Changes**:
- `design-tokens.json` structure unchanged
- `tokens.css` files no longer generated (V2 commands only)
- Style guides (`style-guide.md`) unchanged
## [4.2.1] - 2025-10-10
### 📝 Command Renaming & Documentation Refactoring