Compare commits

..

36 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
catlog22
92c543aa45 release: v4.2.1 - Command rename and documentation updates
- Rename /workflow:concept-verify to /workflow:concept-clarify
- Update CHANGELOG.md with v4.2.1 release notes
- Improve command naming for better clarity

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 09:58:23 +08:00
catlog22
4cf66b41a4 refactor(ui-design): update workflow commands and agent configuration
**Agent Changes:**
- Update ui-design-agent.md with refined task definitions
- Improve agent prompt structure and guidelines

**Workflow Command Updates:**
- Simplify explore-auto.md workflow orchestration (-589 lines)
- Streamline imitate-auto.md for faster execution (-378 lines)
- Optimize update.md command flow and documentation (-136 lines)

**Architecture Updates:**
- Update workflow-architecture.md with current patterns
- Refine command parameter documentation

**Cleanup:**
- Remove outdated release-notes-v3.5.0.md

**Summary:**
- Net reduction: 729 lines removed
- Improved clarity and maintainability
- Better alignment with agent-driven execution model

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 09:46:27 +08:00
catlog22
f6292a6288 refactor(ui-design): relocate MCP research from extract to consolidate agent
**Extract Changes:**
- Remove Phase 1.5 MCP trend research (Exa queries)
- Save design-space-analysis.json with search keywords for consolidate
- Update to pure Claude-native analysis (aligns with philosophy)
- Simplify completion todos and output documentation

**Consolidate Changes:**
- Load design-space-analysis.json from extraction phase
- Add Step 1: Variant-Specific Trend Research (MCP) to agent prompt
- Agent performs 4 MCP queries per variant + shared accessibility research
- Refine tokens using trend insights while maintaining variant identity
- Update completion reporting and key features

**Generate Changes:**
- Enhance HTML placeholder documentation with critical warnings
- Add complete HTML template examples (page/component modes)
- Clarify {{STRUCTURAL_CSS}} and {{TOKEN_CSS}} placeholder rules
- Simplify agent completion requirements (remove detailed report format)
- Allow agent to self-report completion status

**Benefits:**
- Extract becomes truly Claude-native (no external tools)
- Consolidate agent handles all MCP research in one place
- Better separation of concerns between phases
- Clearer template generation instructions for agents
- More flexible agent reporting

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 09:41:49 +08:00
catlog22
29dfd49c90 Enhance UI Design Workflow: Parameter Validation and Documentation Improvements
- Added validation for --style-variants in generate command to ensure it matches actual style directories, preventing errors during prototype generation.
- Updated ui-instantiate-prototypes.sh script to validate style variants against existing directories, providing warnings and auto-correcting when necessary.
- Improved clarity in generate.md documentation regarding parameters, default values, and auto-detection mechanisms.
- Created a comprehensive UI Design Workflow Parameter Clarity Report to address inconsistencies in parameter naming and documentation across extract, consolidate, and generate commands.
- Unified parameter naming conventions to reduce confusion and improve user experience.
- Enhanced user guidance with a new README.md for the UI Design Workflow, outlining best practices and common mistakes.
2025-10-09 22:37:20 +08:00
catlog22
f0bed9e072 Refactor UI design workflow scripts and documentation
- Removed the generation of a unified consolidation report in the consolidate.md file, streamlining the output structure.
- Updated the extract.md file to prioritize the --base-path argument for session management and improved error handling for style variant detection.
- Enhanced generate.md to enforce critical requirements for layout templates, ensuring independence from other targets.
- Added a comprehensive analysis report for the ui-instantiate-prototypes.sh script, detailing issues with style variant mismatches and proposing solutions for validation and prevention.
2025-10-09 22:10:22 +08:00
catlog22
a7153dfc6d fix: unify agent output pattern in generate.md to match consolidate.md
Changes agent task delegation from direct file writing to labeled output format, giving main command control over file paths. Fixes path inconsistency issues when called from explore-auto workflow.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 20:46:26 +08:00
catlog22
02448ccd21 refactor: unify UI design workflow target parameters for pages and components
Consolidate separate page/component modes into a unified target system to
reduce code duplication and simplify the workflow parameter model.

Changes:
- Merge --pages and --components into unified --targets parameter
- Add --target-type (auto|page|component) with intelligent detection
- Remove Phase 0d from explore-auto.md (131 lines of duplicate logic)
- Implement detect_target_type() helper for automatic classification
- Update generate.md to support adaptive wrapper generation
  - Full HTML structure for pages
  - Minimal wrapper for isolated components
- Update imitate-auto.md and update.md for parameter consistency
- Enhance ui-design-agent.md with adaptive design capabilities
- Maintain full backward compatibility with legacy syntax

Benefits:
- Code reduction: -35% in target inference logic (255 → 165 lines)
- Maintenance: Single unified logic path vs dual implementations
- Extensibility: Foundation for future mixed-mode support
- UX: Simpler parameter model with automatic type detection

Technical Details:
- explore-auto.md: 605 lines changed (unified Phase 0c)
- generate.md: 353 lines changed (targets + adaptive wrapper)
- Net change: +685 insertions, -504 deletions across 5 files

All existing workflows remain compatible via legacy parameter support.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 20:33:09 +08:00
catlog22
1d573979c7 feat: refactor UI design workflow for agent-driven execution and default separate mode
## Core Changes

### 1. Fix Token Application Issues (v4.2.1-fix)
- Add convert_tokens_to_css.sh script for design-tokens.json → tokens.css conversion
- Auto-generate Google Fonts @import for web fonts
- Auto-generate global font application rules (body, headings)
- Add Phase 1.8 to generate.md: Token Variable Name Extraction
- Update generate.md Phase 2a: Inject exact variable names into agent prompt
- Fix CSS variable naming mismatches (20+ variables)

### 2. Refactor consolidate.md - Default to Separate Mode
- Remove --keep-separate parameter (now default behavior)
- Remove Unified Mode (Phase 4A) entirely
- Use ui-design-agent for multi-file generation (Phase 4)
- Generate N independent design systems by default
- Update documentation and completion messages
- Add Task(*) to allowed-tools

### 3. Update explore-auto.md Integration
- Remove --keep-separate from Phase 2 consolidate command
- Update comments to reflect default separate mode behavior

### 4. Refactor ui-design-agent.md (v2.0 → v3.0)
- Remove slash command execution logic
- Focus on consolidate.md and generate.md task execution
- Remove workflow orchestration content
- Add MCP integration strategies (Exa + Code Index)
- Integrate v4.2.1-fix changes

## Impact
- All workflows now default to separate design systems (matrix-ready)
- Agent handles multi-file generation efficiently
- Token application issues resolved
- Simplified user experience (fewer parameters)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 19:42:50 +08:00
catlog22
447837df39 fix: ensure correct layout variant count generation in UI workflow
Fix layout strategy generation issues across UI design commands:
- consolidate.md: Enhance layout synthesis prompt with explicit examples and requirements
  * Add concrete 3-layout example to clarify expected output structure
  * Emphasize requirement to generate EXACTLY N strategies (not more, not less)
  * Add sequential ID validation (layout-1, layout-2, ..., layout-N)
- explore-auto.md: Add missing --layout-variants parameter to consolidate command call
  * Phase 2 now passes layout_variants count to ensure correct strategy generation
  * Prevents mismatch between requested layouts and generated strategies
- extract.md: Update next step suggestions to include --layout-variants parameter
  * Users now see optional [--layout-variants <count>] in command examples
  * Improves discoverability of layout customization option

Before: consolidate would only generate default 3 layouts even when user specified different count
After: consolidate receives and respects user-specified layout variant count

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 18:17:39 +08:00
catlog22
20c75c0060 feat: integrate Exa MCP for design trend research in UI workflow
Enhance UI Design Workflow with intelligent design trend research capabilities:
- Add design trend analysis in extract phase using Exa MCP API
- Integrate layout strategy planning with current UI/UX patterns (2024-2025)
- Update consolidation command to include dynamic layout generation
- Add ui-instantiate-prototypes.sh script for prototype management
- Simplify path structure by removing nested .design directories
- Update workflow architecture documentation

This integration enables context-aware design decisions based on modern design trends
and improves the quality of generated UI prototypes.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 18:04:37 +08:00
catlog22
c7e2d6f82f Refactor documentation for UI Design Workflow (v4.2.1): Optimize explore-auto and imitate-auto commands, enhance clarity and maintainability, and reduce file sizes while preserving functionality. Remove CHANGELOG-v4.2.0.md as it is no longer needed. Update README and README_CN to reflect new version and features. 2025-10-09 15:51:23 +08:00
catlog22
561a04c193 feat: add imitate-auto workflow for rapid UI design replication
- Introduced a new command `/workflow:ui-design:imitate-auto` for imitating UI designs from URLs or images.
- Streamlined execution model with 5 phases: initialization, screenshot capture, style extraction, token adaptation, and prototype generation.
- Emphasized single style and layout generation, bypassing the consolidate step for improved speed.
- Implemented automated screenshot capture with fallback to manual input if necessary.
- Enhanced error handling for missing references and screenshot failures.
- Provided detailed documentation and examples for usage and execution flows.
2025-10-09 14:38:35 +08:00
catlog22
76fc10c2f9 feat: v4.2.0 - Enhance multi-page support with improved prompt parsing, cross-page consistency validation, and user confirmation mechanisms 2025-10-09 12:19:31 +08:00
catlog22
ad32e7f4a2 docs: move CHANGELOG files to root directory
Move version changelogs to project root for better visibility:
- CHANGELOG-v4.1.0.md (Pure matrix mode + path corrections)
- CHANGELOG-v4.1.1.md (Windows symlink fix + agent optimization)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 11:37:25 +08:00
catlog22
184fd1475b fix: v4.1.1 - Windows symlink fix and layout-based agent optimization
## Fixes
- Fix Windows symlink creation using mklink /D instead of ln -s
- Resolve duplicate directory issue (latest/ vs runs/run-xxx/)

## Optimizations
- Redesign agent allocation from style-based to layout-based
- Add batch processing (max 8 styles per agent)
- Reduce agent count by 60%+ for high variant scenarios (32 styles: 32→12 agents)

## Files Changed
- auto.md: Phase 0b symlink creation (Windows-compatible)
- generate.md: Phase 2 agent allocation strategy (layout-based)
- CHANGELOG-v4.1.1.md: Complete documentation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 11:27:23 +08:00
catlog22
b27708a7da feat: v4.1.0 - UI design workflow matrix mode refactoring
## Core Changes
- Pure matrix mode (style × layout combinations)
- Removed standard/creative mode selection
- Simplified parameters: --style-variants, --layout-variants
- Path corrections: standalone mode uses .workflow/.scratchpad/

## Modified Files
- auto.md: Simplified Phase 3, corrected paths
- generate.md: Complete rewrite for matrix-only mode
- consolidate.md: Path corrections for standalone mode
- extract.md: Path corrections for standalone mode

## New Files
- CHANGELOG-v4.1.0.md: Complete changelog
- _template-compare-matrix.html: Interactive visualization template

## Breaking Changes
- Deprecated: --variants, --creative-variants
- New: --style-variants, --layout-variants
- File naming: {page}-style-{s}-layout-{l}.html

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 10:52:34 +08:00
catlog22
56a3543031 chore: remove obsolete files
- Remove old RELEASE_NOTES_v3.2.3.md (use CHANGELOG.md instead)
- Remove accidentally added tailwind-tokens.js

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 09:39:34 +08:00
catlog22
28c93a0001 refactor: v4.0.2 - Complete UI design workflow refactoring
BREAKING CHANGES:
- Command paths: /workflow:design:* → /workflow:ui-design:*
- Removed --tool parameter from all commands
- Pure Claude execution, zero external tool dependencies

Major Changes:
- style-extract: Single-pass Claude analysis (1 file vs 4+)
- style-consolidate: Claude synthesis (no gemini-wrapper/codex)
- ui-generate: Unified agent-only execution
- File renames: style-extract.md → extract.md, etc.

Improvements:
- Zero external dependencies (no CLI tools)
- Faster execution, reduced I/O
- Enhanced reproducibility
- Streamlined data flow

Updated:
- CHANGELOG.md: Detailed v4.0.2 release notes
- README.md: Updated all UI design examples
- Command files: Complete rewrite for Claude-native execution

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 09:36:30 +08:00
catlog22
81e1d3e940 docs: update README for v4.0.1 with intelligent page inference
Updates:
- Version badge: v3.5.0 → v4.0.1
- What's New: Highlight intelligent page inference and agent mode
- Phase 2 examples: Show simplified commands with page inference
- UI Design Commands: Update all command examples and descriptions
- Command table: Update descriptions with v4.0 features

Key changes:
- Simplest command: /workflow:design:auto --prompt "Modern blog with home and article pages"
- All parameters now optional with smart defaults
- Agent mode examples with --use-agent flag
- Dual input sources (images + text prompts)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-07 22:04:24 +08:00
27 changed files with 7484 additions and 3048 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,11 @@
---
name: concept-verify
name: concept-clarify
description: Identify underspecified areas in brainstorming artifacts through targeted clarification questions before action planning
usage: /workflow:concept-verify [--session <session-id>]
usage: /workflow:concept-clarify [--session <session-id>]
argument-hint: "optional: --session <session-id>"
examples:
- /workflow:concept-verify
- /workflow:concept-verify --session WFS-auth
- /workflow:concept-clarify
- /workflow:concept-clarify --session WFS-auth
allowed-tools: Read(*), Write(*), Edit(*), TodoWrite(*), Glob(*), Bash(*)
---
@@ -255,7 +255,7 @@ You **MUST** consider the user input before proceeding (if not empty).
- ✅ **PROCEED to /workflow:plan**: Conceptual foundation is clear
- OR ⚠️ **Address Outstanding Items First**: {list critical outstanding items}
- OR 🔄 **Run /workflow:concept-verify Again**: If new information available
- OR 🔄 **Run /workflow:concept-clarify Again**: If new information available
### Next Steps
```bash

View File

@@ -1,451 +0,0 @@
---
name: auto
description: Orchestrate UI design refinement workflow with interactive checkpoints for user selection
usage: /workflow:design:auto [--prompt "<desc>"] [--images "<glob>"] [--pages "<list>"] [--session <id>] [--variants <count>] [--use-agent] [--batch-plan]
argument-hint: "[--prompt \"Modern SaaS\"] [--images \"refs/*.png\"] [--pages \"dashboard,auth\"] [--session WFS-xxx] [--variants 3] [--use-agent]"
examples:
- /workflow:design:auto --prompt "Modern blog with home, article and author pages, dark theme"
- /workflow:design:auto --prompt "SaaS dashboard and settings" --variants 3 --use-agent
- /workflow:design:auto --images "refs/*.png" --prompt "E-commerce site: home, product, cart"
- /workflow:design:auto --session WFS-auth --images "refs/*.png" --variants 2
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*)
---
# UI Design Auto Workflow Command
## Overview
Semi-autonomous UI design workflow with interactive checkpoints: style extraction → **user selection** → consolidation → UI generation → **user confirmation** → design update → optional batch planning.
## Coordinator Role
**Checkpoint-based orchestrator**: Execute Phase 1 automatically, pause for user style selection, execute Phase 3, pause for user prototype confirmation, complete with optional batch task generation.
## Execution Model - Checkpoint Workflow
This workflow runs **semi-autonomously** with user checkpoints:
1. **User triggers**: `/workflow:design:auto --session WFS-xxx --images "refs/*.png" --pages "dashboard,auth" [--batch-plan]`
2. **Phase 1 executes** (style-extract) → Reports style cards → **⏸️ PAUSE FOR USER SELECTION**
3. **User selects variants** → Runs `style-consolidate --variants "..."` → Auto-continues
4. **Phase 3 executes** (ui-generate) → Reports prototypes → **⏸️ PAUSE FOR USER CONFIRMATION**
5. **User confirms prototypes** → Runs `design-update --selected-prototypes "..."` → Auto-continues
6. **Phase 5 executes** (batch-plan, optional) → Reports task files
**Checkpoint Mechanism**:
- TodoWrite tracks current phase with "awaiting_user_confirmation" status
- System reports output location and exact command for next step
- User runs provided command to continue workflow
- Workflow resumes automatically after user input
## Core Rules
1. **Start Immediately**: First action is TodoWrite initialization, second action is Phase 1 command execution
2. **No Preliminary Analysis**: Do not read files or validate before Phase 1 (commands handle their own validation)
3. **Parse Every Output**: Extract required data from each command's output for next phase
4. **Pause at Checkpoints**: After Phase 1 and Phase 3, pause and prompt user with exact command to continue
5. **User-Driven Continuation**: Workflow resumes when user runs style-consolidate or design-update commands
6. **Track Progress**: Update TodoWrite after every phase completion and checkpoint
## Parameter Requirements
**Optional Parameters** (all have smart defaults):
- `--pages "<page_list>"`: Pages to generate (if omitted, inferred from prompt/session)
- `--session <session_id>`: Workflow session ID (if omitted, runs in standalone mode)
- `--images "<glob_pattern>"`: Reference image paths (default: `design-refs/*`)
- `--prompt "<description>"`: Text description of design style and pages
- `--variants <count>`: Number of style/UI variants to generate (default: 3, range: 1-5)
- `--use-agent`: Enable agent-driven creative exploration mode
- `--batch-plan`: Auto-generate implementation tasks after design-update (integrated mode only)
**Input Source Rules**:
- Must provide at least one of: `--images` or `--prompt`
- Both can be combined for guided style analysis
**Page Inference Logic**:
1. If `--pages` provided: Use explicit list
2. Else if `--prompt` provided: Extract page names from prompt text
- Example: "dashboard and login page" → ["dashboard", "login"]
- Example: "Modern SaaS app" → ["home", "dashboard", "settings"]
3. Else if `--session` provided (integrated mode): Infer from synthesis-specification.md
4. Else: Default to ["home"]
## Execution Modes
### Integrated Mode (with `--session`)
- Works within existing workflow session: `.workflow/WFS-{session}/`
- Reads from `.brainstorming/` artifacts
- Phase 4 (design-update) updates synthesis-specification.md
- Enables `--batch-plan` for task generation
### Standalone Mode (without `--session`)
- Creates new session: `design-session-YYYYMMDD-HHMMSS/`
- Independent of brainstorming phase
- Phase 4 (design-update) is **skipped**
- Outputs final summary instead of artifact updates
### Mode Detection
```bash
IF --session provided:
mode = "integrated"
base_path = ".workflow/WFS-{session}/"
ELSE:
mode = "standalone"
session_id = "design-session-" + timestamp()
base_path = "./{session_id}/"
```
## 5-Phase Execution
### Phase 0: Page Inference (if needed)
**Infer page list if not explicitly provided**:
```bash
IF --pages provided:
page_list = {explicit_pages}
ELSE IF --prompt provided:
# Extract page names from prompt using Claude analysis
page_list = extract_page_names_from_prompt({prompt_text})
# Examples:
# "dashboard and login page" → ["dashboard", "login"]
# "blog with home, article, author pages" → ["home", "article", "author"]
# "Modern SaaS app" → ["home", "dashboard", "settings"]
ELSE IF --session provided:
# Read synthesis-specification.md and extract page requirements
page_list = extract_pages_from_synthesis({session_id})
ELSE:
page_list = ["home"] # Default fallback
VALIDATE: page_list not empty
```
### Phase 1: Style Extraction
**Command Construction**:
```bash
variants_flag = --variants present ? "--variants {variants_count}" : ""
agent_flag = --use-agent present ? "--use-agent" : ""
images_flag = --images present ? "--images \"{image_glob}\"" : ""
prompt_flag = --prompt present ? "--prompt \"{prompt_text}\"" : ""
session_flag = --session present ? "--session {session_id}" : ""
command = "/workflow:design:style-extract {session_flag} {images_flag} {prompt_flag} {variants_flag} {agent_flag}"
```
**Command**: `SlashCommand(command="{constructed_command}")`
**Parse Output**:
- Verify: `.design/style-extraction/style-cards.json` created
- Extract: `style_cards_count` (should match `variants_count`)
- List available style variant IDs
**Validation**:
- Style cards successfully generated
- Variant count matches requested count
**TodoWrite**: Mark phase 1 completed, mark checkpoint "awaiting_user_confirmation"
**⏸️ CHECKPOINT 1: Pause for User Style Selection**
```
Phase 1 Complete: Style Extraction
Style cards generated: {count}
Available variants: {variant_ids}
Location: .workflow/WFS-{session}/.design/style-extraction/
⏸️ USER SELECTION REQUIRED
Review style cards and select your preferred variants.
Then run:
/workflow:design:style-consolidate --session WFS-{session} --variants "{variant_ids}"
Example: /workflow:design:style-consolidate --session WFS-{session} --variants "variant-1,variant-3"
```
---
### Phase 2: Style Consolidation (User-Triggered)
**User Command**: `/workflow:design:style-consolidate --session {session_id} --variants "{selected_variants}"`
**After user runs command**:
- Workflow automatically continues to Phase 3
- Parse output: token_count, validation_status
**TodoWrite**: Mark phase 2 completed, phase 3 in_progress
**Output**:
```
Phase 2 Complete: Style Consolidation
Design tokens: {count}
Validation: {pass|warnings}
Location: .workflow/WFS-{session}/.design/style-consolidation/
Continuing to Phase 3: UI Generation...
```
---
### Phase 3: UI Generation (Auto-Triggered after Phase 2)
**Command Construction**:
```bash
variants_flag = --variants present ? "--variants {variants_count}" : ""
agent_flag = --use-agent present ? "--use-agent" : ""
session_flag = --session present ? "--session {session_id}" : ""
command = "/workflow:design:ui-generate {session_flag} --pages \"{page_list}\" {variants_flag} {agent_flag}"
```
**Command**: `SlashCommand(command="{constructed_command}")`
**Parse Output**:
- Verify: `.design/prototypes/*.html` files created
- Extract: `prototype_count`, `page_list`, `generated_files` list
**Validation**:
- All requested pages generated
- HTML and CSS files present for each variant
**TodoWrite**: Mark phase 3 completed, mark checkpoint "awaiting_user_confirmation"
**⏸️ CHECKPOINT 2: Pause for User Prototype Confirmation**
```
Phase 3 Complete: UI Generation
Prototypes generated: {count} ({page_list})
Generated files: {file_list}
Location: .workflow/WFS-{session}/.design/prototypes/
⏸️ USER CONFIRMATION REQUIRED
Review the generated prototypes and select your preferred variants.
Then run:
/workflow:design:design-update --session WFS-{session} --selected-prototypes "{prototype_ids}"
Example: /workflow:design:design-update --session WFS-{session} --selected-prototypes "dashboard-variant-1,auth-variant-2"
Or to use all generated prototypes:
/workflow:design:design-update --session WFS-{session}
```
---
### Phase 4: Design System Integration (User-Triggered)
**User Command**: `/workflow:design:design-update --session {session_id} [--selected-prototypes "{selected_prototypes}"]`
**After user runs command**:
- Workflow updates brainstorming artifacts
- If --batch-plan flag present, automatically continues to Phase 5
**Parse Output**:
- Verify: `synthesis-specification.md` updated
- Verify: `ui-designer/style-guide.md` created/updated
**TodoWrite**: Mark phase 4 completed
**Output** (if --batch-plan NOT present):
```
UI Design Refinement Complete for session: WFS-{session}
Design System Summary:
- Tokens: {token_count} (OKLCH-based)
- Prototypes: {prototype_count} ({page_list})
- Validation: {pass|warnings}
Updated Artifacts:
✓ synthesis-specification.md (UI/UX Guidelines section)
✓ ui-designer/style-guide.md (comprehensive style guide)
✓ Design tokens ready for task generation
Location: .workflow/WFS-{session}/.design/
Next Steps:
1. Review prototypes: .workflow/WFS-{session}/.design/prototypes/
2. Continue to planning: /workflow:plan [--agent] "<task description>"
(The plan phase will automatically discover and utilize the design system)
```
**Output** (if --batch-plan present):
```
Phase 4 Complete: Design System Integration
Updated Artifacts:
✓ synthesis-specification.md
✓ ui-designer/style-guide.md
Continuing to Phase 5: Batch Task Generation...
```
---
### Phase 5: Batch Task Generation (Optional, Auto-Triggered if --batch-plan)
**Condition**: Only executes if `--batch-plan` flag present
**Execution**:
```bash
FOR each page IN selected_prototypes_pages:
SlashCommand(command="/workflow:plan --agent \"Implement {page} page based on design system\"")
# Parse output task file location
task_files.add(output_location)
```
**TodoWrite**: Mark phase 5 completed
**Return to User**:
```
Phase 5 Complete: Batch Task Generation
Tasks generated for: {page_count} pages
Generated task files:
{task_file_list}
Design workflow complete for session: WFS-{session}
Next: /workflow:execute
```
## TodoWrite Pattern
```javascript
// Initialize (before Phase 1)
TodoWrite({todos: [
{"content": "Execute style extraction from reference images", "status": "in_progress", "activeForm": "Executing style extraction"},
{"content": "Execute style consolidation and token validation", "status": "pending", "activeForm": "Executing style consolidation"},
{"content": "Execute UI prototype generation", "status": "pending", "activeForm": "Executing UI generation"},
{"content": "Execute design system integration to brainstorming", "status": "pending", "activeForm": "Executing design system integration"}
]})
// After Phase 1
TodoWrite({todos: [
{"content": "Execute style extraction from reference images", "status": "completed", "activeForm": "Executing style extraction"},
{"content": "Execute style consolidation and token validation", "status": "in_progress", "activeForm": "Executing style consolidation"},
{"content": "Execute UI prototype generation", "status": "pending", "activeForm": "Executing UI generation"},
{"content": "Execute design system integration to brainstorming", "status": "pending", "activeForm": "Executing design system integration"}
]})
// Continue pattern for Phase 2, 3, 4...
```
## Parameter Processing
### Session Validation
```bash
# Verify active session
CHECK: .workflow/.active-* marker files
VERIFY: session_id parameter matches active session
IF mismatch:
ERROR: "Session {session_id} is not active. Active session: {active_session_id}"
```
### Image Glob Expansion
```bash
# Expand glob pattern
expanded_paths = bash(ls {image_glob})
IF no files found:
ERROR: "No images found matching pattern: {image_glob}"
VALIDATE: All files are image formats (.png, .jpg, .jpeg, .webp)
```
### Page List Parsing
```bash
# Parse comma-separated page list
pages = split(page_list, ",")
TRIM: whitespace from each page name
VALIDATE: page_list not empty
```
## Data Flow
```
User Input
├── session_id
├── image_glob → expanded_image_paths
├── page_list → parsed_pages[]
├── --interactive → interactive_mode (bool)
└── --variants → variants_count (int)
Phase 1: style-extract
Input: session_id, expanded_image_paths
Output: style-cards.json
Phase 2: style-consolidate
Input: session_id, interactive_mode | auto-select
Output: design-tokens.json, style-guide.md, tailwind.config.js
Phase 3: ui-generate
Input: session_id, parsed_pages[], variants_count
Output: {page}-variant-{n}.html/css for each page
Phase 4: design-update
Input: session_id
Output: Updated synthesis-specification.md, ui-designer/style-guide.md
Return summary to user
```
## Error Handling
**Phase Execution Failures**:
- **Keep phase `in_progress`**: Do not proceed to next phase
- **Report error to user**: Include specific failure message from command
- **Provide recovery instructions**: Suggest manual command execution with corrected parameters
**Common Errors**:
1. **Session not found**: Verify session exists and is active
2. **No images found**: Check image glob pattern and file paths
3. **Style extraction failed**: Retry with different images or manual style description
4. **Consolidation validation errors**: Review validation-report.json and address token issues
5. **UI generation failed**: Check synthesis-specification.md for requirements clarity
6. **Integration conflicts**: Review synthesis-specification.md edit conflicts
## Workflow Position
**In Complete Development Flow**:
```
/workflow:brainstorm:auto-parallel "{topic}"
↓ Generates synthesis-specification.md (WHAT)
/workflow:design:auto --session WFS-xxx --images "refs/*.png" --pages "dashboard,auth"
↓ Refines visual design (WHAT → Visual Spec)
/workflow:plan [--agent] "{task description}"
↓ Generates task breakdown (HOW)
/workflow:execute
↓ Implements tasks with design system
```
**Key Benefits**:
1. **Visual Validation**: Users confirm design before implementation
2. **Token Enforcement**: Implementation strictly follows design system
3. **Accessibility**: WCAG AA validated at design phase
4. **Consistency**: Single source of truth for visual design
## Coordinator Checklist
✅ Initialize TodoWrite before any command execution
✅ Validate session parameter before Phase 1
✅ Expand image glob to concrete paths
✅ Parse page list to array
✅ Execute Phase 1 immediately (no preliminary analysis)
✅ Parse style card count from Phase 1 output
✅ Construct Phase 2 command based on --interactive flag
✅ Parse token count and validation status from Phase 2
✅ Construct Phase 3 command with variants parameter
✅ Parse prototype count from Phase 3 output
✅ Execute Phase 4 design system integration
✅ Verify all artifacts updated successfully
✅ Update TodoWrite after each phase
✅ After each phase, automatically continue to next phase based on TodoWrite status
## Integration Notes
**Seamless Workflow Transition**:
- Design phase is **optional but recommended** for UI-heavy projects
- Can be skipped entirely if visual design is not critical
- Brainstorming → Plan flow still works without design phase
- Design artifacts automatically discovered by task-generate if present
**Use Cases**:
- **Use design workflow**: User-facing applications, design systems, brand-critical UIs
- **Skip design workflow**: Backend APIs, CLI tools, prototypes, MVPs
**Artifact Discovery**:
- `task-generate` automatically detects `.design/` directory
- If present, adds design system to task context.artifacts
- UI tasks automatically include `load_design_tokens` in flow_control

View File

@@ -1,348 +0,0 @@
---
name: design-update
description: Update brainstorming artifacts with finalized design system
usage: /workflow:design:design-update --session <session_id> [--selected-prototypes "<list>"]
argument-hint: "--session WFS-session-id [--selected-prototypes \"dashboard-variant-1,auth-variant-2\"]"
examples:
- /workflow:design:design-update --session WFS-auth
- /workflow:design:design-update --session WFS-dashboard --selected-prototypes "dashboard-variant-1"
allowed-tools: Read(*), Write(*), TodoWrite(*), Glob(*), Bash(*)
---
# Design Update Command
## Overview
Synchronize finalized design system (tokens, style guide, selected prototypes) back to brainstorming artifacts, preparing for `/workflow:plan` phase consumption.
## Core Philosophy
- **Main Claude Execution**: Direct updates by main Claude (avoid Agent context loss, following synthesis pattern)
- **Reference-Based Integration**: Use @ references, not content duplication
- **Synthesis Alignment**: Update synthesis-specification.md UI/UX Guidelines section
- **UI Designer Sync**: Mirror design system to ui-designer/style-guide.md
- **Plan-Ready Output**: Ensure design artifacts discoverable by task-generate
## Execution Protocol
### Phase 1: Session & Design System Validation
```bash
# Validate session and verify design system completeness
CHECK: .workflow/.active-* marker files
VALIDATE: session_id matches active session
VERIFY required artifacts:
- .design/style-consolidation/design-tokens.json
- .design/style-consolidation/style-guide.md
- .design/style-consolidation/tailwind.config.js
- .design/prototypes/*.html (at least one prototype)
IF --selected-prototypes provided:
VALIDATE: Specified prototypes exist
ELSE:
AUTO-SELECT: Use all generated prototypes
```
### Phase 2: Load Design System Context
**Direct Claude Code Execution** (no Agent invocation)
```bash
# Load all design system artifacts
Read(.workflow/WFS-{session}/.design/style-consolidation/design-tokens.json)
Read(.workflow/WFS-{session}/.design/style-consolidation/style-guide.md)
Read(.workflow/WFS-{session}/.design/style-consolidation/style-philosophy.md)
Read(.workflow/WFS-{session}/.design/style-consolidation/tailwind.config.js)
# Load selected prototype files
FOR each selected_prototype IN selected_prototypes:
Read(.workflow/WFS-{session}/.design/prototypes/{selected_prototype}.html)
Read(.workflow/WFS-{session}/.design/prototypes/{selected_prototype}-notes.md)
# Load target brainstorming artifacts
Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md)
Read(.workflow/WFS-{session}/.brainstorming/ui-designer/analysis.md) [if exists]
```
### Phase 3: Update Synthesis Specification
**Direct Write by Main Claude**
Update `.brainstorming/synthesis-specification.md`:
```markdown
## UI/UX Guidelines
### Design System Reference
**Finalized Design Tokens**: @../.design/style-consolidation/design-tokens.json
**Style Guide**: @../.design/style-consolidation/style-guide.md
**Tailwind Configuration**: @../.design/style-consolidation/tailwind.config.js
### Design Philosophy
[Insert content from style-philosophy.md]
### Token System Overview
**Colors**: OKLCH-based color system with semantic naming
- Brand: primary, secondary, accent
- Surface: background, elevated, sunken
- Semantic: success, warning, error, info
**Typography**: {font_family_count} font families, {scale_count}-step scale
- Heading: {heading_font}
- Body: {body_font}
- Monospace: {mono_font}
**Spacing**: {scale_count}-step scale ({min}rem to {max}rem)
**Components**: Border radius, shadows, and component tokens defined
### Implementation Requirements
**Token Adherence**: All UI implementations MUST use design token CSS custom properties
**Accessibility**: WCAG AA compliance validated in design-tokens.json
**Responsive**: Mobile-first design using token-based breakpoints
**Component Patterns**: Follow patterns documented in style-guide.md
### Reference Prototypes
[For each selected prototype:]
- **{page_name}**: @../.design/prototypes/{prototype}.html
- Layout: {layout_description from notes}
- Components: {component_list from notes}
- Token Usage: {token_usage_summary from notes}
### Design System Assets (for task-generate consumption)
```json
{
"design_tokens": ".design/style-consolidation/design-tokens.json",
"style_guide": ".design/style-consolidation/style-guide.md",
"tailwind_config": ".design/style-consolidation/tailwind.config.js",
"prototypes": [
".design/prototypes/{prototype-1}.html",
".design/prototypes/{prototype-2}.html"
]
}
```
```
**Implementation**:
```bash
# Edit synthesis-specification.md
Edit(
file_path=".workflow/WFS-{session}/.brainstorming/synthesis-specification.md",
old_string="## UI/UX Guidelines\n[existing content or empty]",
new_string="## UI/UX Guidelines\n\n[new design system content with @ references]"
)
```
### Phase 4: Update UI Designer Analysis
**Create or update** `.brainstorming/ui-designer/style-guide.md`:
```markdown
# UI Designer Style Guide
## Design System Integration
This style guide integrates the finalized design system from the design refinement phase.
**Source Design Tokens**: @../../.design/style-consolidation/design-tokens.json
**Source Style Guide**: @../../.design/style-consolidation/style-guide.md
## Design Philosophy
[Content from style-philosophy.md]
## Design Tokens Reference
For complete token definitions, see: @../../.design/style-consolidation/design-tokens.json
### Color System
[Summary of color tokens]
### Typography System
[Summary of typography tokens]
### Spacing System
[Summary of spacing tokens]
### Component Tokens
[Summary of component tokens: border-radius, shadows]
## Component Patterns
[Reference to style-guide.md component patterns]
## Implementation Guidelines
1. **Use CSS Custom Properties**: All styles reference design tokens
2. **Follow Semantic HTML**: Use HTML5 semantic elements
3. **Maintain Accessibility**: WCAG AA compliance required
4. **Responsive Design**: Mobile-first with token-based breakpoints
## Reference Prototypes
[Links to selected prototypes with descriptions]
---
*Auto-generated by /workflow:design:design-update*
*Last updated: {timestamp}*
```
**Implementation**:
```bash
Write(
file_path=".workflow/WFS-{session}/.brainstorming/ui-designer/style-guide.md",
content="[generated style guide content with @ references]"
)
```
### Phase 5: Create Design System Symlinks (Optional)
**For easier task-generate discovery**
```bash
# Create read-only mirror of key design files in brainstorming space
bash(cd .workflow/WFS-{session}/.brainstorming && \
ln -s ../.design/style-consolidation/design-tokens.json design-tokens.json && \
ln -s ../.design/style-consolidation/style-guide.md design-style-guide.md)
```
### Phase 6: TodoWrite Integration
```javascript
TodoWrite({
todos: [
{
content: "Validate session and design system completeness",
status: "completed",
activeForm: "Validating design system"
},
{
content: "Load design tokens, style guide, and selected prototypes",
status: "completed",
activeForm: "Loading design artifacts"
},
{
content: "Update synthesis-specification.md with design system references",
status: "completed",
activeForm: "Updating synthesis specification"
},
{
content: "Create or update ui-designer/style-guide.md",
status: "completed",
activeForm: "Updating UI designer style guide"
},
{
content: "Create design system symlinks for task-generate discovery",
status: "completed",
activeForm: "Creating artifact symlinks"
}
]
});
```
## Output Structure
**Updated Files**:
```
.workflow/WFS-{session}/.brainstorming/
├── synthesis-specification.md # Updated with UI/UX Guidelines section
├── ui-designer/
│ └── style-guide.md # New or updated comprehensive style guide
├── design-tokens.json # Symlink to ../.design/style-consolidation/design-tokens.json
└── design-style-guide.md # Symlink to ../.design/style-consolidation/style-guide.md
```
**Reference Structure** (@ references in synthesis-specification.md):
- `@../.design/style-consolidation/design-tokens.json`
- `@../.design/style-consolidation/style-guide.md`
- `@../.design/style-consolidation/tailwind.config.js`
- `@../.design/prototypes/{prototype}.html`
## Integration with task-generate
After this update, `/workflow:tools:task-generate` will discover:
**In context.artifacts**:
```json
{
"artifacts": [
{
"type": "synthesis_specification",
"path": ".brainstorming/synthesis-specification.md"
},
{
"type": "design_tokens",
"path": ".design/style-consolidation/design-tokens.json"
},
{
"type": "style_guide",
"path": ".design/style-consolidation/style-guide.md"
},
{
"type": "tailwind_config",
"path": ".design/style-consolidation/tailwind.config.js"
},
{
"type": "ui_prototypes",
"paths": [
".design/prototypes/dashboard-variant-1.html",
".design/prototypes/auth-variant-2.html"
]
}
]
}
```
**In flow_control.pre_analysis** (for UI tasks):
```json
{
"step": "load_design_tokens",
"action": "Load design system tokens and style guide",
"commands": [
"bash(cat .workflow/WFS-{session}/.design/style-consolidation/design-tokens.json)",
"bash(cat .workflow/WFS-{session}/.design/style-consolidation/style-guide.md)"
],
"output_to": "design_system_context",
"on_error": "warn"
}
```
## Error Handling
- **Missing design tokens**: Error, run `/workflow:design:style-consolidate` first
- **Missing prototypes**: Error, run `/workflow:design:ui-generate` first
- **synthesis-specification.md not found**: Warning, create minimal version
- **Edit conflicts**: Preserve existing content, append design system section
- **Symlink failures**: Warning only, continue with @ references
## Validation Checks
After update, verify:
- [ ] synthesis-specification.md contains UI/UX Guidelines section
- [ ] UI/UX Guidelines include @ references to design system files
- [ ] ui-designer/style-guide.md created or updated
- [ ] design-tokens.json symlink created (if applicable)
- [ ] All referenced files exist and are readable
## Integration Points
- **Input**: design-tokens.json, style-guide.md, prototypes from design phase
- **Output**: Updated synthesis-specification.md, ui-designer/style-guide.md
- **Next Phase**: `/workflow:plan` can now discover and utilize design system
## Completion Message
```
Design system update complete for session: WFS-{session}
Updated artifacts:
✓ synthesis-specification.md - UI/UX Guidelines section added
✓ ui-designer/style-guide.md - Comprehensive style guide created
✓ Design system references: @ notation for all design files
Design system assets ready for task generation:
- design-tokens.json ({token_count} tokens)
- style-guide.md (comprehensive component patterns)
- tailwind.config.js (Tailwind theme extension)
- {prototype_count} reference prototypes
Next: /workflow:plan [--agent] "<task description>"
The plan phase will automatically discover and utilize the design system.
```
## Main Claude Direct Execution Rationale
This command is executed directly by main Claude (not delegated to an Agent) because:
1. **Context Preservation**: Main Claude has full session context and conversation memory
2. **Integration Complexity**: Requires understanding multiple artifact relationships
3. **Reference Accuracy**: @ reference generation needs precise path resolution
4. **Synthesis Pattern**: Follows the same direct-execution pattern as `/workflow:brainstorm:synthesis`
5. **Minimal Transformation**: Primarily reference integration, not generative analysis
6. **Error Recovery**: Main Claude can better handle edit conflicts and missing files
This approach ensures reliable, context-aware integration without Agent handoff overhead.

View File

@@ -1,319 +0,0 @@
---
name: style-consolidate
description: Consolidate user-selected style variants into unified design system
usage: /workflow:design:style-consolidate --session <session_id> [--interactive] [--variants "<ids>"]
argument-hint: "--session WFS-session-id [--interactive] [--variants \"variant-1,variant-3\"]"
examples:
- /workflow:design:style-consolidate --session WFS-auth --interactive
- /workflow:design:style-consolidate --session WFS-dashboard --variants "variant-1,variant-3"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*), Bash(*)
---
# Style Consolidation Command
## Overview
Consolidate user-selected style variants into a unified, production-ready design system with validated CSS tokens and comprehensive style guide.
## Core Philosophy
- **User-Driven Selection**: Interactive mode for visual style card selection
- **Gemini Clustering**: Semantic naming and style philosophy consolidation
- **Codex Validation**: Token consistency, coverage, and accessibility checks
- **Design System Output**: production-ready tokens + comprehensive style guide
## Execution Protocol
### Phase 1: Session & Style Cards Loading
```bash
# Validate session and load extracted style cards
CHECK: .workflow/.active-* marker files
VALIDATE: session_id matches active session
VERIFY: .design/style-extraction/style-cards.json exists
LOAD: style-cards.json for user selection
```
### Phase 2: User Selection (Interactive Mode)
**Interactive Mode**: `--interactive` flag enables visual selection interface
```bash
IF --interactive:
DISPLAY: Style card previews with descriptions
PROMPT: "Select preferred style variants (comma-separated IDs):"
COLLECT: user_selection (e.g., "variant-1,variant-3")
ELSE IF --variants provided:
PARSE: variant IDs from --variants flag
ELSE:
ERROR: "Must provide either --interactive or --variants parameter"
```
### Phase 3: Gemini Style Philosophy Consolidation
**Agent Invocation**: Task(conceptual-planning-agent) with Gemini capabilities
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Consolidate selected style variants into unified design philosophy
## Context Loading
ASSIGNED_TASK: style-consolidation
OUTPUT_LOCATION: .workflow/WFS-{session}/.design/style-consolidation/
SELECTED_VARIANTS: {user_selected_variant_ids}
## Flow Control Steps
1. **load_selected_variants**
- Action: Load user-selected style card data
- Command: Read(.workflow/WFS-{session}/.design/style-extraction/style-cards.json)
- Filter: Extract only selected variant IDs
- Output: selected_style_data
2. **load_design_context**
- Action: Load brainstorming design context
- Command: Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md) || Read(.workflow/WFS-{session}/.brainstorming/ui-designer/analysis.md)
- Output: design_context
- Optional: true
3. **consolidate_style_philosophy_gemini**
- Action: Synthesize unified style philosophy and semantic naming
- Command: bash(cd .workflow/WFS-{session} && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p \"
PURPOSE: Synthesize unified design philosophy from selected style variants
TASK: Create coherent style narrative, consolidate naming conventions, define design principles
MODE: write
CONTEXT: @{.design/style-extraction/style-cards.json,.brainstorming/synthesis-specification.md}
EXPECTED:
1. Unified design philosophy statement
2. Consolidated semantic naming for colors (e.g., 'brand-primary', 'surface-elevated')
3. Typography scale rationale
4. Spacing system principles
5. Component design guidelines
RULES: Ensure consistency, maintain accessibility mindset, align with brainstorming synthesis
\")
- Output: style-philosophy.md
## Consolidation Requirements
**Design Philosophy**: Clear statement of visual design principles
**Semantic Naming**: User-centric token names (not generic color-1, color-2)
**Accessibility**: Ensure WCAG AA contrast ratios for text colors
**Consistency**: Unified token naming conventions across all categories
## Expected Deliverables
1. **style-philosophy.md**: Design philosophy and naming rationale
"
```
### Phase 4: Codex Token Validation & Finalization
**Agent Invocation**: Task(conceptual-planning-agent) with Codex capabilities
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Validate and finalize production-ready design tokens
## Context Loading
INPUT_PHILOSOPHY: .workflow/WFS-{session}/.design/style-consolidation/style-philosophy.md
INPUT_TOKENS: .workflow/WFS-{session}/.design/style-extraction/design-tokens.json
SELECTED_VARIANTS: {user_selected_variant_ids}
OUTPUT_LOCATION: .workflow/WFS-{session}/.design/style-consolidation/
## Flow Control Steps
1. **load_consolidation_inputs**
- Action: Load style philosophy and extracted tokens
- Commands:
- Read(.workflow/WFS-{session}/.design/style-consolidation/style-philosophy.md)
- Read(.workflow/WFS-{session}/.design/style-extraction/design-tokens.json)
- Read(.workflow/WFS-{session}/.design/style-extraction/style-cards.json)
- Output: consolidation_inputs
2. **validate_and_finalize_tokens_codex**
- Action: Merge selected variants, validate consistency, generate final tokens
- Command: bash(codex -C .workflow/WFS-{session}/.design/style-consolidation --full-auto exec \"
PURPOSE: Finalize production-ready design tokens with validation
TASK: Merge selected variant tokens, validate consistency, check accessibility, generate final design system
MODE: auto
CONTEXT: @{style-philosophy.md,../style-extraction/design-tokens.json,../style-extraction/style-cards.json,../../../CLAUDE.md}
EXPECTED:
1. design-tokens.json - Final validated CSS token definitions
2. tailwind.config.js - Complete Tailwind configuration
3. style-guide.md - Comprehensive design system documentation
4. validation-report.json - Token consistency and accessibility audit
RULES:
- Use semantic names from style-philosophy.md
- Validate WCAG AA contrast ratios (4.5:1 for text, 3:1 for UI)
- Ensure complete token coverage (colors, typography, spacing, shadows, borders)
- Generate CSS custom properties and Tailwind theme extension
- Include usage examples in style-guide.md
\" --skip-git-repo-check -s danger-full-access)
- Output: design-tokens.json, tailwind.config.js, style-guide.md, validation-report.json
## Validation Requirements
**Consistency Checks**:
- All color tokens use OKLCH format
- Spacing scale follows consistent ratio (e.g., 1.5x or 2x progression)
- Typography scale includes appropriate line-heights
- All tokens have semantic names
**Accessibility Checks**:
- Text colors meet WCAG AA contrast (4.5:1)
- UI component colors meet WCAG AA contrast (3:1)
- Focus indicators have sufficient visibility
- Color is not sole differentiator
**Coverage Checks**:
- Primary, secondary, accent color families
- Surface colors (background, elevated, sunken)
- Semantic colors (success, warning, error, info)
- Typography scale (xs to 4xl)
- Spacing scale (0.25rem to 6rem)
- Border radius options
- Shadow layers
## Expected Deliverables
1. **design-tokens.json**: Production-ready CSS token definitions
2. **tailwind.config.js**: Complete Tailwind theme configuration
3. **style-guide.md**: Design system documentation with usage examples
4. **validation-report.json**: Validation audit results
"
```
### Phase 5: TodoWrite Integration
```javascript
TodoWrite({
todos: [
{
content: "Load session and style cards from extraction phase",
status: "completed",
activeForm: "Loading style cards"
},
{
content: "Collect user style variant selection (interactive or CLI)",
status: "completed",
activeForm: "Collecting user selection"
},
{
content: "Consolidate style philosophy using Gemini",
status: "completed",
activeForm: "Consolidating style philosophy"
},
{
content: "Validate and finalize tokens using Codex",
status: "completed",
activeForm: "Validating and finalizing tokens"
},
{
content: "Generate design system documentation",
status: "completed",
activeForm: "Generating design system docs"
}
]
});
```
## Output Structure
```
.workflow/WFS-{session}/.design/style-consolidation/
├── style-philosophy.md # Unified design philosophy (Gemini)
├── design-tokens.json # Final validated CSS tokens (Codex)
├── tailwind.config.js # Tailwind theme configuration (Codex)
├── style-guide.md # Design system documentation (Codex)
└── validation-report.json # Accessibility & consistency audit (Codex)
```
### design-tokens.json Format
```json
{
"colors": {
"brand": {
"primary": "oklch(0.45 0.20 270 / 1)",
"secondary": "oklch(0.60 0.15 200 / 1)",
"accent": "oklch(0.65 0.18 30 / 1)"
},
"surface": {
"background": "oklch(0.98 0.01 270 / 1)",
"elevated": "oklch(1.00 0.00 0 / 1)",
"sunken": "oklch(0.95 0.02 270 / 1)"
},
"semantic": {
"success": "oklch(0.55 0.15 150 / 1)",
"warning": "oklch(0.70 0.18 60 / 1)",
"error": "oklch(0.50 0.20 20 / 1)",
"info": "oklch(0.60 0.15 240 / 1)"
}
},
"typography": {
"font_family": {
"heading": "Inter, system-ui, sans-serif",
"body": "Inter, system-ui, sans-serif",
"mono": "Fira Code, monospace"
},
"font_size": {
"xs": "0.75rem",
"sm": "0.875rem",
"base": "1rem",
"lg": "1.125rem",
"xl": "1.25rem",
"2xl": "1.5rem",
"3xl": "1.875rem",
"4xl": "2.25rem"
},
"line_height": {
"tight": "1.25",
"normal": "1.5",
"relaxed": "1.75"
}
},
"spacing": {
"0": "0",
"1": "0.25rem",
"2": "0.5rem",
"3": "0.75rem",
"4": "1rem",
"6": "1.5rem",
"8": "2rem",
"12": "3rem",
"16": "4rem",
"24": "6rem"
},
"border_radius": {
"none": "0",
"sm": "0.25rem",
"md": "0.5rem",
"lg": "0.75rem",
"xl": "1rem",
"2xl": "1.5rem",
"full": "9999px"
},
"shadow": {
"sm": "0 1px 2px oklch(0.00 0.00 0 / 0.05)",
"md": "0 4px 6px oklch(0.00 0.00 0 / 0.07), 0 2px 4px oklch(0.00 0.00 0 / 0.06)",
"lg": "0 10px 15px oklch(0.00 0.00 0 / 0.1), 0 4px 6px oklch(0.00 0.00 0 / 0.05)",
"xl": "0 20px 25px oklch(0.00 0.00 0 / 0.15), 0 10px 10px oklch(0.00 0.00 0 / 0.04)"
}
}
```
## Error Handling
- **No style cards found**: Run `/workflow:design:style-extract` first
- **Invalid variant IDs**: Display available IDs and prompt re-selection
- **Validation failures**: Report specific issues (contrast, coverage, consistency)
- **Gemini/Codex execution errors**: Retry with fallback to manual token editing
## Integration Points
- **Input**: style-cards.json from `/workflow:design:style-extract`
- **Output**: design-tokens.json for `/workflow:design:ui-generate`
- **Context**: synthesis-specification.md, ui-designer/analysis.md
## Next Steps
After successful consolidation:
```
Style consolidation complete for session: WFS-{session}
Design tokens validated and finalized
Validation summary:
- Colors: {count} (WCAG AA compliant: {pass_count}/{total_count})
- Typography: {scale_count} sizes
- Spacing: {scale_count} values
- Accessibility: {pass|warnings}
Next: /workflow:design:ui-generate --session WFS-{session} --pages "dashboard,auth"
```

View File

@@ -1,268 +0,0 @@
---
name: style-extract
description: Extract design style from reference images or text prompts using triple vision analysis or agent mode
usage: /workflow:design:style-extract [--session <id>] [--images "<glob>"] [--prompt "<desc>"] [--variants <count>] [--use-agent]
argument-hint: "[--session WFS-xxx] [--images \"refs/*.png\"] [--prompt \"Modern minimalist\"] [--variants 3] [--use-agent]"
examples:
- /workflow:design:style-extract --images "design-refs/*.png" --variants 3
- /workflow:design:style-extract --prompt "Modern minimalist blog, dark theme" --variants 3 --use-agent
- /workflow:design:style-extract --session WFS-auth --images "refs/*.png" --prompt "Linear.app style" --variants 2
allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*), Task(conceptual-planning-agent)
---
# Style Extraction Command
## Overview
Extract design style elements from reference images using triple vision analysis: Claude Code's native vision, Gemini Vision for semantic understanding, and Codex for structured token generation.
## Core Philosophy
- **Dual Mode Support**: Conventional triple vision OR agent-driven creative exploration
- **Flexible Input**: Images, text prompts, or both combined
- **Variant Control**: Generate N style cards based on `--variants` parameter (default: 3)
- **Consensus Synthesis**: Multi-source analysis for quality assurance
- **Style Card Output**: Reusable design direction cards for consolidation phase
## Execution Protocol
### Phase 0: Mode & Parameter Detection
```bash
# Detect execution mode
IF --use-agent:
mode = "agent" # Agent-driven creative exploration
ELSE:
mode = "conventional" # Triple vision analysis
# Detect input source
IF --images AND --prompt:
input_mode = "hybrid" # Text guides image analysis
ELSE IF --images:
input_mode = "image"
ELSE IF --prompt:
input_mode = "text"
ELSE:
ERROR: "Must provide --images or --prompt"
# Detect session mode
IF --session:
session_mode = "integrated"
session_id = {provided_session}
base_path = ".workflow/WFS-{session_id}/"
ELSE:
session_mode = "standalone"
session_id = "design-session-" + timestamp()
base_path = "./{session_id}/"
# Set variant count
variants_count = --variants provided ? {count} : 3
VALIDATE: 1 <= variants_count <= 5
```
### Phase 1: Input Validation & Preparation
```bash
# Validate and prepare inputs based on input_mode
IF input_mode IN ["image", "hybrid"]:
EXPAND: --images glob pattern to concrete paths
VERIFY: at least one image file exists
IF input_mode IN ["text", "hybrid"]:
VALIDATE: --prompt is non-empty string
# Create session directory structure
CREATE: {base_path}/.design/style-extraction/
```
### Phase 2: Style Extraction Execution
**Route based on mode**:
#### A. Conventional Mode (Triple Vision)
Execute if `mode == "conventional"`
**Step 1**: Claude Code initial analysis
```bash
IF input_mode IN ["image", "hybrid"]:
FOR each image IN expanded_image_paths:
Read({image_path}) # Claude analyzes visuals
ELSE IF input_mode == "text":
# Analyze text prompt for design keywords
keywords = extract_design_keywords({prompt_text})
Write({base_path}/.design/style-extraction/claude_analysis.json)
```
**Step 2**: Gemini deep semantic analysis
```bash
context_arg = ""
IF input_mode IN ["image", "hybrid"]:
context_arg += "@{image_paths}"
IF input_mode IN ["text", "hybrid"]:
guidance = "GUIDED BY PROMPT: '{prompt_text}'"
bash(cd {base_path}/.design/style-extraction && \
~/.claude/scripts/gemini-wrapper --approval-mode yolo -p "
PURPOSE: Extract design semantics {guidance}
TASK: Generate {variants_count} distinct style directions
MODE: write
CONTEXT: {context_arg}
EXPECTED: {variants_count} style analysis variants in JSON
RULES: OKLCH colors, semantic naming, explore diverse themes
")
```
**Step 3**: Codex structured token generation
```bash
bash(codex -C {base_path}/.design/style-extraction --full-auto exec "
PURPOSE: Convert semantic analysis to structured tokens
TASK: Generate design-tokens.json and {variants_count} style-cards
MODE: auto
CONTEXT: @{claude_analysis.json,gemini output}
EXPECTED: design-tokens.json, style-cards.json with {variants_count} variants
RULES: OKLCH format, rem spacing, semantic names
" --skip-git-repo-check -s danger-full-access)
```
#### B. Agent Mode (Creative Exploration)
Execute if `mode == "agent"`
**Agent-Driven Parallel Generation**:
```bash
# Prepare base context
context_files = ""
IF input_mode IN ["image", "hybrid"]:
context_files += "@{image_paths}"
IF session_mode == "integrated":
context_files += "@{../../.brainstorming/synthesis-specification.md}"
# Define creative themes for diversity
themes = generate_creative_themes(variants_count)
# Example: ["Modern Minimalist", "Brutalist Tech", "Organic Warmth"]
# Launch parallel agent tasks
FOR i IN range(variants_count):
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Generate unique design style variant: '{themes[i]}'
## Context
INPUT_SOURCE: {input_mode}
PROMPT_GUIDANCE: {prompt_text if present else 'derive from images'}
THEME_FOCUS: {themes[i]}
OUTPUT_LOCATION: {base_path}/.design/style-extraction/
## Flow Steps
1. **analyze_input**
IF input_mode IN ['image', 'hybrid']:
Use Gemini Vision to analyze images with theme focus
IF input_mode IN ['text', 'hybrid']:
Use Gemini to expand prompt into detailed design philosophy
2. **generate_tokens**
Use Codex to create design-tokens subset for this variant
Output: variant-{i}-tokens.json
3. **create_style_card**
Synthesize into style card with:
- id: 'variant-{i}'
- name: '{themes[i]}'
- preview: key design token values
Output: variant-{i}-card.json
## Rules
- Focus on '{themes[i]}' aesthetic
- OKLCH colors, rem spacing, semantic naming
- Must be distinct from other variants
"
# Consolidate parallel results
Wait for all {variants_count} tasks to complete
Consolidate variant-*-card.json → style-cards.json
Merge variant-*-tokens.json → design-tokens.json (include all variants)
```
**Output**: `style-cards.json` with {variants_count} creatively distinct variants
### Phase 3: TodoWrite & Completion
```javascript
TodoWrite({
todos: [
{content: "Detect mode and validate inputs", status: "completed", activeForm: "Detecting mode"},
{content: "Execute style extraction (conventional/agent mode)", status: "completed", activeForm: "Extracting styles"},
{content: "Generate {variants_count} style cards", status: "completed", activeForm: "Generating style cards"}
]
});
```
**Completion Message**:
```
Style extraction complete for session: {session_id}
Mode: {mode} | Input: {input_mode} | Variants: {variants_count}
Generated {variants_count} style cards:
{list_variant_names}
Location: {base_path}/.design/style-extraction/
Next: /workflow:design:style-consolidate --session {session_id} --variants "{selected_ids}"
```
## Output Structure
```
.workflow/WFS-{session}/.design/style-extraction/
├── semantic_style_analysis.json # Gemini Vision semantic analysis
├── design-tokens.json # Structured CSS tokens (OKLCH)
├── tailwind-tokens.js # Tailwind config extension
└── style-cards.json # Style variants for user selection
```
### style-cards.json Format
```json
{
"style_cards": [
{
"id": "variant-1",
"name": "Modern Minimalist",
"description": "Clean, high contrast with bold typography",
"preview": {
"primary": "oklch(0.45 0.20 270 / 1)",
"background": "oklch(0.98 0.01 270 / 1)",
"font_heading": "Inter, system-ui, sans-serif",
"border_radius": "0.5rem"
}
},
{
"id": "variant-2",
"name": "Soft Neumorphic",
"description": "Subtle shadows with gentle colors",
"preview": {
"primary": "oklch(0.60 0.10 200 / 1)",
"background": "oklch(0.95 0.02 200 / 1)",
"font_heading": "Poppins, sans-serif",
"border_radius": "1rem"
}
}
]
}
```
## Error Handling
- **No images found**: Report error and suggest correct glob pattern
- **Gemini Vision failure**: Retry once, then fall back to manual style description
- **Codex token generation failure**: Use default token template and report warning
- **Invalid session**: Prompt user to start workflow session first
## Integration Points
- **Input**: Reference images (PNG, JPG, WebP)
- **Output**: Style cards for `/workflow:design:style-consolidate`
- **Context**: Optional synthesis-specification.md or ui-designer/analysis.md
## Next Steps
After successful extraction:
```
Style extraction complete for session: WFS-{session}
Style cards generated: {count}
Next: /workflow:design:style-consolidate --session WFS-{session} [--interactive]
```

View File

@@ -1,554 +0,0 @@
---
name: ui-generate
description: Generate UI prototypes using consolidated design tokens with conventional or agent mode
usage: /workflow:design:ui-generate [--pages "<list>"] [--session <id>] [--variants <count>] [--use-agent]
argument-hint: "[--pages \"dashboard,auth\"] [--session WFS-xxx] [--variants 3] [--use-agent]"
examples:
- /workflow:design:ui-generate --variants 2
- /workflow:design:ui-generate --session WFS-auth --variants 3 --use-agent
- /workflow:design:ui-generate --pages "home,pricing,contact" --variants 2
allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*), Task(conceptual-planning-agent)
---
# UI Generation Command
## Overview
Generate production-ready UI prototypes (HTML/CSS) strictly adhering to consolidated design tokens and synthesis specification requirements.
## Core Philosophy
- **Dual Mode**: Conventional (Codex primary) OR agent-driven (creative layouts)
- **Token-Driven**: All styles reference design-tokens.json, no hardcoded values
- **Variant Control**: Generate N prototypes per page based on `--variants` (default: 1)
- **Layout Diversity**: Agent mode explores structural variations (F-pattern, grid, asymmetric)
- **Production-Ready**: Semantic HTML5, ARIA attributes, responsive design
## Execution Protocol
### Phase 1: Mode Detection & Context Loading
```bash
# Detect execution mode
IF --use-agent:
mode = "agent" # Agent-driven creative layouts
ELSE:
mode = "conventional" # Codex primary generation
# Detect session mode
IF --session:
session_mode = "integrated"
session_id = {provided_session}
base_path = ".workflow/WFS-{session_id}/"
ELSE:
session_mode = "standalone"
# Infer session_id from existing design-session-* directory
base_path = "./{detected_design_session}/"
# Infer page list if not provided
IF --pages provided:
page_list = {explicit_pages}
ELSE IF session_mode == "integrated":
# Read synthesis-specification.md to extract page requirements
page_list = extract_pages_from_synthesis({base_path}/.brainstorming/synthesis-specification.md)
ELSE:
# Infer from generated prototypes or default
page_list = detect_from_prototypes({base_path}/.design/prototypes/) OR ["home"]
VALIDATE: page_list not empty
# Set parameters
variants_count = --variants provided ? {count} : 1
VALIDATE: 1 <= variants_count <= 5
# Load design system
VERIFY: {base_path}/.design/style-consolidation/design-tokens.json exists
LOAD: design-tokens.json, style-guide.md, tailwind.config.js
# Load requirements (if integrated mode)
IF session_mode == "integrated":
LOAD: {base_path}/.brainstorming/synthesis-specification.md
```
### Phase 2: UI Generation Execution
**Route based on mode**:
#### A. Conventional Mode (Codex Primary)
Execute if `mode == "conventional"`
```bash
# Single Codex call generates all variants for all pages
bash(codex -C {base_path}/.design/prototypes --full-auto exec "
PURPOSE: Generate UI prototypes adhering to design tokens
TASK: Create HTML/CSS for pages: {page_list} with {variants_count} variant(s) each
MODE: auto
CONTEXT: @{../style-consolidation/design-tokens.json,../style-consolidation/style-guide.md}
EXPECTED:
For each page, generate {variants_count} variant(s):
- {page}-variant-{n}.html (semantic HTML5)
- {page}-variant-{n}.css (token-driven, no hardcoded values)
- {page}-variant-{n}-notes.md (implementation notes)
RULES:
- STRICT token adherence: var(--color-brand-primary), var(--spacing-4)
- Semantic HTML5 + ARIA attributes
- Responsive: mobile-first, token-based breakpoints
- Variants differ in minor layout details
" --skip-git-repo-check -s danger-full-access)
```
#### B. Agent Mode (Creative Layouts)
Execute if `mode == "agent"`
**Agent-Driven Parallel Generation**:
```bash
# Define layout strategies for diversity
layouts = generate_layout_strategies(variants_count)
# Example: ["F-Pattern", "Asymmetric Grid", "Card-Based Modular"]
# Launch parallel agent tasks for each page-variant combination
FOR page IN page_list:
FOR i IN range(variants_count):
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Generate UI prototype: {page} using '{layouts[i]}' layout
## Context
PAGE: {page}
LAYOUT_STRATEGY: {layouts[i]}
OUTPUT: {base_path}/.design/prototypes/
## Flow Steps
1. **load_design_system**
Read design-tokens.json and style-guide.md
2. **load_requirements**
IF session_mode == 'integrated':
Read synthesis-specification.md for {page} requirements
3. **generate_prototype_codex**
Use Codex to generate HTML/CSS with layout focus:
Layout: {layouts[i]}
Token adherence: STRICT (all values from design-tokens)
Output: {page}-variant-{i}.html/css/notes.md
## Rules
- Layout must follow '{layouts[i]}' strategy
- Examples:
* F-Pattern: Content flows top→left→middle→bottom
* Asymmetric Grid: Strong visual hierarchy, off-center
* Card-Based: Modular components, flexible grid
- STRICT token usage, semantic HTML, ARIA attributes
"
Wait for all {len(page_list) * variants_count} tasks to complete
```
### Phase 3: Generate Preview Files
```bash
# Generate preview utilities
Write({base_path}/.design/prototypes/index.html) # Master navigation
Write({base_path}/.design/prototypes/compare.html) # Side-by-side comparison
Write({base_path}/.design/prototypes/PREVIEW.md) # Setup instructions
```
### Phase 4: TodoWrite & Completion
```javascript
TodoWrite({
todos: [
{content: "Detect mode and load design system", status: "completed", activeForm: "Loading design system"},
{content: "Generate {len(page_list) * variants_count} UI prototypes", status: "completed", activeForm: "Generating prototypes"},
{content: "Generate preview files", status: "completed", activeForm: "Generating preview"}
]
});
```
**Completion Message**:
```
UI generation complete for session: {session_id}
Mode: {mode} | Pages: {page_list} | Variants: {variants_count}
Generated {len(page_list) * variants_count} prototypes:
{list_generated_files}
Location: {base_path}/.design/prototypes/
Preview: Open index.html or run: python -m http.server 8080
Next: /workflow:design:design-update --session {session_id} --selected-prototypes "{selected_ids}"
```
## Output Structure
```
.workflow/WFS-{session}/.design/prototypes/
├── index.html # 🆕 Preview index page (master navigation)
├── compare.html # 🆕 Side-by-side comparison view
├── PREVIEW.md # 🆕 Preview instructions and server setup
├── dashboard-variant-1.html
├── dashboard-variant-1.css
├── dashboard-variant-1-notes.md
├── dashboard-variant-2.html (if --variants 2)
├── dashboard-variant-2.css
├── dashboard-variant-2-notes.md
├── auth-variant-1.html
├── auth-variant-1.css
├── auth-variant-1-notes.md
├── design-tokens.css # CSS custom properties from design-tokens.json
└── variant-suggestions.md # Gemini layout rationale (if variants > 1)
```
### HTML Prototype Example
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard - Variant 1</title>
<link rel="stylesheet" href="design-tokens.css">
<link rel="stylesheet" href="dashboard-variant-1.css">
</head>
<body>
<header role="banner" class="header">
<nav role="navigation" aria-label="Main navigation" class="nav">
<!-- Token-based navigation -->
</nav>
</header>
<main role="main" class="main">
<section aria-labelledby="dashboard-heading" class="dashboard-section">
<h1 id="dashboard-heading" class="heading-primary">Dashboard</h1>
<!-- Content using design tokens -->
</section>
</main>
<footer role="contentinfo" class="footer">
<!-- Footer content -->
</footer>
</body>
</html>
```
### CSS Example
```css
/* Design Tokens (auto-generated from design-tokens.json) */
:root {
--color-brand-primary: oklch(0.45 0.20 270 / 1);
--color-surface-background: oklch(0.98 0.01 270 / 1);
--spacing-4: 1rem;
--spacing-6: 1.5rem;
--font-size-lg: 1.125rem;
--border-radius-md: 0.5rem;
--shadow-md: 0 4px 6px oklch(0.00 0.00 0 / 0.07);
}
/* Component Styles (using tokens) */
.header {
background-color: var(--color-surface-elevated);
padding: var(--spacing-4) var(--spacing-6);
box-shadow: var(--shadow-md);
}
.heading-primary {
font-size: var(--font-size-3xl);
color: var(--color-brand-primary);
margin-bottom: var(--spacing-6);
}
```
### Preview Index Page Template (index.html)
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UI Prototypes Preview - WFS-{session}</title>
<style>
body { font-family: system-ui; max-width: 1200px; margin: 2rem auto; padding: 0 1rem; }
h1 { color: #2563eb; }
.prototype-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 1.5rem; margin-top: 2rem; }
.prototype-card { border: 1px solid #e5e7eb; border-radius: 0.5rem; padding: 1rem; transition: box-shadow 0.2s; }
.prototype-card:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
.prototype-card h3 { margin: 0 0 0.5rem; color: #1f2937; }
.prototype-card .meta { font-size: 0.875rem; color: #6b7280; margin-bottom: 1rem; }
.prototype-card a { display: inline-block; margin-right: 0.5rem; color: #2563eb; text-decoration: none; }
.prototype-card a:hover { text-decoration: underline; }
.actions { margin-top: 2rem; padding: 1rem; background: #f3f4f6; border-radius: 0.5rem; }
.actions a { margin-right: 1rem; color: #2563eb; }
</style>
</head>
<body>
<h1>🎨 UI Prototypes Preview</h1>
<p><strong>Session:</strong> WFS-{session} | <strong>Generated:</strong> {timestamp}</p>
<div class="actions">
<a href="compare.html">📊 Compare All Variants</a>
<a href="PREVIEW.md">📖 Preview Instructions</a>
</div>
<div class="prototype-grid">
<!-- Auto-generated for each page-variant -->
<div class="prototype-card">
<h3>Dashboard - Variant 1</h3>
<div class="meta">Generated: {timestamp}</div>
<a href="dashboard-variant-1.html" target="_blank">View Prototype →</a>
<a href="dashboard-variant-1-notes.md">Implementation Notes</a>
</div>
</div>
</body>
</html>
```
### Comparison View Template (compare.html)
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Side-by-Side Comparison - WFS-{session}</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: system-ui; }
.header { background: #1f2937; color: white; padding: 1rem 2rem; display: flex; justify-content: space-between; align-items: center; }
.controls { display: flex; gap: 1rem; align-items: center; }
select, button { padding: 0.5rem 1rem; border-radius: 0.25rem; border: 1px solid #d1d5db; background: white; cursor: pointer; }
button:hover { background: #f3f4f6; }
.comparison-container { display: flex; height: calc(100vh - 60px); }
.variant-panel { flex: 1; border-right: 2px solid #e5e7eb; position: relative; }
.variant-panel:last-child { border-right: none; }
.variant-label { position: absolute; top: 0; left: 0; right: 0; background: rgba(37,99,235,0.9); color: white; padding: 0.5rem; text-align: center; z-index: 10; font-weight: 600; }
iframe { width: 100%; height: 100%; border: none; padding-top: 2.5rem; }
.viewport-toggle { display: flex; gap: 0.5rem; }
.viewport-btn { padding: 0.25rem 0.75rem; font-size: 0.875rem; }
.viewport-btn.active { background: #2563eb; color: white; border-color: #2563eb; }
</style>
</head>
<body>
<div class="header">
<h1>📊 Side-by-Side Comparison</h1>
<div class="controls">
<div class="viewport-toggle">
<button class="viewport-btn active" data-width="100%">Desktop</button>
<button class="viewport-btn" data-width="768px">Tablet</button>
<button class="viewport-btn" data-width="375px">Mobile</button>
</div>
<select id="page-select">
<option value="dashboard">Dashboard</option>
<option value="auth">Auth</option>
</select>
<label><input type="checkbox" id="sync-scroll"> Sync Scroll</label>
<a href="index.html" style="color: white;">← Back to Index</a>
</div>
</div>
<div class="comparison-container">
<div class="variant-panel">
<div class="variant-label">Variant 1</div>
<iframe id="frame1" src="dashboard-variant-1.html"></iframe>
</div>
<div class="variant-panel">
<div class="variant-label">Variant 2</div>
<iframe id="frame2" src="dashboard-variant-2.html"></iframe>
</div>
</div>
<script>
// Viewport switching
document.querySelectorAll('.viewport-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.viewport-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const width = btn.dataset.width;
document.querySelectorAll('iframe').forEach(frame => {
frame.style.width = width;
frame.style.margin = width === '100%' ? '0' : '0 auto';
});
});
});
// Synchronized scrolling
const syncCheckbox = document.getElementById('sync-scroll');
const frames = [document.getElementById('frame1'), document.getElementById('frame2')];
syncCheckbox.addEventListener('change', () => {
if (syncCheckbox.checked) {
frames.forEach(frame => {
frame.contentWindow.addEventListener('scroll', () => {
const scrollTop = frame.contentWindow.scrollY;
frames.forEach(f => {
if (f !== frame) f.contentWindow.scrollTo(0, scrollTop);
});
});
});
}
});
// Page switching
document.getElementById('page-select').addEventListener('change', (e) => {
const page = e.target.value;
document.getElementById('frame1').src = `${page}-variant-1.html`;
document.getElementById('frame2').src = `${page}-variant-2.html`;
});
</script>
</body>
</html>
```
### Preview Instructions Template (PREVIEW.md)
```markdown
# UI Prototypes Preview Guide
## Session Information
- **Session ID**: WFS-{session}
- **Generated**: {timestamp}
- **Pages**: {page_list}
- **Variants per page**: {variants_count}
## Quick Preview Options
### Option 1: Direct Browser Opening (Simplest)
1. Navigate to `.workflow/WFS-{session}/.design/prototypes/`
2. Double-click `index.html` to open the preview index
3. Click any prototype link to view in browser
### Option 2: Local Development Server (Recommended)
#### Python (Built-in)
```bash
cd .workflow/WFS-{session}/.design/prototypes
python -m http.server 8080
# Visit: http://localhost:8080
```
#### Node.js (npx)
```bash
cd .workflow/WFS-{session}/.design/prototypes
npx http-server -p 8080
# Visit: http://localhost:8080
```
#### PHP (Built-in)
```bash
cd .workflow/WFS-{session}/.design/prototypes
php -S localhost:8080
# Visit: http://localhost:8080
```
#### VS Code Live Server
1. Install "Live Server" extension
2. Right-click `index.html`
3. Select "Open with Live Server"
## Preview Features
### Index Page (`index.html`)
- **Master navigation** for all prototypes
- **Quick links** to individual variants
- **Metadata display**: timestamps, page info
- **Direct access** to implementation notes
### Comparison View (`compare.html`)
- **Side-by-side** variant comparison
- **Viewport toggles**: Desktop (100%), Tablet (768px), Mobile (375px)
- **Synchronized scrolling** option
- **Page switching** dropdown
- **Real-time** comparison
## Browser Compatibility
- ✅ Chrome/Edge (Recommended)
- ✅ Firefox
- ✅ Safari
- ⚠️ Some CSS features may require modern browsers (OKLCH colors)
## Files Overview
```
prototypes/
├── index.html ← Start here
├── compare.html ← Side-by-side comparison
├── PREVIEW.md ← This file
├── {page}-variant-{n}.html ← Individual prototypes
├── {page}-variant-{n}.css ← Styles (token-driven)
├── design-tokens.css ← CSS custom properties
└── {page}-variant-{n}-notes.md ← Implementation guidance
```
## Next Steps
1. **Review prototypes**: Open index.html
2. **Compare variants**: Use compare.html for side-by-side view
3. **Select preferred**: Note variant IDs for design-update command
4. **Continue workflow**: Run design-update with selected prototypes
## Troubleshooting
**Styles not loading?**
- Ensure `design-tokens.css` is in the same directory
- Check browser console for CSS errors
- Verify file paths in HTML `<link>` tags
**OKLCH colors not displaying?**
- Use Chrome/Edge 111+ or Firefox 113+
- Fallback colors should work in older browsers
**Local server CORS issues?**
- Use one of the recommended local servers
- Avoid opening HTML files with `file://` protocol for best results
```
## Error Handling
- **No design tokens found**: Run `/workflow:design:style-consolidate` first
- **Invalid page names**: List available pages from synthesis-specification.md
- **Codex generation errors**: Retry with simplified requirements, report warnings
- **Token reference errors**: Validate all CSS against design-tokens.json
## Quality Checks
After generation, verify:
- [ ] All CSS values reference design token custom properties
- [ ] No hardcoded colors, spacing, or typography
- [ ] Semantic HTML structure
- [ ] Accessibility attributes present
- [ ] Responsive design implemented
- [ ] Token-driven styling consistent across variants
## Integration Points
- **Input**: design-tokens.json, style-guide.md, synthesis-specification.md
- **Output**: HTML/CSS prototypes for `/workflow:design:design-update`
- **Context**: ui-designer/analysis.md for UX guidance
## Next Steps
After successful generation:
```
✅ UI prototypes generated for session: WFS-{session}
Pages: {page_list}
Variants per page: {variants_count}
Generated files:
- {count} HTML prototypes (complete, standalone)
- {count} CSS files (token-driven)
- {count} implementation notes
- 🆕 index.html (preview navigation)
- 🆕 compare.html (side-by-side comparison)
- 🆕 PREVIEW.md (preview instructions)
📂 Location: .workflow/WFS-{session}/.design/prototypes/
🌐 Preview Options:
1. Quick: Open index.html in browser
2. Full: Start local server and visit http://localhost:8080
- Python: cd prototypes && python -m http.server 8080
- Node.js: cd prototypes && npx http-server -p 8080
📊 Compare Variants:
- Open compare.html for side-by-side view
- Toggle viewports: Desktop / Tablet / Mobile
- Switch between pages dynamically
- Synchronized scrolling option
Review prototypes and select preferred variants, then run:
/workflow:design:design-update --session WFS-{session} --selected-prototypes "{page-variant-ids}"
Example:
/workflow:design:design-update --session WFS-{session} --selected-prototypes "dashboard-variant-1,auth-variant-2"
```

View File

@@ -0,0 +1,450 @@
---
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>]
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
- /workflow:ui-design:consolidate --base-path "./.workflow/.design/run-20250109-150533" # Uses all variants
- /workflow:ui-design:consolidate --session WFS-auth # Process all variants from extraction
allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*), Task(*)
---
# Design System Consolidation Command
## Overview
Consolidate user-selected style variants into **independent production-ready design systems**. This command serves as the **Style Planning Phase**, focusing exclusively on design tokens and style guides for the subsequent generation phase.
## Core Philosophy
- **Style System Focus**: Exclusively handles design system consolidation
- **Agent-Driven**: Uses ui-design-agent for multi-file generation efficiency
- **Separate Design Systems**: Generates N independent design systems (one per variant)
- **Token Refinement**: Refines `proposed_tokens` from each variant into complete systems
- **Intelligent Synthesis**: Ensures completeness and consistency
- **Production-Ready**: Complete design system(s) with documentation
- **Matrix-Ready**: Provides style variants for style × layout matrix exploration in generate phase
## Execution Protocol
### Phase 1: Path Resolution & Variant Loading
```bash
# 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/*")
# Verify extraction output exists
style_cards_path = "{base_path}/style-extraction/style-cards.json"
VERIFY: exists(style_cards_path)
# Load style cards
style_cards = Read(style_cards_path)
total_variants = len(style_cards.style_cards)
```
### Phase 2: Variant Selection
```bash
# Determine how many variants to consolidate
IF --variants:
variants_count = {provided_count}
VALIDATE: 1 <= variants_count <= total_variants
ELSE:
variants_count = total_variants
# Select first N variants
selected_variants = style_cards.style_cards[0:variants_count]
VERIFY: selected_variants.length > 0
REPORT: "📦 Generating {variants_count} independent design systems"
```
### Phase 3: Load Design Context (Optional)
```bash
# Load brainstorming context if available
design_context = ""
IF exists({base_path}/.brainstorming/synthesis-specification.md):
design_context = Read(synthesis-specification.md)
ELSE IF exists({base_path}/.brainstorming/ui-designer/analysis.md):
design_context = Read(ui-designer/analysis.md)
# Load design space analysis from extraction phase
design_space_analysis = {}
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 {len(design_space_analysis.divergent_directions)} variant directions"
ELSE:
REPORT: "⚠️ No design space analysis found - will refine tokens from proposed_tokens only"
```
### Phase 4: Design System Synthesis (Agent Execution)
```bash
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 with clear task identifier
agent_task_prompt = """
[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 philosophy-driven refinement (NO MCP)
BASE_PATH: {base_path}
VARIANTS TO PROCESS: {variants_count}
## Variant Data
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 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)}
---
}
{IF design_context: DESIGN CONTEXT (from brainstorming): {design_context}}
{IF design_space_analysis:
## Design Space Analysis (for Philosophy-Driven Refinement)
{JSON.stringify(design_space_analysis, null, 2)}
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. **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: Load Design Philosophy (No MCP Calls)
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
ELSE:
Refine tokens based solely on variant's proposed_tokens and design_philosophy from style-cards.json
## Philosophy-Driven Refinement Strategy
**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
**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 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 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 based on its attributes
8. **Divergence Preservation**: Apply anti_keywords to prevent convergence with other variants
## Step 3: FILE WRITE OPERATIONS (CRITICAL)
**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": {
"brand": {"primary": "oklch(...)", "secondary": "oklch(...)", "accent": "oklch(...)"},
"surface": {"background": "oklch(...)", "elevated": "oklch(...)", "overlay": "oklch(...)"},
"semantic": {"success": "oklch(...)", "warning": "oklch(...)", "error": "oklch(...)", "info": "oklch(...)"},
"text": {"primary": "oklch(...)", "secondary": "oklch(...)", "tertiary": "oklch(...)", "inverse": "oklch(...)"},
"border": {"default": "oklch(...)", "strong": "oklch(...)", "subtle": "oklch(...)"}
},
"typography": {"font_family": {...}, "font_size": {...}, "font_weight": {...}, "line_height": {...}, "letter_spacing": {...}},
"spacing": {"0": "0", "1": "0.25rem", ..., "24": "6rem"},
"border_radius": {"none": "0", "sm": "0.25rem", ..., "full": "9999px"},
"shadows": {"sm": "...", "md": "...", "lg": "...", "xl": "..."},
"breakpoints": {"sm": "640px", ..., "2xl": "1536px"}
}
```
#### 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}
## Design Philosophy
{Expanded variant philosophy}
## Color System
### Brand Colors, Surface Colors, Semantic Colors, Text Colors, Border Colors
{List all with usage and accessibility notes}
## Typography
### Font Families, Type Scale, Usage Examples
{Complete typography documentation}
## Spacing System, Component Guidelines
{Spacing patterns and component token examples}
## Accessibility
- All text meets WCAG AA (4.5:1 minimum)
- UI components meet WCAG AA (3:1 minimum)
- Focus indicators are clearly visible
```
### Execution Checklist (Per Variant)
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
// 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
After completing all {variants_count} variants, report:
```
✅ 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)
```
## 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
"""
# 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"
```
### Phase 5: Verify Agent File Creation
```bash
REPORT: "📝 Verifying agent file creation for {variants_count} design systems..."
# 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-{N}"
VERIFY: exists(guide_path), "Style guide not created by agent for style-{N}"
# Optional: Validate JSON structure
TRY:
tokens = Read(tokens_path)
tokens_json = parse_json(tokens)
VALIDATE: tokens_json.colors exists, "Missing colors in design-tokens.json"
VALIDATE: tokens_json.typography exists, "Missing typography in design-tokens.json"
VALIDATE: tokens_json.spacing exists, "Missing spacing in design-tokens.json"
tokens_size = get_file_size(tokens_path)
guide_size = get_file_size(guide_path)
REPORT: " ✅ style-{N}/ verified ({tokens_size} KB tokens, {guide_size} KB guide)"
CATCH error:
ERROR: "Validation failed for style-{N}: {error}"
REPORT: " ⚠️ Files exist but validation failed - review agent output"
REPORT: "✅ All {variants_count} design systems verified"
```
**Output Structure**:
```
{base_path}/style-consolidation/
├── style-1/ (design-tokens.json, style-guide.md)
├── style-2/ (same structure)
└── style-N/ (same structure)
```
### Phase 6: Completion & Reporting
```javascript
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: "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"}
]});
```
**Completion Message**:
```
✅ Design system consolidation complete for session: {session_id}
{IF design_space_analysis:
🎨 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:
{FOR each variant: - {variant.name} ({variant.id})}
📂 Output: {base_path}/style-consolidation/
├── style-1/ (design-tokens.json, style-guide.md)
├── style-2/ (same structure)
└── style-{variants_count}/ (same structure)
Next: /workflow:ui-design:generate --session {session_id} --style-variants {variants_count} --targets "dashboard,auth" --layout-variants N
Note: When called from /workflow:ui-design:explore-auto, UI generation is triggered automatically.
Layout planning is now handled in the generate phase for each specific target.
```
## design-tokens.json Format
**Token structure** (all variants follow identical structure with different values):
```json
{
"colors": {
"brand": {"primary": "oklch(...)", "secondary": "oklch(...)", "accent": "oklch(...)"},
"surface": {"background": "oklch(...)", "elevated": "oklch(...)", "overlay": "oklch(...)"},
"semantic": {"success": "oklch(...)", "warning": "oklch(...)", "error": "oklch(...)", "info": "oklch(...)"},
"text": {"primary": "oklch(...)", "secondary": "oklch(...)", "tertiary": "oklch(...)", "inverse": "oklch(...)"},
"border": {"default": "oklch(...)", "strong": "oklch(...)", "subtle": "oklch(...)"}
},
"typography": {
"font_family": {"heading": "...", "body": "...", "mono": "..."},
"font_size": {"xs": "...", "sm": "...", "base": "...", "lg": "...", "xl": "...", "2xl": "...", "3xl": "...", "4xl": "..."},
"font_weight": {"normal": "400", "medium": "500", "semibold": "600", "bold": "700"},
"line_height": {"tight": "1.25", "normal": "1.5", "relaxed": "1.75"},
"letter_spacing": {"tight": "-0.025em", "normal": "0", "wide": "0.025em"}
},
"spacing": {"0": "0", "1": "0.25rem", ..., "24": "6rem"},
"border_radius": {"none": "0", "sm": "0.25rem", ..., "full": "9999px"},
"shadows": {"sm": "...", "md": "...", "lg": "...", "xl": "..."},
"breakpoints": {"sm": "640px", "md": "768px", "lg": "1024px", "xl": "1280px", "2xl": "1536px"}
}
```
**Requirements**: All colors in OKLCH format, complete token coverage, semantic naming
## Error Handling
- **No style cards found**: Report error, suggest running `/workflow:ui-design:extract` first
- **Invalid variant count**: List available count, auto-select all if called from auto workflow
- **Parsing errors**: Retry with stricter format instructions
- **Validation warnings**: Report but continue (non-blocking)
- **Missing categories**: Claude will fill gaps based on design philosophy
## Key Features
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 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 (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

@@ -0,0 +1,350 @@
---
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]
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"
- /workflow:ui-design:explore-auto --images "refs/*.png" --prompt "E-commerce: home, product, cart" --style-variants 3 --layout-variants 3
- /workflow:ui-design:explore-auto --session WFS-auth --images "refs/*.png"
- /workflow:ui-design:explore-auto --targets "navbar,hero" --target-type "component" --prompt "Compare 3 navigation bar designs" --style-variants 3 --layout-variants 2
- /workflow:ui-design:explore-auto --targets "card,form,button" --images "refs/*.png" --style-variants 2 --layout-variants 3
- /workflow:ui-design:explore-auto --targets "home,dashboard" --target-type "page"
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 [params]`
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 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** (unified):
- Generates `style_variants × layout_variants × targets` prototypes
- **Phase 1**: `style_variants` style options (extract)
- **Phase 2**: `style_variants` independent design systems (consolidate)
- **Phase 3**: Layout planning + UI generation (generate)
- Sub-phase 1: `targets × layout_variants` target-specific layout plans
- Sub-phase 2: `layout_variants × targets` HTML/CSS templates
- Sub-phase 3: `style_variants × layout_variants × targets` final prototypes
- Pages: Full-page layouts with complete structure
- Components: Isolated elements with minimal wrapper
- Mixed: Combination based on intelligent detection
**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",
"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"
}
```
### 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"
"Type: {target_type} | Source: {target_source}"
"Targets ({count}): {', '.join(validated_targets)}"
"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
```
**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)
# 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)
# 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)
```
### Phase 3: Matrix UI Generation (with Layout Planning)
```bash
targets_string = ",".join(inferred_target_list)
command = "/workflow:ui-design:generate --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)
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)
# 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)
# - compare.html (matrix view)
```
### Phase 4: Design System Integration
```bash
command = "/workflow:ui-design:update" + (--session ? " --session {session_id}" : "")
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)
```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 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..."}
]})
// ⚠️ 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
- **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 --prompt "Modern blog: home, article, author"
# Result: 27 prototypes (3×3×3 - inferred defaults)
```
### 2. Custom Matrix with Session
```bash
/workflow:ui-design:explore-auto --session WFS-ecommerce --images "refs/*.png" --style-variants 2 --layout-variants 2
# Result: 2×2×N prototypes (targets from synthesis)
```
### 3. Component Mode
```bash
/workflow:ui-design:explore-auto --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 --prompt "Create 4 styles with 2 layouts for dashboard and settings" --batch-plan
# Result: 16 prototypes (4×2×2) + auto-generated implementation tasks
```
### 5. Legacy Support
```bash
/workflow:ui-design:explore-auto --pages "home,dashboard,settings"
# Equivalent to: --targets "home,dashboard,settings" --target-type "page"
```
## Completion Output
```
✅ UI Design Explore-Auto Workflow Complete!
Run ID: {run_id} | Session: {session_id or "standalone"}
Type: {icon} {target_type} | Matrix: {s}×{l}×{n} = {total} prototypes
Phase 1: {s} style variants (extract)
Phase 2: {s} design systems (consolidate)
Phase 3: Layout planning + generation (generate)
- {n}×{l} target-specific layout plans
- {l}×{n} HTML/CSS templates
- {s}×{l}×{n} = {total} final prototypes
Phase 4: Brainstorming artifacts updated
[Phase 5: {n} implementation tasks created] # if --batch-plan
📂 {base_path}/
├── style-consolidation/ ({s} design systems)
├── prototypes/
│ ├── _templates/ ({n}×{l} layout JSON + {l}×{n} HTML/CSS)
│ └── ... ({total} final prototypes)
└── .run-metadata.json
🌐 Preview: {base_path}/prototypes/compare.html
- Interactive {s}×{l} matrix view
- Side-by-side comparison
- Target-specific layouts per prototype
{icon} Targets: {', '.join(targets)} (type: {target_type})
- Each target has {l} custom-designed layouts
- Layout plans stored as structured JSON
Next: [/workflow:execute] OR [Open compare.html → Select → /workflow:plan]
```

View File

@@ -0,0 +1,425 @@
---
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>]
examples:
- /workflow:ui-design:extract --images "design-refs/*.png" --variants 3
- /workflow:ui-design:extract --prompt "Modern minimalist blog, dark theme" --variants 3
- /workflow:ui-design:extract --session WFS-auth --images "refs/*.png" --prompt "Linear.app style" --variants 2
- /workflow:ui-design:extract --base-path ".workflow/WFS-auth/design-run-20250109-143022" --images "refs/*.png" --variants 3
- /workflow:ui-design:extract --prompt "Bold vibrant" --variants 1 # Single variant (default)
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*)
---
# Style Extraction Command
## Overview
Extract design style elements from reference images or text prompts using Claude's built-in analysis capabilities. Generates a single, comprehensive `style-cards.json` file containing multiple design variants with complete token proposals.
## Core Philosophy
- **Claude-Native**: 100% Claude-driven analysis, no external tools
- **Single Output**: Only `style-cards.json` with embedded token proposals
- **Sequential Execution**: Generate multiple style variants in one pass
- **Flexible Input**: Images, text prompts, or both (hybrid mode)
- **Reproducible**: Deterministic output structure
## Execution Protocol
### Phase 0: Parameter Detection & Validation
```bash
# Detect input source
IF --images AND --prompt: input_mode = "hybrid" # Text guides image analysis
ELSE IF --images: input_mode = "image"
ELSE IF --prompt: input_mode = "text"
ELSE: ERROR: "Must provide --images or --prompt"
# Determine base path (PRIORITY: --base-path > --session > standalone)
IF --base-path:
base_path = {provided_base_path}; session_mode = "integrated"
session_id = base_path matches ".workflow/WFS-*/design-*" ? extract_session_id(base_path) : "standalone"
ELSE:
run_id = "run-" + timestamp()
IF --session:
session_mode = "integrated"; session_id = {provided_session}
base_path = ".workflow/WFS-{session_id}/design-{run_id}/"
ELSE:
session_mode = "standalone"; base_path = ".workflow/.design/{run_id}/"
# Set variant count
variants_count = --variants OR 1; VALIDATE: 1 <= variants_count <= 5
```
### Phase 1: Input Loading & Validation
```bash
# Expand and validate inputs
IF input_mode IN ["image", "hybrid"]:
expanded_images = Glob({--images pattern}); VERIFY: expanded_images.length > 0
FOR each image: image_data[i] = Read({image_path})
IF input_mode IN ["text", "hybrid"]:
VALIDATE: --prompt is non-empty; prompt_guidance = {--prompt value}
CREATE: {base_path}/style-extraction/
```
### Phase 0.5: AI-Driven Design Space Divergence
```bash
# 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: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🎨 EXPLORE MODE: Analyzing design space (REQUIRED)"
REPORT: " → Generating {variants_count} maximally contrasting directions"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# Step 2: AI-driven divergent direction generation (REQUIRED)
divergence_prompt = """
Analyze user requirements and generate {variants_count} MAXIMALLY CONTRASTING design directions.
USER INPUT:
{IF prompt_guidance: Prompt: "{prompt_guidance}"}
{IF project_context: Project Context Summary: {extract_key_points(project_context, max_lines=10)}}
{IF images: Reference Images: {image_count} images will be analyzed in next phase}
DESIGN ATTRIBUTE SPACE (maximize contrast):
- Color Saturation: [monochrome, muted, moderate, vibrant, hypersaturated]
- Visual Weight: [minimal, light, balanced, bold, heavy]
- Formality: [playful, casual, professional, formal, luxury]
- Organic vs Geometric: [organic/fluid, soft, balanced, geometric, brutalist]
- Innovation: [timeless, modern, contemporary, trendy, experimental]
- Density: [spacious, airy, balanced, compact, dense]
TASK:
1. Identify design space center point from user requirements
2. Generate {variants_count} directions that:
- Are MAXIMALLY DISTANT from each other in attribute space
- Each occupies a distinct region/quadrant of the design spectrum
- Together provide diverse aesthetic options
- Are contextually appropriate for project type
- Have clear, memorable philosophical differences
3. For each direction, generate:
- Specific search keywords for MCP research (3-5 keywords)
- Anti-keywords to avoid (2-3 keywords)
- Clear rationale explaining contrast with other variants
OUTPUT FORMAT: Valid JSON only, no markdown:
{"design_space_center": {attributes}, "divergent_directions": [
{"id": "variant-1", "philosophy_name": "Brief name 2-3 words",
"design_attributes": {attribute_scores}, "search_keywords": [...],
"anti_keywords": [...], "rationale": "..."}
], "contrast_verification": {"min_pairwise_distance": "0.75", "strategy": "..."}}
RULES: Output ONLY valid JSON, maximize inter-variant distance, ensure each variant
occupies distinct aesthetic region, avoid overlapping attributes
"""
# Execute AI analysis (REQUIRED in explore mode)
divergent_directions = parse_json(Claude_Native_Analysis(divergence_prompt))
REPORT: "✅ Generated {variants_count} contrasting design directions:"
FOR direction IN divergent_directions.divergent_directions:
REPORT: " - {direction.philosophy_name}: {direction.rationale}"
design_space_analysis = divergent_directions
# 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 & Direct File Write
**Analysis Prompt Template**:
```
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:
{FOR each direction IN design_space_analysis.divergent_directions:
---
VARIANT: {direction.id} | PHILOSOPHY: {direction.philosophy_name}
DESIGN ATTRIBUTES: {direction.design_attributes}
SEARCH KEYWORDS: {direction.search_keywords}
ANTI-PATTERNS (avoid): {direction.anti_keywords}
RATIONALE: {direction.rationale}
---}
}
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},
"style_cards": [
{"id": "variant-1", "name": "Concise Style Name (2-3 words)", "description": "2-3 sentences",
"design_philosophy": "Core design principles",
"preview": {"primary": "oklch(...)", "background": "oklch(...)", "font_heading": "...", "border_radius": "..."},
"proposed_tokens": {
"colors": {"brand": {...}, "surface": {...}, "semantic": {...}, "text": {...}, "border": {...}},
"typography": {"font_family": {...}, "font_size": {...}, "font_weight": {...}, "line_height": {...}, "letter_spacing": {...}},
"spacing": {"0": "0", ..., "24": "6rem"},
"border_radius": {"none": "0", ..., "full": "9999px"},
"shadows": {"sm": "...", ..., "xl": "..."},
"breakpoints": {"sm": "640px", ..., "2xl": "1536px"}
}}
// Repeat for ALL {variants_count} variants
]}
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)
```
**Execution & File Write**:
```bash
# 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 3: Completion
```javascript
TodoWrite({todos: [
{content: "Validate inputs and create directories", status: "completed", activeForm: "Validating inputs"},
{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"}
]});
```
**Completion Message**:
```
✅ 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{variants_count > 1 ? "s" : ""}:
{FOR each card: - {card.name} ({card.id}) - {card.design_philosophy}}
📂 Outputs:
- {base_path}/style-extraction/style-cards.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:{extraction_mode == "imitate" ? "imitate" : "explore"}-auto, consolidation is triggered automatically.
```
## Output Structure
```
.workflow/WFS-{session}/design-{run_id}/style-extraction/
├── style-cards.json # Complete style variants with token proposals
└── 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 # Only in explore mode
```
### style-cards.json Format
**Schema Structure**:
```json
{
"extraction_metadata": {"session_id": "string", "input_mode": "image|text|hybrid",
"timestamp": "ISO 8601", "variants_count": "number"},
"style_cards": [
{
"id": "variant-{n}", "name": "Concise Style Name (2-3 words)",
"description": "2-3 sentence description of visual language and UX",
"design_philosophy": "Core design principles for this variant",
"preview": {"primary": "oklch(...)", "background": "oklch(...)",
"font_heading": "Font family, fallbacks", "border_radius": "value"},
"proposed_tokens": {
"colors": {
"brand": {"primary": "oklch(...)", "secondary": "oklch(...)", "accent": "oklch(...)"},
"surface": {"background": "oklch(...)", "elevated": "oklch(...)", "overlay": "oklch(...)"},
"semantic": {"success": "oklch(...)", "warning": "oklch(...)", "error": "oklch(...)", "info": "oklch(...)"},
"text": {"primary": "oklch(...)", "secondary": "oklch(...)", "tertiary": "oklch(...)", "inverse": "oklch(...)"},
"border": {"default": "oklch(...)", "strong": "oklch(...)", "subtle": "oklch(...)"}
},
"typography": {
"font_family": {"heading": "...", "body": "...", "mono": "..."},
"font_size": {"xs": "...", "sm": "...", "base": "...", "lg": "...", "xl": "...", "2xl": "...", "3xl": "...", "4xl": "..."},
"font_weight": {"normal": "400", "medium": "500", "semibold": "600", "bold": "700"},
"line_height": {"tight": "1.25", "normal": "1.5", "relaxed": "1.75"},
"letter_spacing": {"tight": "-0.025em", "normal": "0", "wide": "0.025em"}
},
"spacing": {"0": "0", "1": "0.25rem", "2": "0.5rem", "3": "0.75rem", "4": "1rem",
"5": "1.25rem", "6": "1.5rem", "8": "2rem", "10": "2.5rem", "12": "3rem",
"16": "4rem", "20": "5rem", "24": "6rem"},
"border_radius": {"none": "0", "sm": "0.25rem", "md": "0.5rem", "lg": "0.75rem",
"xl": "1rem", "full": "9999px"},
"shadows": {"sm": "0 1px 2px oklch(0.00 0.00 0 / 0.05)",
"md": "0 4px 6px oklch(0.00 0.00 0 / 0.07)",
"lg": "0 10px 15px oklch(0.00 0.00 0 / 0.10)",
"xl": "0 20px 25px oklch(0.00 0.00 0 / 0.15)"},
"breakpoints": {"sm": "640px", "md": "768px", "lg": "1024px", "xl": "1280px", "2xl": "1536px"}
}
}
// Repeat structure for variants_count total (variant-1, variant-2, ..., variant-n)
]
}
```
**Key Structural Requirements**:
- Each variant MUST have complete, independent token proposals (all categories present)
- All colors MUST use OKLCH format: `oklch(L C H / A)`
- Token keys MUST match exactly across all variants for consistency
- Variants differ in VALUES, not structure
- Production-ready: no placeholders or incomplete sections
## Error Handling
- **No images found**: Report glob pattern and suggest corrections
- **Invalid prompt**: Require non-empty string for text mode
- **Claude JSON parsing error**: Retry with stricter format instructions
- **Invalid session**: Create standalone session automatically in `.workflow/.scratchpad/`
- **Invalid variant count**: Clamp to 1-5 range and warn user
## Key Features
1. **🚀 AI-Driven Design Space Exploration** 🆕
- Phase 0.5: AI analyzes requirements and generates MAXIMALLY CONTRASTING design directions
- Uses 6-dimensional design attribute space (color saturation, visual weight, formality, organic/geometric, innovation, density)
- Ensures each variant occupies a distinct region of the design spectrum
- Generates search keywords and anti-patterns for each variant
- Provides contrast verification with minimum pairwise distance metrics
2. **🎯 Variant-Specific Design Directions** 🆕
- AI generates search keywords and anti-patterns for each variant
- Each variant has distinct design philosophy (e.g., "minimal brutalist" vs "bold vibrant")
- Philosophy-specific keywords guide synthesis
- Design space analysis saved for consolidation phase
- Trend research deferred to consolidation for better integration
3. **🔒 Maximum Contrast Guarantee**
- AI-driven divergence ensures variants are maximally distant in attribute space
- Each variant has distinct: philosophy, color saturation, visual weight, formality, etc.
- Explicit anti-patterns prevent variants from borrowing each other's characteristics
- Contrast verification built into design space analysis
4. **100% Claude-Native Analysis**
- No external tools (gemini-wrapper, codex, or MCP) - pure Claude
- Single-pass comprehensive analysis guided by design space analysis
- Fast, deterministic style synthesis without external dependencies
5. **Streamlined Output**
- Single file (`style-cards.json`) vs. multiple scattered files
- Eliminates `semantic_style_analysis.json`, `design-tokens.json`, `tailwind-tokens.js` clutter
- Each variant contains complete token proposals embedded
6. **Flexible Input Modes**
- Image-only: Analyze visual references through each variant's philosophical lens
- Text-only: Generate from descriptions with maximum divergence
- Hybrid: Text guides image analysis while maintaining variant independence
- All modes enhanced with AI-driven design space analysis
7. **Context-Aware & Dynamic**
- Extracts design keywords from user prompts (e.g., "minimalist", "Linear.app")
- Considers project type from brainstorming artifacts
- Dynamically generates design directions based on project context
- No hardcoded design philosophies - fully adaptive
8. **Production-Ready Token Proposals**
- Complete design system proposals per variant
- OKLCH color format for perceptual uniformity and accessibility
- Semantic naming conventions
- WCAG AA accessibility considerations built-in
- Variant-specific token sets (not generic)
9. **Workflow Integration**
- Integrated mode: Works within existing workflow sessions
- Standalone mode: Auto-creates session in scratchpad
- Context-aware: Can reference synthesis-specification.md or ui-designer/analysis.md
- Contrast metrics included in completion report
## Integration Points
- **Input**: Reference images (PNG, JPG, WebP) via glob patterns, or text prompts
- **Output**: `style-cards.json` for `/workflow:ui-design:consolidate`
- **Context**: Optional brainstorming artifacts (`synthesis-specification.md`, `ui-designer/analysis.md`)
- **Auto Integration**: Automatically triggered by `/workflow:ui-design:auto` workflow
- **Next Step**: `/workflow:ui-design:consolidate --session {session_id} --variants {count} [--layout-variants <count>]` (add `--keep-separate` for matrix mode)

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

@@ -0,0 +1,617 @@
---
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>]
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
allowed-tools: TodoWrite(*), Read(*), Write(*), Task(ui-design-agent), Bash(*)
---
# UI Generation Command (Matrix Mode)
**Executor**: → @ui-design-agent
**Parallel Generation**: Phase 2a → @ui-design-agent (L×T tasks)
## Overview
Generate production-ready UI prototypes (HTML/CSS) in `style × layout` matrix mode, strictly adhering to consolidated design tokens from separate style design systems. Supports both full-page layouts and isolated component generation.
## Core Philosophy
- **Unified Generation**: Single mode generating `style_variants × layout_variants × targets` prototypes
- **Target Types**: Supports pages (full layouts) and components (isolated UI elements)
- **Agent-Driven**: Uses `Task(ui-design-agent)` for parallel generation
- **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**: All templates use complete HTML5 documents; body content adapts (full page structure for pages, isolated component for components)
## 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 3; VALIDATE: 1 <= style_variants <= 5
layout_variants = --layout-variants OR 3; 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)
VERIFY: exists({base_path}/style-consolidation/style-{style_id}/style-guide.md)
# 6. Load requirements (if integrated mode)
IF --session: synthesis_spec = Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md)
```
### Phase 1.5: Target-Specific Layout Planning
```bash
REPORT: "📐 Planning {layout_variants} layout strategies for each target..."
CREATE: {base_path}/prototypes/_templates/
# For each target, plan its specific layouts
FOR target IN target_list:
REPORT: " Planning layouts for '{target}' ({target_type})..."
FOR layout_id IN range(1, layout_variants + 1):
Task(ui-design-agent): "
[TARGET_LAYOUT_PLANNING]
TARGET: {target} | TARGET_TYPE: {target_type} | LAYOUT_ID: {layout_id}/{layout_variants}
BASE_PATH: {base_path}
{IF --session: PROJECT_REQUIREMENTS: .workflow/WFS-{session}/.brainstorming/synthesis-specification.md}
## Task
Research {target} {target_type} layout variations → Select approach #{layout_id} → Generate layout plan JSON
## 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}
## Output
Write(\"{base_path}/prototypes/_templates/{target}-layout-{layout_id}.json\", layout_plan_json)
## JSON Structure
```json
{
"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": [...],
"accessibility_features": [...],
"research_references": [...]
}
```
## Requirements
- Research-informed, structurally DIFFERENT from other layout IDs
- Write file directly (not text output)
"
# Wait for all agent tasks to complete
REPORT: "⏳ Waiting for layout planning agents to complete..."
# Verify agent created layout JSON files
REPORT: "📝 Verifying agent file creation..."
FOR target IN target_list:
FOR layout_id IN range(1, layout_variants + 1):
layout_json_label = f"{target}-layout-{layout_id}.json"
json_path = f"{base_path}/prototypes/_templates/{layout_json_label}"
# Verify file exists
VERIFY: exists(json_path), f"Layout JSON not created by agent: {layout_json_label}"
# Validate JSON structure
TRY:
layout_json_content = Read(json_path)
layout_plan = JSON.parse(layout_json_content)
# Validate required fields
VALIDATE: layout_plan.id == f"layout-{layout_id}", f"Invalid layout ID in {layout_json_label}"
VALIDATE: layout_plan.target == target, f"Invalid target in {layout_json_label}"
VALIDATE: layout_plan.target_type == target_type, f"Invalid target_type in {layout_json_label}"
VALIDATE: layout_plan.name exists, f"Missing 'name' field in {layout_json_label}"
VALIDATE: layout_plan.structure exists, f"Missing 'structure' field in {layout_json_label}"
file_size = get_file_size(json_path)
REPORT: f" ✓ Verified: {layout_json_label} - {layout_plan.name} ({file_size} KB)"
CATCH error:
ERROR: f"Validation failed for {layout_json_label}: {error}"
REPORT: f" ⚠️ File exists but validation failed - review agent output"
REPORT: f"✅ Phase 1.5 complete: Verified {len(target_list) × layout_variants} target-specific layout files"
```
### Phase 1.6: Convert Design Tokens to CSS
```bash
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
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 input file exists
VERIFY: exists(tokens_json_path), f"Design tokens not found for style-{style_id}"
# 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):
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
**Strategy**: Two-layer generation reduces complexity from `O(S×L×T)` to `O(L×T)`, achieving **`S` times faster** performance.
- **Layer 1**: Generate `L × T` layout templates (HTML structure + structural CSS) by agent
- **Layer 2**: Instantiate `S × L × T` final prototypes via fast file operations
#### Phase 2a: Layout Template Generation
**Parallel Executor**: → @ui-design-agent
```bash
CREATE: {base_path}/prototypes/_templates/
CREATE: {base_path}/prototypes/
# Launch parallel template generation tasks → @ui-design-agent
# Total agent tasks: layout_variants × len(target_list)
FOR layout_id IN range(1, layout_variants + 1):
FOR target IN target_list:
# Read the target-specific layout plan
layout_json_path = f"{base_path}/prototypes/_templates/{target}-layout-{layout_id}.json"
layout_plan = Read(layout_json_path)
Task(ui-design-agent): "
[UI_LAYOUT_TEMPLATE_GENERATION]
🚨 TARGET INDEPENDENCE: Generate template for EXACTLY ONE target: '{target}' (standalone, reusable)
LAYOUT_ID: {layout_id} | TARGET: {target} | TARGET_TYPE: {target_type}
BASE_PATH: {base_path}
{IF --session: REQUIREMENTS: .workflow/WFS-{session}/.brainstorming/synthesis-specification.md}
## Layout Plan to Implement
**Path**: {layout_json_path}
**Plan**: {JSON.stringify(layout_plan, null, 2)}
## Task
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
## 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}}\">
## CSS Requirements - Token Reference
**1. Read tokens.css**
Read(\"{base_path}/style-consolidation/style-1/tokens.css\")
Extract all CSS variable names (pattern: lines with \" --\" in \":root {}\")
**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)}
**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)
**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`
**CSS Scope**: Structural layout only (Flexbox, Grid, positioning)
**Responsive**: Mobile-first approach
## 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)
Report completion with file paths. Write files directly (not text output).
"
REPORT: "⏳ Phase 2a: Waiting for agents to complete template generation..."
```
#### Phase 2a.5: Verify Agent Template File Creation
```bash
REPORT: "📝 Phase 2a.5: Verifying agent template file creation..."
# Verify each agent created template files
FOR layout_id IN range(1, layout_variants + 1):
FOR target IN target_list:
html_label = f"{target}-layout-{layout_id}.html"
css_label = f"{target}-layout-{layout_id}.css"
html_path = f"{base_path}/prototypes/_templates/{html_label}"
css_path = f"{base_path}/prototypes/_templates/{css_label}"
# Verify files exist
VERIFY: exists(html_path), f"HTML template not created by agent: {html_label}"
VERIFY: exists(css_path), f"CSS template not created by agent: {css_label}"
# Validate content
TRY:
html_content = Read(html_path)
css_content = Read(css_path)
# 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, f"Invalid HTML structure: {html_label}"
VALIDATE: "var(--" in css_content, f"Missing CSS variables: {css_label}"
html_size = get_file_size(html_path)
css_size = get_file_size(css_path)
REPORT: f" ✓ Verified: {html_label} ({html_size} KB) + {css_label} ({css_size} KB)"
CATCH error:
ERROR: f"Validation failed for {target}-layout-{layout_id}: {error}"
REPORT: f" ⚠️ Files exist but validation failed - review agent output"
REPORT: "✅ Phase 2a.5 complete: Verified {layout_variants * len(target_list) * 2} template files"
```
#### Phase 2b: Prototype Instantiation
```bash
REPORT: "🚀 Phase 2b: Instantiating prototypes from templates..."
# Verify tokens.css files exist (should be created in Phase 1.6)
FOR style_id IN range(1, style_variants + 1):
tokens_css_path = "{base_path}/style-consolidation/style-${style_id}/tokens.css"
VERIFY: exists(tokens_css_path), f"tokens.css missing for style-{style_id}. Phase 1.6 may have failed."
REPORT: " ✓ Verified {style_variants} tokens.css files exist"
# 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
Bash(~/.claude/scripts/ui-instantiate-prototypes.sh "{prototypes_dir}" --session-id "{session_id}" --mode "{target_type}")
# The script auto-detects: Targets, Style variants, Layout variants
# The script generates:
# 1. S × L × T HTML prototypes with CSS links
# 2. Implementation notes for each prototype
# 3. compare.html (interactive matrix)
# 4. index.html (navigation page)
# 5. PREVIEW.md (documentation)
REPORT: "✅ Phase 2b complete: Instantiated {style_variants * layout_variants * len(target_list)} final prototypes"
REPORT: " Mode: {target_type} | Performance: {style_variants}× faster than original approach"
```
### Phase 3: Verify Preview Files
```bash
REPORT: "🔍 Phase 3: Verifying preview files..."
expected_files = ["{base_path}/prototypes/compare.html", "{base_path}/prototypes/index.html", "{base_path}/prototypes/PREVIEW.md"]
all_present = true
FOR file_path IN expected_files:
IF exists(file_path): REPORT: " ✓ Found: {basename(file_path)}"
ELSE: REPORT: " ✗ Missing: {basename(file_path)}"; all_present = false
IF all_present: REPORT: "✅ Phase 3 complete: All preview files verified"
ELSE: WARN: "⚠️ Some preview files missing - script may have failed"
# Optional: Generate fallback design-tokens.css for reference
fallback_css_path = "{base_path}/prototypes/design-tokens.css"
IF NOT exists(fallback_css_path):
Write(fallback_css_path, "/* Auto-generated fallback CSS custom properties */\n/* See style-consolidation/style-{n}/tokens.css for actual values */")
REPORT: " ✓ Generated fallback design-tokens.css"
```
### Phase 3.5: Cross-Target Consistency Validation
**Condition**: Only executes if `len(target_list) > 1 AND target_type == "page"`
```bash
# Skip if single target or component mode
IF len(target_list) <= 1 OR target_type == "component": SKIP to Phase 4
# For multi-page workflows, validate cross-page consistency → @ui-design-agent
FOR style_id IN range(1, style_variants + 1):
FOR layout_id IN range(1, layout_variants + 1):
Task(@ui-design-agent): "
[CROSS_PAGE_CONSISTENCY_VALIDATION]
STYLE: {style_id} | LAYOUT: {layout_id} | TARGETS: {target_list} | TYPE: {target_type}
BASE_PATH: {base_path}
## Input
{base_path}/prototypes/{target}-style-{style_id}-layout-{layout_id}.html/css (all targets)
## Validate
1. Shared components (header/nav/footer)
2. Token usage (no hardcoded values)
3. Accessibility (ARIA, headings, landmarks)
4. Layout strategy consistency
## Output
Write({base_path}/prototypes/consistency-report-s{style_id}-l{layout_id}.md, validation_report)
Focus on shared elements. Page-specific variations acceptable.
"
# Aggregate consistency reports
Write({base_path}/prototypes/CONSISTENCY_SUMMARY.md):
# Multi-{target_type.capitalize()} Consistency Summary
## Validated Combinations
- Style Variants: {style_variants} | Layout Variants: {layout_variants}
- Total Reports: {style_variants * layout_variants}
## Report Files
{FOR s, l: - [Style {s} Layout {l}](./consistency-report-s{s}-l{l}.md)}
Run `/workflow:ui-design:update` once all issues are resolved.
```
### Phase 4: Completion
```javascript
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: `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"}
]});
```
**Completion Message**:
```
✅ Optimized Matrix UI generation complete!
Configuration:
- Style Variants: {style_variants}
- Layout Variants: {layout_variants} (target-specific planning)
- Target Type: {target_type_icon} {target_type}
- Targets: {target_list}
- Total Prototypes: {style_variants * layout_variants * len(target_list)}
- Layout Plans: {len(target_list) × layout_variants} target-specific JSON files generated
Performance Metrics:
- Layout Templates Generated: {layout_variants * len(target_list)} (Agent tasks)
- Prototypes Instantiated: {style_variants * layout_variants * len(target_list)} (script-based)
- Preview Files: compare.html, index.html, PREVIEW.md (auto-generated)
- Speed Improvement: {style_variants}× faster than previous approach
- Resource Efficiency: {100 * (1 - 1/style_variants)}% reduction in Agent calls
- Script: ui-instantiate-prototypes.sh v3.0 with auto-detection
Generated Structure:
📂 {base_path}/prototypes/
├── _templates/
│ ├── {target}-layout-{l}.json ({len(target_list) × layout_variants} layout plans)
│ ├── {target}-layout-{l}.html ({layout_variants * len(target_list)} HTML templates)
│ └── {target}-layout-{l}.css ({layout_variants * len(target_list)} CSS templates)
├── {target}-style-{s}-layout-{l}.html ({style_variants * layout_variants * len(target_list)} final prototypes)
├── {target}-style-{s}-layout-{l}-notes.md
├── compare.html (interactive matrix visualization)
└── index.html (quick navigation)
🌐 Interactive Preview:
1. Matrix View: Open compare.html (recommended)
2. Quick Index: Open index.html
3. Instructions: See PREVIEW.md
{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}
Note: When called from /workflow:ui-design:auto, design-update is triggered automatically.
**Dynamic Values**: target_type_icon: "📄" for page, "🧩" for component
```
## Output Structure
```
{base_path}/prototypes/
├── _templates/ # Target-specific layout plans and templates
│ ├── {target}-layout-1.json # Layout plan JSON (target-specific)
│ ├── {target}-layout-1.html # Style-agnostic HTML structure
│ ├── {target}-layout-1.css # Structural CSS with var() references
│ └── ... (T × L layout plans + templates)
├── compare.html # Interactive matrix visualization
├── index.html # Simple navigation page
├── PREVIEW.md # Preview instructions
├── design-tokens.css # CSS custom properties fallback
├── {target}-style-{s}-layout-{l}.html # Final prototypes (copied from templates)
├── {target}-style-{s}-layout-{l}-notes.md # Implementation notes
└── ... (S × L × T total final files)
{base_path}/style-consolidation/
├── style-1/ (design-tokens.json, tokens.css, style-guide.md)
├── style-2/ (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 templates directory**: Auto-created in Phase 1.5
- **Unsupported target type**: Error if target_type not in ["page", "component"]
- **Layout planning failures**: Check Phase 1.5 agent outputs for errors
### Phase-Specific Errors
- **Agent execution errors (Phase 2a)**: Report details, suggest retry with specific phase
- **Token conversion errors (Phase 2b)**: Check design-tokens.json format, validate JSON schema
- **Script execution errors (Phase 2b)**: Check script exists, permissions, output for specific errors
- **Preview generation errors (Phase 3)**: Check script completed, verify template exists, review Phase 2b output
### Recovery Strategies
- **Partial failure**: Script reports generated vs failed counts - review logs
- **Missing templates**: Indicates Phase 2a issue - regenerate templates
- **Auto-detection failures**: Use manual mode with explicit parameters
- **Permission errors**: Run `chmod +x ~/.claude/scripts/ui-instantiate-prototypes.sh`
## Quality Checks
After generation, ensure:
- [ ] All CSS values reference design token custom properties
- [ ] No hardcoded colors, spacing, or typography
- [ ] Semantic HTML structure with proper element hierarchy
- [ ] ARIA attributes present for accessibility
- [ ] Responsive design implemented with mobile-first approach
- [ ] File naming follows `{target}-style-{s}-layout-{l}` convention
- [ ] compare.html loads correctly with all prototypes
- [ ] Template files are reusable and style-agnostic
- [ ] All templates use complete HTML5 documents with appropriate body content (full structure for pages, isolated component for components)
## Key Features
1. **Target-Specific Layout Planning** 🆕 - Each target gets custom-designed layouts; Agent researches modern patterns using MCP tools; Layout plans saved as structured JSON
2. **Unified Target Generation** - Supports both pages (full layouts) and components (isolated elements); Backward compatible with legacy `--pages` parameter
3. **Optimized Template-Based Architecture** - Generates `L × T` reusable templates plus `L × T` layout plans; **`S` times faster**
4. **Three-Layer Generation Strategy** - Layer 1: Layout planning (target-specific); Layer 2: Template generation (implements plans); Layer 3: Fast instantiation; Agent autonomously uses MCP tools
5. **Script-Based Instantiation (v3.0)** - Uses `ui-instantiate-prototypes.sh` for efficient file operations; Auto-detection; Robust error handling; Integrated preview generation; Supports both page and component modes
6. **Consistent Cross-Style Layouts** - Same layout structure applied uniformly; Easier to compare styles; Simplified maintenance
7. **Dynamic Style Injection** - CSS custom properties enable runtime style switching; Each style variant has its own `tokens.css` file
8. **Interactive Visualization** - Full-featured compare.html; Matrix grid view with synchronized scrolling; Enhanced index.html with statistics; Comprehensive PREVIEW.md
9. **Production-Ready Output** - Semantic HTML5 and ARIA attributes (WCAG 2.2); Mobile-first responsive design; Token-driven styling; Implementation notes
## Integration Points
- **Input**: Per-style `design-tokens.json` from `/workflow:ui-design:consolidate`; `--targets` and `--layout-variants` parameters; Optional: `synthesis-specification.md` for target requirements; Target type specification
- **Output**: Target-specific `layout-{n}.json` files; Matrix HTML/CSS prototypes for `/workflow:ui-design:update`
- **Template**: `~/.claude/workflows/_template-compare-matrix.html` (global)
- **Auto Integration**: Automatically triggered by `/workflow:ui-design:explore-auto` workflow
- **Key Change**: Layout planning moved from consolidate to generate phase; Each target gets custom-designed layouts
- **Backward Compatibility**: Legacy `--pages` parameter continues to work

View File

@@ -0,0 +1,436 @@
---
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>]
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"
- /workflow:ui-design:imitate-auto --url "https://stripe.com" --session WFS-payment
- /workflow:ui-design:imitate-auto --images "refs/*.png" --targets "home"
- /workflow:ui-design:imitate-auto --url "https://example.com" --targets "navbar,hero" --target-type "component"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*)
---
# UI Design Imitate-Auto Workflow Command
## Overview & Philosophy
**Fast-track UI imitation workflow**: Replicates a single design style from reference source (URL or images), bypassing exploration and consolidation phases for maximum speed (~2-3× faster than explore-auto).
**Core Philosophy**:
- **Imitation over Exploration**: Focus on replicating specific design, not generating variants
- **Single Mode**: Always 1 style × 1 layout × N targets
- **Speed Optimized**: Bypasses `consolidate` step via direct token extraction
- **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) → 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
2. **No Multi-Variant**: Always 1 style × 1 layout × N targets
3. **Reference Required**: Must provide `--url` OR `--images`
4. **Auto-Continue**: Automatic phase progression without pausing
5. **Track Progress**: Update TodoWrite after each phase
## Parameter Requirements
**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 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 Parameters** (maintained for backward compatibility):
- `--pages "<list>"`: Alias for `--targets` with `--target-type page`
**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
### Phase 0: Simplified Initialization
```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/style-1,prototypes}")
# Metadata
Write({base_path}/.run-metadata.json): {
"run_id": "${run_id}", "session_id": "${session_id}", "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
"workflow": "ui-design:imitate-auto", "mode": "single_style_imitation",
"parameters": {"url": "${url_value}", "images": "${images_pattern}", "targets": "${target_list}", "prompt": "${prompt_text}"},
"status": "in_progress"
}
# Unified target inference (no interactive confirmation)
target_list = []; target_type = "page"; target_source = "none"
# Priority: --pages (legacy) → --targets → --prompt → default
IF --pages: target_list = split(--pages); target_type = "page"; target_source = "explicit_legacy"
ELSE IF --targets:
target_list = split(--targets)
target_type = --target-type ? --target-type : detect_target_type(target_list)
target_source = "explicit"
ELSE IF --prompt:
target_list = extract_targets_from_prompt(prompt_text) OR ["home"]
target_type = --target-type ? --target-type : detect_target_type(target_list)
target_source = "prompt_inferred"
ELSE:
target_list = ["home"]; target_type = "page"; target_source = "default"
# Validate and clean
validated_targets = [t.strip().lower().replace(" ", "-") for t in target_list if regex_match(t, r"^[a-z0-9][a-z0-9_-]*$")]
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"
# 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
```bash
IF --url:
screenshot_dir = "{base_path}/screenshots"; Bash(mkdir -p "{screenshot_dir}")
screenshot_success = false; screenshot_files = []
# Try Playwright → Chrome → Manual fallback
TRY: Bash(npx playwright screenshot "{url_value}" "{screenshot_dir}/full-page.png" --full-page --timeout 30000)
screenshot_files.append("{screenshot_dir}/full-page.png"); screenshot_success = true
REPORT: " ✅ Playwright screenshot captured"
CATCH: REPORT: " ⚠️ Playwright failed"
IF NOT screenshot_success:
TRY: Bash(google-chrome --headless --disable-gpu --screenshot="{screenshot_dir}/full-page.png" --window-size=1920,1080 "{url_value}")
screenshot_files.append("{screenshot_dir}/full-page.png"); screenshot_success = true
REPORT: " ✅ Chrome screenshot captured"
CATCH: REPORT: " ⚠️ Chrome failed"
# Manual upload fallback
IF NOT screenshot_success:
REPORT: "━━━ ⚠️ AUTOMATED SCREENSHOT FAILED ━━━"
REPORT: "Unable to capture: {url_value}"
REPORT: "Manual screenshot required:"
REPORT: " 1. Visit: {url_value} | 2. Take full-page screenshot | 3. Save to: {screenshot_dir}/"
REPORT: "Options: 'ready' (screenshot saved) | 'skip' (URL only) | 'abort' (cancel)"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
user_response = WAIT_FOR_USER_INPUT()
MATCH user_response:
"ready|done|ok"screenshot_files = Glob("{screenshot_dir}/*.{png,jpg,jpeg}");
IF screenshot_files: screenshot_success = true; REPORT: "✅ Manual screenshot detected"
ELSE: REPORT: "❌ No screenshot found, using URL analysis only"
"skip" → REPORT: "⏭️ Skipping screenshot, using URL analysis"
"abort" → ERROR: "Workflow aborted by user"; EXIT
_ → REPORT: "⚠️ Invalid input, proceeding with URL analysis"
# Store results
STORE: screenshot_mode = screenshot_success ? "with_screenshots" : "url_only", screenshot_paths = screenshot_files
REPORT: screenshot_success ? "✅ Screenshot capture complete: {len(screenshot_files)} image(s)" : " Proceeding with URL analysis only"
ELSE:
STORE: screenshot_mode = "manual_images", screenshot_paths = []
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
# Determine input based on screenshot capture
source_desc = screenshot_mode == "with_screenshots" ? "captured screenshots from {url_value}" :
screenshot_mode == "url_only" ? "URL analysis of {url_value}" : "user-provided images"
images_flag = screenshot_mode == "with_screenshots" ? "--images \"{base_path}/screenshots/*.{png,jpg,jpeg}\"" :
screenshot_mode == "manual_images" AND --images ? "--images \"{image_glob}\"" : ""
url_flag = screenshot_mode == "url_only" ? "--url \"{url_value}\"" : ""
# 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 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: imitate (high-fidelity)"
SlashCommand(command) # → Phase 2
```
### Phase 2: Fast Token Adaptation (Bypass Consolidate)
```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]
design_tokens = style_card.proposed_tokens
philosophy = style_card.design_philosophy
style_name = style_card.name
# 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
Write({base_path}/style-consolidation/style-1/style-guide.md):
# Design System: {style_name}
## Design Philosophy
{philosophy}
## Description
{style_card.description}
## Design Tokens
All tokens in `design-tokens.json` follow OKLCH color space.
**Key Colors**: Primary: {design_tokens.colors.brand.primary} | Background: {design_tokens.colors.surface.background} | Text: {design_tokens.colors.text.primary}
**Typography**: Heading: {design_tokens.typography.font_family.heading} | Body: {design_tokens.typography.font_family.body}
**Spacing Scale**: {design_tokens.spacing.keys().length} values
*Note: Generated in imitate mode for fast replication.*
REPORT: "✅ Tokens extracted and formatted | Style: {style_name} | Bypassed consolidate for {performance_gain}× speed"
```
### Phase 3: Single Prototype Generation
```bash
targets_string = ",".join(inferred_target_list)
type_emoji = "📄" IF target_type == "page" ELSE "🧩"
type_label = "page(s)" IF target_type == "page" ELSE "component(s)"
command = "/workflow:ui-design:generate --base-path \"{base_path}\" --targets \"{targets_string}\" --target-type \"{target_type}\" --style-variants 1 --layout-variants 1"
REPORT: "🚀 Phase 3: Generating {len(inferred_target_list)} {type_label}"
REPORT: " {type_emoji} Targets: {targets_string} | Mode: 1×1 (imitation-optimized)"
SlashCommand(command) # → Phase 4
# 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}") # → Complete
ELSE:
REPORT: " Standalone mode: Skipping integration | Prototypes at: {base_path}/prototypes/"
# → Complete (standalone)
```
## TodoWrite Pattern
```javascript
// Initialize
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"},
{"content": "Integrate design system", "status": "pending", "activeForm": "Integrating design"}
]})
// Update after each phase: Mark current completed, next in_progress
```
## Error Handling
- **No reference source**: Error if neither `--url` nor `--images` provided
- **Screenshot capture failure**: Tries Playwright → Chrome → Manual upload (user uploads, skips, or aborts); gracefully handles missing tools
- **Invalid URL/images**: Report error, suggest alternative input
- **Token extraction failure**: Fallback to minimal default design system
## Performance Comparison
| Aspect | explore-auto | imitate-auto |
|--------|--------------|--------------|
| **Purpose** | Design exploration | Design replication |
| **Input** | Optional URL/images | **Required** URL or images |
| **Variants** | 1-5 styles × 1-5 layouts | Always 1 × 1 |
| **Consolidate** | Full consolidation | **Bypassed** (direct tokens) |
| **Speed** | Baseline | **~2-3× faster** |
| **Output** | Matrix (S×L×T) | Direct (1×1×T) |
**Performance Benefits**: Skipped consolidate (~30-60s saved), single variant, direct token mapping, streamlined decisions
## Example Execution Flows
### Example 1: URL with Auto-Screenshot (Pages)
```bash
/workflow:ui-design:imitate-auto --url "https://linear.app" --targets "home,features,pricing"
# Flow: 0 (3 pages) → 0.5 (Playwright captures) → 1 (single style) → 2 (direct tokens ~2s vs ~45s) → 3 (3 prototypes) → 4
# Time: ~2-3 min (vs 5-7 min with explore-auto)
```
### Example 2: Images with Guidance (Page Mode)
```bash
/workflow:ui-design:imitate-auto --images "refs/dark-theme.png" --prompt "Focus on dark mode" --targets "dashboard"
# Flow: 0 → 0.5 (skip) → 1 → 2 → 3 → 4
# Output: dashboard-style-1-layout-1.html | Type: page (full-page layout)
```
### Example 3: Component Mode
```bash
/workflow:ui-design:imitate-auto --url "https://example.com" --targets "navbar,hero,card" --target-type "component"
# Flow: 0 → 0.5 → 1 → 2 → 3 → 4
# Output: navbar/hero/card-style-1-layout-1.html | Type: component (minimal wrapper)
```
### Example 4: URL with Manual Screenshot
```bash
/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
# If skip: 0.75 (MCP URL analysis) → 1 → 2 → 3 → 4
# If ready: 1 → 2 → 3 → 4
```
## Completion Output
```
✅ UI Design Imitation Complete!
Mode: Single Style Replication | Run ID: {run_id} | Session: {session_id or "standalone"} | Reference: {url OR images} | Type: {type_emoji} {type_label}
Phase 0 - Initialization: {target_count} {target_type}(s) prepared
Phase 0.5 - Screenshot Capture: {screenshot_status}
{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
Phase 4 - Design Integration: {integrated OR "Standalone mode"}
📂 Output: {base_path}/
├── style-extraction/style-cards.json (1 style card)
├── style-consolidation/style-1/ (design tokens)
└── prototypes/ ({target_count} HTML/CSS files)
🌐 Preview: {base_path}/prototypes/index.html
{type_emoji} Targets: {', '.join(inferred_target_list)} | Type: {target_type}
Context: {IF target_type == "page": "Full-page layouts" ELSE: "Isolated components with minimal wrapper"}
Performance:
- Design system: ~{time}s (vs ~{consolidate_time}s with consolidate)
- Total workflow: ~{total_time}s
- Speed improvement: ~{improvement}× faster than explore-auto
{IF session: Next: /workflow:plan to create implementation tasks | ELSE: Prototypes ready: {base_path}/prototypes/}
```

View File

@@ -0,0 +1,272 @@
---
name: update
description: Update brainstorming artifacts with finalized design system references
usage: /workflow:ui-design:update --session <session_id> [--selected-prototypes "<list>"]
examples:
- /workflow:ui-design:update --session WFS-auth
- /workflow:ui-design:update --session WFS-dashboard --selected-prototypes "dashboard-variant-1"
allowed-tools: Read(*), Write(*), Edit(*), TodoWrite(*), Glob(*), Bash(*)
---
# Design Update Command
## Overview
Synchronize finalized design system references to brainstorming artifacts, preparing them for `/workflow:plan` consumption. This command updates **references only** (via @ notation), not content duplication.
## Core Philosophy
- **Reference-Only Updates**: Use @ references, no content duplication
- **Main Claude Execution**: Direct updates by main Claude (no Agent handoff)
- **Synthesis Alignment**: Update synthesis-specification.md UI/UX Guidelines section
- **Plan-Ready Output**: Ensure design artifacts discoverable by task-generate
- **Minimal Reading**: Verify file existence, don't read design content
## Execution Protocol
### Phase 1: Session & Artifact Validation
```bash
# Validate session
CHECK: .workflow/.active-* marker files; VALIDATE: session_id matches active session
# Verify design artifacts in latest design run
latest_design = find_latest_path_matching(".workflow/WFS-{session}/design-*")
# Detect design system structure (unified vs separate)
IF exists({latest_design}/style-consolidation/design-tokens.json):
design_system_mode = "unified"; design_tokens_path = "style-consolidation/design-tokens.json"; style_guide_path = "style-consolidation/style-guide.md"
ELSE IF exists({latest_design}/style-consolidation/style-1/design-tokens.json):
design_system_mode = "separate"; design_tokens_path = "style-consolidation/style-1/design-tokens.json"; style_guide_path = "style-consolidation/style-1/style-guide.md"
ELSE:
ERROR: "No design tokens found. Run /workflow:ui-design:consolidate first"
VERIFY: {latest_design}/{design_tokens_path}, {latest_design}/{style_guide_path}, {latest_design}/prototypes/*.html
REPORT: "📋 Design system mode: {design_system_mode} | Tokens: {design_tokens_path}"
# Prototype selection
selected_list = --selected-prototypes ? parse_comma_separated(--selected-prototypes) : Glob({latest_design}/prototypes/*.html)
VALIDATE: Specified prototypes exist IF --selected-prototypes
REPORT: "Found {count} design artifacts, {prototype_count} prototypes"
```
### Phase 2: Load Target Artifacts Only
**What to Load**: Only the files we need to **update**, not the design files we're referencing.
```bash
# Load target brainstorming artifacts (files to be updated)
Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md)
IF exists(.workflow/WFS-{session}/.brainstorming/ui-designer/analysis.md): Read(analysis.md)
# Optional: Read prototype notes for descriptions (minimal context)
FOR each selected_prototype IN selected_list:
Read({latest_design}/prototypes/{selected_prototype}-notes.md) # Extract: layout_strategy, page_name only
# Note: Do NOT read design-tokens.json, style-guide.md, or prototype HTML. Only verify existence and generate @ references.
```
### Phase 3: Update Synthesis Specification
Update `.brainstorming/synthesis-specification.md` with design system references.
**Target Section**: `## UI/UX Guidelines`
**Content Template**:
```markdown
## UI/UX Guidelines
### Design System Reference
**Finalized Design Tokens**: @../design-{run_id}/{design_tokens_path}
**Style Guide**: @../design-{run_id}/{style_guide_path}
**Design System Mode**: {design_system_mode}
### Implementation Requirements
**Token Adherence**: All UI implementations MUST use design token CSS custom properties
**Accessibility**: WCAG AA compliance validated in design-tokens.json
**Responsive**: Mobile-first design using token-based breakpoints
**Component Patterns**: Follow patterns documented in style-guide.md
### Reference Prototypes
{FOR each selected_prototype:
- **{page_name}**: @../design-{run_id}/prototypes/{prototype}.html | Layout: {layout_strategy from notes}
}
### Design System Assets
```json
{"design_tokens": "design-{run_id}/{design_tokens_path}", "style_guide": "design-{run_id}/{style_guide_path}", "design_system_mode": "{design_system_mode}", "prototypes": [{FOR each: "design-{run_id}/prototypes/{prototype}.html"}]}
```
```
**Implementation**:
```bash
# Option 1: Edit existing section
Edit(file_path=".workflow/WFS-{session}/.brainstorming/synthesis-specification.md",
old_string="## UI/UX Guidelines\n[existing content]",
new_string="## UI/UX Guidelines\n\n[new design reference content]")
# Option 2: Append if section doesn't exist
IF section not found:
Edit(file_path="...", old_string="[end of document]", new_string="\n\n## UI/UX Guidelines\n\n[new design reference content]")
```
### Phase 4: Update UI Designer Style Guide
Create or update `.brainstorming/ui-designer/style-guide.md`:
```markdown
# UI Designer Style Guide
## Design System Integration
This style guide references the finalized design system from the design refinement phase.
**Design Tokens**: @../../design-{run_id}/{design_tokens_path}
**Style Guide**: @../../design-{run_id}/{style_guide_path}
**Design System Mode**: {design_system_mode}
## Implementation Guidelines
1. **Use CSS Custom Properties**: All styles reference design tokens
2. **Follow Semantic HTML**: Use HTML5 semantic elements
3. **Maintain Accessibility**: WCAG AA compliance required
4. **Responsive Design**: Mobile-first with token-based breakpoints
## Reference Prototypes
{FOR each selected_prototype:
- **{page_name}**: @../../design-{run_id}/prototypes/{prototype}.html
}
## Token System
For complete token definitions and usage examples, see:
- Design Tokens: @../../design-{run_id}/{design_tokens_path}
- Style Guide: @../../design-{run_id}/{style_guide_path}
---
*Auto-generated by /workflow:ui-design:update | Last updated: {timestamp}*
```
**Implementation**:
```bash
Write(file_path=".workflow/WFS-{session}/.brainstorming/ui-designer/style-guide.md",
content="[generated content with @ references]")
```
### Phase 5: Completion
```javascript
TodoWrite({todos: [
{content: "Validate session and design system artifacts", status: "completed", activeForm: "Validating artifacts"},
{content: "Load target brainstorming artifacts", status: "completed", activeForm: "Loading target files"},
{content: "Update synthesis-specification.md with design references", status: "completed", activeForm: "Updating synthesis spec"},
{content: "Create/update ui-designer/style-guide.md", status: "completed", activeForm: "Updating UI designer guide"}
]});
```
**Completion Message**:
```
✅ Design system references updated for session: WFS-{session}
Updated artifacts:
✓ synthesis-specification.md - UI/UX Guidelines section with @ references
✓ ui-designer/style-guide.md - Design system reference guide
Design system assets ready for /workflow:plan:
- design-tokens.json | style-guide.md | {prototype_count} reference prototypes
Next: /workflow:plan [--agent] "<task description>"
The plan phase will automatically discover and utilize the design system.
```
## Output Structure
**Updated Files**:
```
.workflow/WFS-{session}/.brainstorming/
├── synthesis-specification.md # Updated with UI/UX Guidelines section
└── ui-designer/
└── style-guide.md # New or updated design reference guide
```
**@ Reference Format** (synthesis-specification.md):
```
@../design-{run_id}/style-consolidation/design-tokens.json
@../design-{run_id}/style-consolidation/style-guide.md
@../design-{run_id}/prototypes/{prototype}.html
```
**@ Reference Format** (ui-designer/style-guide.md):
```
@../../design-{run_id}/style-consolidation/design-tokens.json
@../../design-{run_id}/style-consolidation/style-guide.md
@../../design-{run_id}/prototypes/{prototype}.html
```
## Integration with /workflow:plan
After this update, `/workflow:plan` will discover design assets through:
**Phase 3: Intelligent Analysis** (`/workflow:tools:concept-enhanced`)
- Reads synthesis-specification.md → Discovers @ references → Includes design system context in ANALYSIS_RESULTS.md
**Phase 4: Task Generation** (`/workflow:tools:task-generate`)
- Reads ANALYSIS_RESULTS.md → Discovers design assets → Includes design system paths in task JSON files
**Example Task JSON** (generated by task-generate):
```json
{
"task_id": "IMPL-001",
"context": {
"design_system": {
"tokens": "design-{run_id}/style-consolidation/design-tokens.json",
"style_guide": "design-{run_id}/style-consolidation/style-guide.md",
"prototypes": ["design-{run_id}/prototypes/dashboard-variant-1.html"]
}
}
}
```
## Error Handling
- **Missing design artifacts**: Error with message "Run /workflow:ui-design:consolidate and /workflow:ui-design:generate first"
- **synthesis-specification.md not found**: Warning, create minimal version with just UI/UX Guidelines
- **ui-designer/ directory missing**: Create directory and file
- **Edit conflicts**: Preserve existing content, append or replace only UI/UX Guidelines section
- **Invalid prototype names**: Skip invalid entries, continue with valid ones
## Validation Checks
After update, verify:
- [ ] synthesis-specification.md contains UI/UX Guidelines section
- [ ] UI/UX Guidelines include @ references (not content duplication)
- [ ] ui-designer/style-guide.md created or updated
- [ ] All @ referenced files exist and are accessible
- [ ] @ reference paths are relative and correct
## Key Features
1. **Reference-Only Updates**: Uses @ notation for file references, no content duplication, lightweight and maintainable
2. **Main Claude Direct Execution**: No Agent handoff (preserves context), simple reference generation, reliable path resolution
3. **Plan-Ready Output**: `/workflow:plan` Phase 3 can discover design system, task generation includes design asset paths, clear integration points
4. **Minimal Reading**: Only reads target files to update, verifies design file existence (no content reading), optional prototype notes for descriptions
5. **Flexible Prototype Selection**: Auto-select all prototypes (default), manual selection via --selected-prototypes parameter, validates existence
## Integration Points
- **Input**: Design system artifacts from `/workflow:ui-design:consolidate` and `/workflow:ui-design:generate`
- **Output**: Updated synthesis-specification.md, ui-designer/style-guide.md with @ references
- **Next Phase**: `/workflow:plan` discovers and utilizes design system through @ references
- **Auto Integration**: Automatically triggered by `/workflow:ui-design:auto` workflow
## Why Main Claude Execution?
This command is executed directly by main Claude (not delegated to an Agent) because:
1. **Simple Reference Generation**: Only generating file paths, not complex synthesis
2. **Context Preservation**: Main Claude has full session and conversation context
3. **Minimal Transformation**: Primarily updating references, not analyzing content
4. **Path Resolution**: Requires precise relative path calculation
5. **Edit Operations**: Better error recovery for Edit conflicts
6. **Synthesis Pattern**: Follows same direct-execution pattern as other reference updates
This ensures reliable, lightweight integration without Agent handoff overhead.

View File

@@ -0,0 +1,225 @@
#!/bin/bash
# Convert design-tokens.json to tokens.css with Google Fonts import and global font rules
# Usage: cat design-tokens.json | ./convert_tokens_to_css.sh > tokens.css
# Or: ./convert_tokens_to_css.sh < design-tokens.json > tokens.css
# Read JSON from stdin
json_input=$(cat)
# Extract metadata for header comment
style_name=$(echo "$json_input" | jq -r '.meta.name // "Unknown Style"' 2>/dev/null || echo "Design Tokens")
# Generate header
cat <<EOF
/* ========================================
Design Tokens: ${style_name}
Auto-generated from design-tokens.json
======================================== */
EOF
# ========================================
# Google Fonts Import Generation
# ========================================
# Extract font families and generate Google Fonts import URL
fonts=$(echo "$json_input" | jq -r '
.typography.font_family | to_entries[] | .value
' 2>/dev/null | sed "s/'//g" | cut -d',' -f1 | sort -u)
# Build Google Fonts URL
google_fonts_url="https://fonts.googleapis.com/css2?"
font_params=""
while IFS= read -r font; do
# Skip system fonts and empty lines
if [[ -z "$font" ]] || [[ "$font" =~ ^(system-ui|sans-serif|serif|monospace|cursive|fantasy)$ ]]; then
continue
fi
# Special handling for common web fonts with weights
case "$font" in
"Comic Neue")
font_params+="family=Comic+Neue:wght@300;400;700&"
;;
"Patrick Hand"|"Caveat"|"Dancing Script"|"Architects Daughter"|"Indie Flower"|"Shadows Into Light"|"Permanent Marker")
# URL-encode font name and add common weights
encoded_font=$(echo "$font" | sed 's/ /+/g')
font_params+="family=${encoded_font}:wght@400;700&"
;;
"Segoe Print"|"Bradley Hand"|"Chilanka")
# These are system fonts, skip
;;
*)
# Generic font: add with default weights
encoded_font=$(echo "$font" | sed 's/ /+/g')
font_params+="family=${encoded_font}:wght@400;500;600;700&"
;;
esac
done <<< "$fonts"
# Generate @import if we have fonts
if [[ -n "$font_params" ]]; then
# Remove trailing &
font_params="${font_params%&}"
echo "/* Import Web Fonts */"
echo "@import url('${google_fonts_url}${font_params}&display=swap');"
echo ""
fi
# ========================================
# CSS Custom Properties Generation
# ========================================
echo ":root {"
# Colors - Brand
echo " /* Colors - Brand */"
echo "$json_input" | jq -r '
.colors.brand | to_entries[] |
" --color-brand-\(.key): \(.value);"
' 2>/dev/null
echo ""
# Colors - Surface
echo " /* Colors - Surface */"
echo "$json_input" | jq -r '
.colors.surface | to_entries[] |
" --color-surface-\(.key): \(.value);"
' 2>/dev/null
echo ""
# Colors - Semantic
echo " /* Colors - Semantic */"
echo "$json_input" | jq -r '
.colors.semantic | to_entries[] |
" --color-semantic-\(.key): \(.value);"
' 2>/dev/null
echo ""
# Colors - Text
echo " /* Colors - Text */"
echo "$json_input" | jq -r '
.colors.text | to_entries[] |
" --color-text-\(.key): \(.value);"
' 2>/dev/null
echo ""
# Colors - Border
echo " /* Colors - Border */"
echo "$json_input" | jq -r '
.colors.border | to_entries[] |
" --color-border-\(.key): \(.value);"
' 2>/dev/null
echo ""
# Typography - Font Family
echo " /* Typography - Font Family */"
echo "$json_input" | jq -r '
.typography.font_family | to_entries[] |
" --font-family-\(.key): \(.value);"
' 2>/dev/null
echo ""
# Typography - Font Size
echo " /* Typography - Font Size */"
echo "$json_input" | jq -r '
.typography.font_size | to_entries[] |
" --font-size-\(.key): \(.value);"
' 2>/dev/null
echo ""
# Typography - Font Weight
echo " /* Typography - Font Weight */"
echo "$json_input" | jq -r '
.typography.font_weight | to_entries[] |
" --font-weight-\(.key): \(.value);"
' 2>/dev/null
echo ""
# Typography - Line Height
echo " /* Typography - Line Height */"
echo "$json_input" | jq -r '
.typography.line_height | to_entries[] |
" --line-height-\(.key): \(.value);"
' 2>/dev/null
echo ""
# Typography - Letter Spacing
echo " /* Typography - Letter Spacing */"
echo "$json_input" | jq -r '
.typography.letter_spacing | to_entries[] |
" --letter-spacing-\(.key): \(.value);"
' 2>/dev/null
echo ""
# Spacing
echo " /* Spacing */"
echo "$json_input" | jq -r '
.spacing | to_entries[] |
" --spacing-\(.key): \(.value);"
' 2>/dev/null
echo ""
# Border Radius
echo " /* Border Radius */"
echo "$json_input" | jq -r '
.border_radius | to_entries[] |
" --border-radius-\(.key): \(.value);"
' 2>/dev/null
echo ""
# Shadows
echo " /* Shadows */"
echo "$json_input" | jq -r '
.shadows | to_entries[] |
" --shadow-\(.key): \(.value);"
' 2>/dev/null
echo ""
# Breakpoints
echo " /* Breakpoints */"
echo "$json_input" | jq -r '
.breakpoints | to_entries[] |
" --breakpoint-\(.key): \(.value);"
' 2>/dev/null
echo "}"
echo ""
# ========================================
# Global Font Application
# ========================================
echo "/* ========================================"
echo " Global Font Application"
echo " ======================================== */"
echo ""
echo "body {"
echo " font-family: var(--font-family-body);"
echo " font-size: var(--font-size-base);"
echo " line-height: var(--line-height-normal);"
echo " color: var(--color-text-primary);"
echo " background-color: var(--color-surface-background);"
echo "}"
echo ""
echo "h1, h2, h3, h4, h5, h6, legend {"
echo " font-family: var(--font-family-heading);"
echo "}"
echo ""
echo "/* Reset default margins for better control */"
echo "* {"
echo " margin: 0;"
echo " padding: 0;"
echo " box-sizing: border-box;"
echo "}"

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

@@ -0,0 +1,811 @@
#!/bin/bash
# UI Prototype Instantiation Script with Preview Generation (v3.0 - Auto-detect)
# Purpose: Generate S × L × P final prototypes from templates + interactive preview files
# Usage:
# Simple: ui-instantiate-prototypes.sh <prototypes_dir>
# Full: ui-instantiate-prototypes.sh <base_path> <pages> <style_variants> <layout_variants> [options]
# Use safer error handling
set -o pipefail
# ============================================================================
# Helper Functions
# ============================================================================
log_info() {
echo "$1"
}
log_success() {
echo "$1"
}
log_error() {
echo "$1"
}
log_warning() {
echo "⚠️ $1"
}
# Auto-detect pages from templates directory
auto_detect_pages() {
local templates_dir="$1/_templates"
if [ ! -d "$templates_dir" ]; then
log_error "Templates directory not found: $templates_dir"
return 1
fi
# Find unique page names from template files (e.g., login-layout-1.html -> login)
local pages=$(find "$templates_dir" -name "*-layout-*.html" -type f | \
sed 's|.*/||' | \
sed 's|-layout-[0-9]*\.html||' | \
sort -u | \
tr '\n' ',' | \
sed 's/,$//')
echo "$pages"
}
# Auto-detect style variants count
auto_detect_style_variants() {
local base_path="$1"
local style_dir="$base_path/../style-consolidation"
if [ ! -d "$style_dir" ]; then
log_warning "Style consolidation directory not found: $style_dir"
echo "3" # Default
return
fi
# Count style-* directories
local count=$(find "$style_dir" -maxdepth 1 -type d -name "style-*" | wc -l)
if [ "$count" -eq 0 ]; then
echo "3" # Default
else
echo "$count"
fi
}
# Auto-detect layout variants count
auto_detect_layout_variants() {
local templates_dir="$1/_templates"
if [ ! -d "$templates_dir" ]; then
echo "3" # Default
return
fi
# Find the first page and count its layouts
local first_page=$(find "$templates_dir" -name "*-layout-1.html" -type f | head -1 | sed 's|.*/||' | sed 's|-layout-1\.html||')
if [ -z "$first_page" ]; then
echo "3" # Default
return
fi
# Count layout files for this page
local count=$(find "$templates_dir" -name "${first_page}-layout-*.html" -type f | wc -l)
if [ "$count" -eq 0 ]; then
echo "3" # Default
else
echo "$count"
fi
}
# ============================================================================
# Parse Arguments
# ============================================================================
show_usage() {
cat <<'EOF'
Usage:
Simple (auto-detect): ui-instantiate-prototypes.sh <prototypes_dir> [options]
Full: ui-instantiate-prototypes.sh <base_path> <pages> <style_variants> <layout_variants> [options]
Simple Mode (Recommended):
prototypes_dir Path to prototypes directory (auto-detects everything)
Full Mode:
base_path Base path to prototypes directory
pages Comma-separated list of pages/components
style_variants Number of style variants (1-5)
layout_variants Number of layout variants (1-5)
Options:
--run-id <id> Run ID (default: auto-generated)
--session-id <id> Session ID (default: standalone)
--mode <page|component> Exploration mode (default: page)
--template <path> Path to compare.html template (default: ~/.claude/workflows/_template-compare-matrix.html)
--no-preview Skip preview file generation
--help Show this help message
Examples:
# Simple usage (auto-detect everything)
ui-instantiate-prototypes.sh .design/prototypes
# With options
ui-instantiate-prototypes.sh .design/prototypes --session-id WFS-auth
# Full manual mode
ui-instantiate-prototypes.sh .design/prototypes "login,dashboard" 3 3 --session-id WFS-auth
EOF
}
# Default values
BASE_PATH=""
PAGES=""
STYLE_VARIANTS=""
LAYOUT_VARIANTS=""
RUN_ID="run-$(date +%Y%m%d-%H%M%S)"
SESSION_ID="standalone"
MODE="page"
TEMPLATE_PATH="$HOME/.claude/workflows/_template-compare-matrix.html"
GENERATE_PREVIEW=true
AUTO_DETECT=false
# Parse arguments
if [ $# -lt 1 ]; then
log_error "Missing required arguments"
show_usage
exit 1
fi
# Check if using simple mode (only 1 positional arg before options)
if [ $# -eq 1 ] || [[ "$2" == --* ]]; then
# Simple mode - auto-detect
AUTO_DETECT=true
BASE_PATH="$1"
shift 1
else
# Full mode - manual parameters
if [ $# -lt 4 ]; then
log_error "Full mode requires 4 positional arguments"
show_usage
exit 1
fi
BASE_PATH="$1"
PAGES="$2"
STYLE_VARIANTS="$3"
LAYOUT_VARIANTS="$4"
shift 4
fi
# Parse optional arguments
while [[ $# -gt 0 ]]; do
case $1 in
--run-id)
RUN_ID="$2"
shift 2
;;
--session-id)
SESSION_ID="$2"
shift 2
;;
--mode)
MODE="$2"
shift 2
;;
--template)
TEMPLATE_PATH="$2"
shift 2
;;
--no-preview)
GENERATE_PREVIEW=false
shift
;;
--help)
show_usage
exit 0
;;
*)
log_error "Unknown option: $1"
show_usage
exit 1
;;
esac
done
# ============================================================================
# Auto-detection (if enabled)
# ============================================================================
if [ "$AUTO_DETECT" = true ]; then
log_info "🔍 Auto-detecting configuration from directory..."
# Detect pages
PAGES=$(auto_detect_pages "$BASE_PATH")
if [ -z "$PAGES" ]; then
log_error "Could not auto-detect pages from templates"
exit 1
fi
log_info " Pages: $PAGES"
# Detect style variants
STYLE_VARIANTS=$(auto_detect_style_variants "$BASE_PATH")
log_info " Style variants: $STYLE_VARIANTS"
# Detect layout variants
LAYOUT_VARIANTS=$(auto_detect_layout_variants "$BASE_PATH")
log_info " Layout variants: $LAYOUT_VARIANTS"
echo ""
fi
# ============================================================================
# Validation
# ============================================================================
# Validate base path
if [ ! -d "$BASE_PATH" ]; then
log_error "Base path not found: $BASE_PATH"
exit 1
fi
# Validate style and layout variants
if [ "$STYLE_VARIANTS" -lt 1 ] || [ "$STYLE_VARIANTS" -gt 5 ]; then
log_error "Style variants must be between 1 and 5 (got: $STYLE_VARIANTS)"
exit 1
fi
if [ "$LAYOUT_VARIANTS" -lt 1 ] || [ "$LAYOUT_VARIANTS" -gt 5 ]; then
log_error "Layout variants must be between 1 and 5 (got: $LAYOUT_VARIANTS)"
exit 1
fi
# Validate STYLE_VARIANTS against actual style directories
if [ "$STYLE_VARIANTS" -gt 0 ]; then
style_dir="$BASE_PATH/../style-consolidation"
if [ ! -d "$style_dir" ]; then
log_error "Style consolidation directory not found: $style_dir"
log_info "Run /workflow:ui-design:consolidate first"
exit 1
fi
actual_styles=$(find "$style_dir" -maxdepth 1 -type d -name "style-*" 2>/dev/null | wc -l)
if [ "$actual_styles" -eq 0 ]; then
log_error "No style directories found in: $style_dir"
log_info "Run /workflow:ui-design:consolidate first to generate style design systems"
exit 1
fi
if [ "$STYLE_VARIANTS" -gt "$actual_styles" ]; then
log_warning "Requested $STYLE_VARIANTS style variants, but only found $actual_styles directories"
log_info "Available style directories:"
find "$style_dir" -maxdepth 1 -type d -name "style-*" 2>/dev/null | sed 's|.*/||' | sort
log_info "Auto-correcting to $actual_styles style variants"
STYLE_VARIANTS=$actual_styles
fi
fi
# Parse pages into array
IFS=',' read -ra PAGE_ARRAY <<< "$PAGES"
if [ ${#PAGE_ARRAY[@]} -eq 0 ]; then
log_error "No pages found"
exit 1
fi
# ============================================================================
# Header Output
# ============================================================================
echo "========================================="
echo "UI Prototype Instantiation & Preview"
if [ "$AUTO_DETECT" = true ]; then
echo "(Auto-detected configuration)"
fi
echo "========================================="
echo "Base Path: $BASE_PATH"
echo "Mode: $MODE"
echo "Pages/Components: $PAGES"
echo "Style Variants: $STYLE_VARIANTS"
echo "Layout Variants: $LAYOUT_VARIANTS"
echo "Run ID: $RUN_ID"
echo "Session ID: $SESSION_ID"
echo "========================================="
echo ""
# Change to base path
cd "$BASE_PATH" || exit 1
# ============================================================================
# Phase 1: Instantiate Prototypes
# ============================================================================
log_info "🚀 Phase 1: Instantiating prototypes from templates..."
echo ""
total_generated=0
total_failed=0
for page in "${PAGE_ARRAY[@]}"; do
# Trim whitespace
page=$(echo "$page" | xargs)
log_info "Processing page/component: $page"
for s in $(seq 1 "$STYLE_VARIANTS"); do
for l in $(seq 1 "$LAYOUT_VARIANTS"); do
# Define file paths
TEMPLATE_HTML="_templates/${page}-layout-${l}.html"
STRUCTURAL_CSS="_templates/${page}-layout-${l}.css"
TOKEN_CSS="../style-consolidation/style-${s}/tokens.css"
OUTPUT_HTML="${page}-style-${s}-layout-${l}.html"
# Copy template and replace placeholders
if [ -f "$TEMPLATE_HTML" ]; then
cp "$TEMPLATE_HTML" "$OUTPUT_HTML" || {
log_error "Failed to copy template: $TEMPLATE_HTML"
((total_failed++))
continue
}
# Replace CSS placeholders (Windows-compatible sed syntax)
sed -i "s|{{STRUCTURAL_CSS}}|${STRUCTURAL_CSS}|g" "$OUTPUT_HTML" || true
sed -i "s|{{TOKEN_CSS}}|${TOKEN_CSS}|g" "$OUTPUT_HTML" || true
log_success "Created: $OUTPUT_HTML"
((total_generated++))
# Create implementation notes (simplified)
NOTES_FILE="${page}-style-${s}-layout-${l}-notes.md"
# Generate notes with simple heredoc
cat > "$NOTES_FILE" <<NOTESEOF
# Implementation Notes: ${page}-style-${s}-layout-${l}
## Generation Details
- **Template**: ${TEMPLATE_HTML}
- **Structural CSS**: ${STRUCTURAL_CSS}
- **Style Tokens**: ${TOKEN_CSS}
- **Layout Strategy**: Layout ${l}
- **Style Variant**: Style ${s}
- **Mode**: ${MODE}
## Template Reuse
This prototype was generated from a shared layout template to ensure consistency
across all style variants. The HTML structure is identical for all ${page}-layout-${l}
prototypes, with only the design tokens (colors, fonts, spacing) varying.
## Design System Reference
Refer to \`../style-consolidation/style-${s}/style-guide.md\` for:
- Design philosophy
- Token usage guidelines
- Component patterns
- Accessibility requirements
## Customization
To modify this prototype:
1. Edit the layout template: \`${TEMPLATE_HTML}\` (affects all styles)
2. Edit the structural CSS: \`${STRUCTURAL_CSS}\` (affects all styles)
3. Edit design tokens: \`${TOKEN_CSS}\` (affects only this style variant)
## Run Information
- **Run ID**: ${RUN_ID}
- **Session ID**: ${SESSION_ID}
- **Generated**: $(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u +%Y-%m-%d)
NOTESEOF
else
log_error "Template not found: $TEMPLATE_HTML"
((total_failed++))
fi
done
done
done
echo ""
log_success "Phase 1 complete: Generated ${total_generated} prototypes"
if [ $total_failed -gt 0 ]; then
log_warning "Failed: ${total_failed} prototypes"
fi
echo ""
# ============================================================================
# Phase 2: Generate Preview Files (if enabled)
# ============================================================================
if [ "$GENERATE_PREVIEW" = false ]; then
log_info "⏭️ Skipping preview generation (--no-preview flag)"
exit 0
fi
log_info "🎨 Phase 2: Generating preview files..."
echo ""
# ============================================================================
# 2a. Generate compare.html from template
# ============================================================================
if [ ! -f "$TEMPLATE_PATH" ]; then
log_warning "Template not found: $TEMPLATE_PATH"
log_info " Skipping compare.html generation"
else
log_info "📄 Generating compare.html from template..."
# Convert page array to JSON format
PAGES_JSON="["
for i in "${!PAGE_ARRAY[@]}"; do
page=$(echo "${PAGE_ARRAY[$i]}" | xargs)
PAGES_JSON+="\"$page\""
if [ $i -lt $((${#PAGE_ARRAY[@]} - 1)) ]; then
PAGES_JSON+=", "
fi
done
PAGES_JSON+="]"
TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u +%Y-%m-%d)
# Read template and replace placeholders
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}}|${STYLE_VARIANTS}|g" | \
sed "s|{{layout_variants}}|${LAYOUT_VARIANTS}|g" | \
sed "s|{{pages_json}}|${PAGES_JSON}|g" \
> compare.html
log_success "Generated: compare.html"
fi
# ============================================================================
# 2b. Generate index.html
# ============================================================================
log_info "📄 Generating index.html..."
# Calculate total prototypes
TOTAL_PROTOTYPES=$((STYLE_VARIANTS * LAYOUT_VARIANTS * ${#PAGE_ARRAY[@]}))
# Generate index.html with simple heredoc
cat > index.html <<'INDEXEOF'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UI Prototypes - __MODE__ Mode - __RUN_ID__</title>
<style>
body {
font-family: system-ui, -apple-system, sans-serif;
max-width: 900px;
margin: 2rem auto;
padding: 0 2rem;
background: #f9fafb;
}
.header {
background: white;
padding: 2rem;
border-radius: 0.75rem;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
margin-bottom: 2rem;
}
h1 {
color: #2563eb;
margin-bottom: 0.5rem;
font-size: 2rem;
}
.meta {
color: #6b7280;
font-size: 0.875rem;
margin-top: 0.5rem;
}
.info {
background: #f3f4f6;
padding: 1.5rem;
border-radius: 0.5rem;
margin: 1.5rem 0;
border-left: 4px solid #2563eb;
}
.cta {
display: inline-block;
background: #2563eb;
color: white;
padding: 1rem 2rem;
border-radius: 0.5rem;
text-decoration: none;
font-weight: 600;
margin: 1rem 0;
transition: background 0.2s;
}
.cta:hover {
background: #1d4ed8;
}
.stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 1rem;
margin: 1.5rem 0;
}
.stat {
background: white;
border: 1px solid #e5e7eb;
padding: 1.5rem;
border-radius: 0.5rem;
text-align: center;
box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}
.stat-value {
font-size: 2.5rem;
font-weight: bold;
color: #2563eb;
margin-bottom: 0.25rem;
}
.stat-label {
color: #6b7280;
font-size: 0.875rem;
}
.section {
background: white;
padding: 2rem;
border-radius: 0.75rem;
margin-bottom: 2rem;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
h2 {
color: #1f2937;
margin-bottom: 1rem;
font-size: 1.5rem;
}
ul {
line-height: 1.8;
color: #374151;
}
.pages-list {
list-style: none;
padding: 0;
}
.pages-list li {
background: #f9fafb;
padding: 0.75rem 1rem;
margin: 0.5rem 0;
border-radius: 0.375rem;
border-left: 3px solid #2563eb;
}
.badge {
display: inline-block;
background: #dbeafe;
color: #1e40af;
padding: 0.25rem 0.75rem;
border-radius: 0.25rem;
font-size: 0.75rem;
font-weight: 600;
margin-left: 0.5rem;
}
</style>
</head>
<body>
<div class="header">
<h1>🎨 UI Prototype __MODE__ Mode</h1>
<div class="meta">
<strong>Run ID:</strong> __RUN_ID__ |
<strong>Session:</strong> __SESSION_ID__ |
<strong>Generated:</strong> __TIMESTAMP__
</div>
</div>
<div class="info">
<p><strong>Matrix Configuration:</strong> __STYLE_VARIANTS__ styles × __LAYOUT_VARIANTS__ layouts × __PAGE_COUNT__ __MODE__s</p>
<p><strong>Total Prototypes:</strong> __TOTAL_PROTOTYPES__ interactive HTML files</p>
</div>
<a href="compare.html" class="cta">🔍 Open Interactive Matrix Comparison →</a>
<div class="stats">
<div class="stat">
<div class="stat-value">__STYLE_VARIANTS__</div>
<div class="stat-label">Style Variants</div>
</div>
<div class="stat">
<div class="stat-value">__LAYOUT_VARIANTS__</div>
<div class="stat-label">Layout Options</div>
</div>
<div class="stat">
<div class="stat-value">__PAGE_COUNT__</div>
<div class="stat-label">__MODE__s</div>
</div>
<div class="stat">
<div class="stat-value">__TOTAL_PROTOTYPES__</div>
<div class="stat-label">Total Prototypes</div>
</div>
</div>
<div class="section">
<h2>🌟 Features</h2>
<ul>
<li><strong>Interactive Matrix View:</strong> __STYLE_VARIANTS__×__LAYOUT_VARIANTS__ grid with synchronized scrolling</li>
<li><strong>Flexible Zoom:</strong> 25%, 50%, 75%, 100% viewport scaling</li>
<li><strong>Fullscreen Mode:</strong> Detailed view for individual prototypes</li>
<li><strong>Selection System:</strong> Mark favorites with export to JSON</li>
<li><strong>__MODE__ Switcher:</strong> Compare different __MODE__s side-by-side</li>
<li><strong>Persistent State:</strong> Selections saved in localStorage</li>
</ul>
</div>
<div class="section">
<h2>📄 Generated __MODE__s</h2>
<ul class="pages-list">
__PAGES_LIST__
</ul>
</div>
<div class="section">
<h2>📚 Next Steps</h2>
<ol>
<li>Open <code>compare.html</code> to explore all variants in matrix view</li>
<li>Use zoom and sync scroll controls to compare details</li>
<li>Select your preferred style×layout combinations</li>
<li>Export selections as JSON for implementation planning</li>
<li>Review implementation notes in <code>*-notes.md</code> files</li>
</ol>
</div>
</body>
</html>
INDEXEOF
# Build pages list HTML
PAGES_LIST_HTML=""
for page in "${PAGE_ARRAY[@]}"; do
page=$(echo "$page" | xargs)
VARIANT_COUNT=$((STYLE_VARIANTS * LAYOUT_VARIANTS))
PAGES_LIST_HTML+=" <li>\n"
PAGES_LIST_HTML+=" <strong>${page}</strong>\n"
PAGES_LIST_HTML+=" <span class=\"badge\">${STYLE_VARIANTS}×${LAYOUT_VARIANTS} = ${VARIANT_COUNT} variants</span>\n"
PAGES_LIST_HTML+=" </li>\n"
done
# Replace all placeholders in index.html
MODE_UPPER=$(echo "$MODE" | awk '{print toupper(substr($0,1,1)) tolower(substr($0,2))}')
sed -i "s|__RUN_ID__|${RUN_ID}|g" index.html
sed -i "s|__SESSION_ID__|${SESSION_ID}|g" index.html
sed -i "s|__TIMESTAMP__|${TIMESTAMP}|g" index.html
sed -i "s|__MODE__|${MODE_UPPER}|g" index.html
sed -i "s|__STYLE_VARIANTS__|${STYLE_VARIANTS}|g" index.html
sed -i "s|__LAYOUT_VARIANTS__|${LAYOUT_VARIANTS}|g" index.html
sed -i "s|__PAGE_COUNT__|${#PAGE_ARRAY[@]}|g" index.html
sed -i "s|__TOTAL_PROTOTYPES__|${TOTAL_PROTOTYPES}|g" index.html
sed -i "s|__PAGES_LIST__|${PAGES_LIST_HTML}|g" index.html
log_success "Generated: index.html"
# ============================================================================
# 2c. Generate PREVIEW.md
# ============================================================================
log_info "📄 Generating PREVIEW.md..."
cat > PREVIEW.md <<PREVIEWEOF
# UI Prototype Preview Guide
## Quick Start
1. Open \`index.html\` for overview and navigation
2. Open \`compare.html\` for interactive matrix comparison
3. Use browser developer tools to inspect responsive behavior
## Configuration
- **Exploration Mode:** ${MODE_UPPER}
- **Run ID:** ${RUN_ID}
- **Session ID:** ${SESSION_ID}
- **Style Variants:** ${STYLE_VARIANTS}
- **Layout Options:** ${LAYOUT_VARIANTS}
- **${MODE_UPPER}s:** ${PAGES}
- **Total Prototypes:** ${TOTAL_PROTOTYPES}
- **Generated:** ${TIMESTAMP}
## File Naming Convention
\`\`\`
{${MODE}}-style-{s}-layout-{l}.html
\`\`\`
**Example:** \`dashboard-style-1-layout-2.html\`
- ${MODE_UPPER}: dashboard
- Style: Design system 1
- Layout: Layout variant 2
## Interactive Features (compare.html)
### Matrix View
- **Grid Layout:** ${STYLE_VARIANTS}×${LAYOUT_VARIANTS} table with all prototypes visible
- **Synchronized Scroll:** All iframes scroll together (toggle with button)
- **Zoom Controls:** Adjust viewport scale (25%, 50%, 75%, 100%)
- **${MODE_UPPER} Selector:** Switch between different ${MODE}s instantly
### Prototype Actions
- **⭐ Selection:** Click star icon to mark favorites
- **⛶ Fullscreen:** View prototype in fullscreen overlay
- **↗ New Tab:** Open prototype in dedicated browser tab
### Selection Export
1. Select preferred prototypes using star icons
2. Click "Export Selection" button
3. Downloads JSON file: \`selection-${RUN_ID}.json\`
4. Use exported file for implementation planning
## Design System References
Each prototype references a specific style design system:
PREVIEWEOF
# Add style references
for s in $(seq 1 "$STYLE_VARIANTS"); do
cat >> PREVIEW.md <<STYLEEOF
### Style ${s}
- **Tokens:** \`../style-consolidation/style-${s}/design-tokens.json\`
- **CSS Variables:** \`../style-consolidation/style-${s}/tokens.css\`
- **Style Guide:** \`../style-consolidation/style-${s}/style-guide.md\`
STYLEEOF
done
cat >> PREVIEW.md <<'FOOTEREOF'
## Responsive Testing
All prototypes are mobile-first responsive. Test at these breakpoints:
- **Mobile:** 375px - 767px
- **Tablet:** 768px - 1023px
- **Desktop:** 1024px+
Use browser DevTools responsive mode for testing.
## Accessibility Features
- Semantic HTML5 structure
- ARIA attributes for screen readers
- Keyboard navigation support
- Proper heading hierarchy
- Focus indicators
## Next Steps
1. **Review:** Open `compare.html` and explore all variants
2. **Select:** Mark preferred prototypes using star icons
3. **Export:** Download selection JSON for implementation
4. **Implement:** Use `/workflow:ui-design:update` to integrate selected designs
5. **Plan:** Run `/workflow:plan` to generate implementation tasks
---
**Generated by:** `ui-instantiate-prototypes.sh`
**Version:** 3.0 (auto-detect mode)
FOOTEREOF
log_success "Generated: PREVIEW.md"
# ============================================================================
# Completion Summary
# ============================================================================
echo ""
echo "========================================="
echo "✅ Generation Complete!"
echo "========================================="
echo ""
echo "📊 Summary:"
echo " Prototypes: ${total_generated} generated"
if [ $total_failed -gt 0 ]; then
echo " Failed: ${total_failed}"
fi
echo " Preview Files: compare.html, index.html, PREVIEW.md"
echo " Matrix: ${STYLE_VARIANTS}×${LAYOUT_VARIANTS} (${#PAGE_ARRAY[@]} ${MODE}s)"
echo " Total Files: ${TOTAL_PROTOTYPES} prototypes + preview files"
echo ""
echo "🌐 Next Steps:"
echo " 1. Open: ${BASE_PATH}/index.html"
echo " 2. Explore: ${BASE_PATH}/compare.html"
echo " 3. Review: ${BASE_PATH}/PREVIEW.md"
echo ""
echo "Performance: Template-based approach with ${STYLE_VARIANTS}× speedup"
echo "========================================="

View File

@@ -0,0 +1,692 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UI Design Matrix Comparison - {{run_id}}</title>
<style>
:root {
--color-primary: #2563eb;
--color-bg: #f9fafb;
--color-surface: #ffffff;
--color-border: #e5e7eb;
--color-text: #1f2937;
--color-text-secondary: #6b7280;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background: var(--color-bg);
color: var(--color-text);
line-height: 1.6;
}
.container {
max-width: 1600px;
margin: 0 auto;
padding: 2rem;
}
header {
background: var(--color-surface);
padding: 1.5rem 2rem;
border-radius: 0.5rem;
margin-bottom: 2rem;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
h1 {
color: var(--color-primary);
font-size: 1.875rem;
margin-bottom: 0.5rem;
}
.meta {
color: var(--color-text-secondary);
font-size: 0.875rem;
}
.controls {
background: var(--color-surface);
padding: 1.5rem;
border-radius: 0.5rem;
margin-bottom: 2rem;
display: flex;
gap: 1.5rem;
align-items: center;
flex-wrap: wrap;
}
.control-group {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
label {
font-size: 0.875rem;
font-weight: 500;
color: var(--color-text-secondary);
}
select, button {
padding: 0.5rem 1rem;
border: 1px solid var(--color-border);
border-radius: 0.375rem;
font-size: 0.875rem;
background: white;
cursor: pointer;
}
select:focus, button:focus {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
button {
background: var(--color-primary);
color: white;
border: none;
font-weight: 500;
transition: background 0.2s;
}
button:hover {
background: #1d4ed8;
}
.matrix-container {
background: var(--color-surface);
border-radius: 0.5rem;
overflow: hidden;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.matrix-table {
width: 100%;
border-collapse: collapse;
}
.matrix-table th,
.matrix-table td {
border: 1px solid var(--color-border);
padding: 0.75rem;
text-align: center;
}
.matrix-table th {
background: #f3f4f6;
font-weight: 600;
color: var(--color-text);
}
.matrix-table thead th {
background: var(--color-primary);
color: white;
}
.matrix-table tbody th {
background: #f9fafb;
font-weight: 600;
}
.prototype-cell {
position: relative;
padding: 0;
height: 400px;
vertical-align: top;
}
.prototype-wrapper {
height: 100%;
display: flex;
flex-direction: column;
}
.prototype-header {
padding: 0.5rem;
background: #f9fafb;
border-bottom: 1px solid var(--color-border);
display: flex;
justify-content: space-between;
align-items: center;
flex-shrink: 0;
}
.prototype-title {
font-size: 0.75rem;
font-weight: 500;
color: var(--color-text-secondary);
}
.prototype-actions {
display: flex;
gap: 0.25rem;
}
.icon-btn {
width: 24px;
height: 24px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
background: transparent;
border: none;
color: var(--color-text-secondary);
cursor: pointer;
border-radius: 0.25rem;
}
.icon-btn:hover {
background: #e5e7eb;
color: var(--color-text);
}
.icon-btn.selected {
background: var(--color-primary);
color: white;
}
.prototype-iframe-container {
flex: 1;
position: relative;
overflow: hidden;
}
.prototype-iframe {
width: 100%;
height: 100%;
border: none;
transform-origin: top left;
}
.zoom-info {
position: absolute;
bottom: 0.5rem;
right: 0.5rem;
background: rgba(0,0,0,0.7);
color: white;
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
font-size: 0.75rem;
pointer-events: none;
}
.tabs {
display: flex;
gap: 0.5rem;
margin-bottom: 1rem;
border-bottom: 2px solid var(--color-border);
}
.tab {
padding: 0.75rem 1.5rem;
background: transparent;
border: none;
border-bottom: 2px solid transparent;
cursor: pointer;
font-weight: 500;
color: var(--color-text-secondary);
margin-bottom: -2px;
}
.tab.active {
color: var(--color-primary);
border-bottom-color: var(--color-primary);
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.fullscreen-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.95);
z-index: 1000;
padding: 2rem;
}
.fullscreen-overlay.active {
display: flex;
flex-direction: column;
}
.fullscreen-header {
color: white;
margin-bottom: 1rem;
display: flex;
justify-content: space-between;
align-items: center;
}
.fullscreen-iframe {
flex: 1;
border: none;
background: white;
border-radius: 0.5rem;
}
.close-btn {
background: rgba(255,255,255,0.2);
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 0.375rem;
cursor: pointer;
}
.close-btn:hover {
background: rgba(255,255,255,0.3);
}
.selection-summary {
background: #fef3c7;
border-left: 4px solid #f59e0b;
padding: 1rem;
margin-bottom: 2rem;
border-radius: 0.375rem;
}
.selection-summary h3 {
color: #92400e;
margin-bottom: 0.5rem;
font-size: 1rem;
}
.selection-list {
list-style: none;
color: #78350f;
font-size: 0.875rem;
}
.selection-list li {
padding: 0.25rem 0;
}
@media (max-width: 1200px) {
.prototype-cell {
height: 300px;
}
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>🎨 UI Design Matrix Comparison</h1>
<div class="meta">
<strong>Run ID:</strong> {{run_id}} |
<strong>Session:</strong> {{session_id}} |
<strong>Generated:</strong> {{timestamp}}
</div>
</header>
<div class="controls">
<div class="control-group">
<label for="page-select">Page:</label>
<select id="page-select">
<!-- Populated by JavaScript -->
</select>
</div>
<div class="control-group">
<label for="zoom-level">Zoom:</label>
<select id="zoom-level">
<option value="0.25">25%</option>
<option value="0.5">50%</option>
<option value="0.75">75%</option>
<option value="1" selected>100%</option>
</select>
</div>
<div class="control-group">
<label>&nbsp;</label>
<button id="sync-scroll-toggle">🔗 Sync Scroll: ON</button>
</div>
<div class="control-group">
<label>&nbsp;</label>
<button id="export-selection">📥 Export Selection</button>
</div>
</div>
<div id="selection-summary" class="selection-summary" style="display:none">
<h3>Selected Prototypes (<span id="selection-count">0</span>)</h3>
<ul id="selection-list" class="selection-list"></ul>
</div>
<div class="tabs">
<button class="tab active" data-tab="matrix">Matrix View</button>
<button class="tab" data-tab="comparison">Side-by-Side</button>
<button class="tab" data-tab="runs">Compare Runs</button>
</div>
<div class="tab-content active" data-content="matrix">
<div class="matrix-container">
<table class="matrix-table">
<thead>
<tr>
<th>Style ↓ / Layout →</th>
<th>Layout 1</th>
<th>Layout 2</th>
<th>Layout 3</th>
</tr>
</thead>
<tbody id="matrix-body">
<!-- Populated by JavaScript -->
</tbody>
</table>
</div>
</div>
<div class="tab-content" data-content="comparison">
<p>Select two prototypes from the matrix to compare side-by-side.</p>
<div id="comparison-view"></div>
</div>
<div class="tab-content" data-content="runs">
<p>Compare the same prototype across different runs.</p>
<div id="runs-comparison"></div>
</div>
</div>
<div id="fullscreen-overlay" class="fullscreen-overlay">
<div class="fullscreen-header">
<h2 id="fullscreen-title"></h2>
<button class="close-btn" onclick="closeFullscreen()">✕ Close</button>
</div>
<iframe id="fullscreen-iframe" class="fullscreen-iframe"></iframe>
</div>
<script>
// Configuration - Replace with actual values during generation
const CONFIG = {
runId: "{{run_id}}",
sessionId: "{{session_id}}",
styleVariants: {{style_variants}}, // e.g., 3
layoutVariants: {{layout_variants}}, // e.g., 3
pages: {{pages_json}}, // e.g., ["dashboard", "auth"]
basePath: "." // Relative path to prototypes
};
// State
let state = {
currentPage: CONFIG.pages[0],
zoomLevel: 1,
syncScroll: true,
selected: new Set(),
fullscreenSrc: null
};
// Initialize
document.addEventListener('DOMContentLoaded', () => {
populatePageSelect();
renderMatrix();
setupEventListeners();
loadSelectionFromStorage();
});
function populatePageSelect() {
const select = document.getElementById('page-select');
CONFIG.pages.forEach(page => {
const option = document.createElement('option');
option.value = page;
option.textContent = capitalize(page);
select.appendChild(option);
});
}
function renderMatrix() {
const tbody = document.getElementById('matrix-body');
tbody.innerHTML = '';
for (let s = 1; s <= CONFIG.styleVariants; s++) {
const row = document.createElement('tr');
// Style header cell
const headerCell = document.createElement('th');
headerCell.textContent = `Style ${s}`;
row.appendChild(headerCell);
// Prototype cells for each layout
for (let l = 1; l <= CONFIG.layoutVariants; l++) {
const cell = document.createElement('td');
cell.className = 'prototype-cell';
const filename = `${state.currentPage}-style-${s}-layout-${l}.html`;
const id = `${state.currentPage}-s${s}-l${l}`;
cell.innerHTML = `
<div class="prototype-wrapper">
<div class="prototype-header">
<span class="prototype-title">S${s}L${l}</span>
<div class="prototype-actions">
<button class="icon-btn select-btn" data-id="${id}" title="Select">
${state.selected.has(id) ? '★' : '☆'}
</button>
<button class="icon-btn" onclick="openFullscreen('${filename}', 'Style ${s} Layout ${l}')" title="Fullscreen">
</button>
<button class="icon-btn" onclick="openInNewTab('${filename}')" title="Open in new tab">
</button>
</div>
</div>
<div class="prototype-iframe-container">
<iframe
class="prototype-iframe"
src="${filename}"
data-cell="s${s}-l${l}"
style="transform: scale(${state.zoomLevel});"
></iframe>
<div class="zoom-info">${Math.round(state.zoomLevel * 100)}%</div>
</div>
</div>
`;
row.appendChild(cell);
}
tbody.appendChild(row);
}
// Re-attach selection event listeners
document.querySelectorAll('.select-btn').forEach(btn => {
btn.addEventListener('click', (e) => toggleSelection(e.target.dataset.id, e.target));
});
// Setup scroll sync
if (state.syncScroll) {
setupScrollSync();
}
}
function setupScrollSync() {
const iframes = document.querySelectorAll('.prototype-iframe');
let isScrolling = false;
iframes.forEach(iframe => {
iframe.addEventListener('load', () => {
const iframeWindow = iframe.contentWindow;
iframe.contentDocument.addEventListener('scroll', (e) => {
if (!state.syncScroll || isScrolling) return;
isScrolling = true;
const scrollTop = iframe.contentDocument.documentElement.scrollTop;
const scrollLeft = iframe.contentDocument.documentElement.scrollLeft;
iframes.forEach(otherIframe => {
if (otherIframe !== iframe && otherIframe.contentDocument) {
otherIframe.contentDocument.documentElement.scrollTop = scrollTop;
otherIframe.contentDocument.documentElement.scrollLeft = scrollLeft;
}
});
setTimeout(() => { isScrolling = false; }, 50);
});
});
});
}
function setupEventListeners() {
// Page selector
document.getElementById('page-select').addEventListener('change', (e) => {
state.currentPage = e.target.value;
renderMatrix();
});
// Zoom level
document.getElementById('zoom-level').addEventListener('change', (e) => {
state.zoomLevel = parseFloat(e.target.value);
renderMatrix();
});
// Sync scroll toggle
document.getElementById('sync-scroll-toggle').addEventListener('click', (e) => {
state.syncScroll = !state.syncScroll;
e.target.textContent = `🔗 Sync Scroll: ${state.syncScroll ? 'ON' : 'OFF'}`;
if (state.syncScroll) setupScrollSync();
});
// Export selection
document.getElementById('export-selection').addEventListener('click', exportSelection);
// Tab switching
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', (e) => {
const tabName = e.target.dataset.tab;
switchTab(tabName);
});
});
}
function toggleSelection(id, btn) {
if (state.selected.has(id)) {
state.selected.delete(id);
btn.textContent = '☆';
btn.classList.remove('selected');
} else {
state.selected.add(id);
btn.textContent = '★';
btn.classList.add('selected');
}
updateSelectionSummary();
saveSelectionToStorage();
}
function updateSelectionSummary() {
const summary = document.getElementById('selection-summary');
const count = document.getElementById('selection-count');
const list = document.getElementById('selection-list');
count.textContent = state.selected.size;
if (state.selected.size > 0) {
summary.style.display = 'block';
list.innerHTML = Array.from(state.selected)
.map(id => `<li>${id}</li>`)
.join('');
} else {
summary.style.display = 'none';
}
}
function saveSelectionToStorage() {
localStorage.setItem(`selection-${CONFIG.runId}`, JSON.stringify(Array.from(state.selected)));
}
function loadSelectionFromStorage() {
const stored = localStorage.getItem(`selection-${CONFIG.runId}`);
if (stored) {
state.selected = new Set(JSON.parse(stored));
updateSelectionSummary();
}
}
function exportSelection() {
const report = {
runId: CONFIG.runId,
sessionId: CONFIG.sessionId,
timestamp: new Date().toISOString(),
selections: Array.from(state.selected).map(id => ({
id,
file: `${id.replace(/-s(\d+)-l(\d+)/, '-style-$1-layout-$2')}.html`
}))
};
const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `selection-${CONFIG.runId}.json`;
a.click();
URL.revokeObjectURL(url);
alert(`Exported ${state.selected.size} selections to selection-${CONFIG.runId}.json`);
}
function openFullscreen(src, title) {
const overlay = document.getElementById('fullscreen-overlay');
const iframe = document.getElementById('fullscreen-iframe');
const titleEl = document.getElementById('fullscreen-title');
iframe.src = src;
titleEl.textContent = title;
overlay.classList.add('active');
state.fullscreenSrc = src;
}
function closeFullscreen() {
const overlay = document.getElementById('fullscreen-overlay');
const iframe = document.getElementById('fullscreen-iframe');
overlay.classList.remove('active');
iframe.src = '';
state.fullscreenSrc = null;
}
function openInNewTab(src) {
window.open(src, '_blank');
}
function switchTab(tabName) {
document.querySelectorAll('.tab').forEach(tab => {
tab.classList.toggle('active', tab.dataset.tab === tabName);
});
document.querySelectorAll('.tab-content').forEach(content => {
content.classList.toggle('active', content.dataset.content === tabName);
});
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
// Close fullscreen on ESC key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && state.fullscreenSrc) {
closeFullscreen();
}
});
</script>
</body>
</html>

View File

@@ -276,6 +276,22 @@ All workflows use the same file structure definition regardless of complexity. *
│ ├── execute-*-[timestamp].md # Ad-hoc implementation logs
│ └── codex-execute-*-[timestamp].md # Multi-stage execution logs
├── [.design/] # Standalone UI design outputs (created when needed)
│ └── run-[timestamp]/ # Timestamped design runs without session
│ ├── style-extraction/ # Style analysis results
│ ├── style-consolidation/ # Design system tokens (per-style)
│ │ ├── style-1/ # design-tokens.json, style-guide.md
│ │ └── style-N/
│ ├── prototypes/ # Generated HTML/CSS prototypes
│ │ ├── _templates/ # Target-specific layout plans and templates
│ │ │ ├── {target}-layout-{n}.json # Layout plan (target-specific)
│ │ │ ├── {target}-layout-{n}.html # HTML template
│ │ │ └── {target}-layout-{n}.css # CSS template
│ │ ├── {target}-style-{s}-layout-{l}.html # Final prototypes
│ │ ├── compare.html # Interactive matrix view
│ │ └── index.html # Navigation page
│ └── .run-metadata.json # Run configuration
└── WFS-[topic-slug]/
├── workflow-session.json # Session metadata and state (REQUIRED)
├── [.brainstorming/] # Optional brainstorming phase (created when needed)
@@ -289,6 +305,20 @@ All workflows use the same file structure definition regardless of complexity. *
├── [.summaries/] # Task completion summaries (created when tasks complete)
│ ├── IMPL-*-summary.md # Main task summaries
│ └── IMPL-*.*-summary.md # Subtask summaries
├── [design-*/] # UI design outputs (created by ui-design workflows)
│ ├── style-extraction/ # Style analysis results
│ ├── style-consolidation/ # Design system tokens (per-style)
│ │ ├── style-1/ # design-tokens.json, style-guide.md
│ │ └── style-N/
│ ├── prototypes/ # Generated HTML/CSS prototypes
│ │ ├── _templates/ # Target-specific layout plans and templates
│ │ │ ├── {target}-layout-{n}.json # Layout plan (target-specific)
│ │ │ ├── {target}-layout-{n}.html # HTML template
│ │ │ └── {target}-layout-{n}.css # CSS template
│ │ ├── {target}-style-{s}-layout-{l}.html # Final prototypes
│ │ ├── compare.html # Interactive matrix view
│ │ └── index.html # Navigation page
│ └── .run-metadata.json # Run configuration
└── .task/ # Task definitions (REQUIRED)
├── IMPL-*.json # Main task definitions
└── IMPL-*.*.json # Subtask definitions (created dynamically)
@@ -299,6 +329,8 @@ All workflows use the same file structure definition regardless of complexity. *
- **On-Demand Creation**: Other directories created when first needed
- **Dynamic Files**: Subtask JSON files created during task decomposition
- **Scratchpad Usage**: `.scratchpad/` created when CLI commands run without active session
- **Design Usage**: `design-{timestamp}/` created by UI design workflows, `.design/` for standalone design runs
- **Layout Planning**: `prototypes/_templates/` contains target-specific layout plans (JSON) generated during UI generation phase
#### Scratchpad Directory (.scratchpad/)
**Purpose**: Centralized location for non-session-specific CLI outputs

View File

@@ -1,235 +0,0 @@
# 🎨 UI Design Workflow with Triple Vision Analysis & Interactive Preview
This release introduces a comprehensive UI design workflow system with triple vision analysis capabilities, interactive user checkpoints, zero agent overhead, and enhanced preview tools for real-time prototype comparison.
## 🌟 Major Features
### UI Design Workflow System
- **`/workflow:design:auto`**: Semi-autonomous workflow orchestrator with interactive checkpoints
- **`/workflow:design:style-extract`**: Triple vision analysis (Claude Code + Gemini + Codex)
- **`/workflow:design:style-consolidate`**: Token validation and style guide generation
- **`/workflow:design:ui-generate`**: Token-driven HTML/CSS prototype generation with preview tools
- **`/workflow:design:design-update`**: Design system integration into brainstorming artifacts
### 👁️ Triple Vision Analysis
- **Claude Code**: Quick initial visual analysis using native Read tool
- **Gemini Vision**: Deep semantic understanding of design intent
- **Codex Vision**: Structured pattern recognition with -i parameter
- **Consensus Synthesis**: Weighted combination strategy for robust results
### ⏸️ Interactive Checkpoints
- **Checkpoint 1**: User selects preferred style variants after extraction
- **Checkpoint 2**: User confirms selected prototypes before design update
- Pause-and-continue pattern for critical design decisions
### 🌐 Preview Enhancement System (NEW!)
- **`index.html`**: Master preview navigation with grid layout
- **`compare.html`**: Side-by-side comparison with responsive viewport toggles
- **`PREVIEW.md`**: Comprehensive preview instructions and server setup guide
- Synchronized scrolling for layout comparison
- Dynamic page switching and real-time responsive testing
### 🎯 Zero Agent Overhead
- Removed Task(conceptual-planning-agent) wrappers from design commands
- Direct bash execution for gemini-wrapper and codex commands
- Improved performance while preserving all functionality
## 🚀 Quick Start
### Complete Design Workflow
```bash
# Semi-autonomous workflow with user checkpoints
/workflow:design:auto --session WFS-auth --images "design-refs/*.png" --pages "login,register" --batch-plan
```
### Individual Commands
```bash
# Extract design styles (triple vision analysis)
/workflow:design:style-extract --session WFS-auth --images "refs/*.png"
# Consolidate selected variants
/workflow:design:style-consolidate --session WFS-auth --variants "variant-1,variant-3"
# Generate prototypes with preview tools
/workflow:design:ui-generate --session WFS-auth --pages "login,register" --variants 2
# Preview generated prototypes
cd .workflow/WFS-auth/.design/prototypes
python -m http.server 8080 # Visit http://localhost:8080
# Integrate design system
/workflow:design:design-update --session WFS-auth --selected-prototypes "login-variant-1,register-variant-2"
```
## 🎨 Design System Features
- **OKLCH Color Format**: Perceptually uniform color space
- **W3C Design Tokens**: Standard-compliant token format
- **WCAG 2.1 AA Compliance**: Automated accessibility validation
- **Style Override Support**: Runtime token customization with --style-overrides
- **Batch Task Generation**: Automatic task creation with --batch-plan
## 📊 Preview Tools
### Master Navigation (index.html)
- Grid layout of all generated prototypes
- Quick links to individual variants
- Metadata display (session ID, timestamps, page info)
- Direct access to implementation notes
### Side-by-Side Comparison (compare.html)
- Iframe-based comparison for multiple variants
- Responsive viewport toggles:
- Desktop (100%)
- Tablet (768px)
- Mobile (375px)
- Synchronized scrolling option
- Dynamic page switching dropdown
- Real-time variant comparison
### Preview Options
```bash
# Option 1: Direct browser (simplest)
cd .workflow/WFS-{session}/.design/prototypes
open index.html # or double-click
# Option 2: Local server (recommended)
python -m http.server 8080 # Python
npx http-server -p 8080 # Node.js
php -S localhost:8080 # PHP
# Visit: http://localhost:8080
```
## 📦 What's Included
### New Commands (5)
- `/workflow:design:auto`
- `/workflow:design:style-extract`
- `/workflow:design:style-consolidate`
- `/workflow:design:ui-generate`
- `/workflow:design:design-update`
### Generated Files
```
.workflow/WFS-{session}/.design/
├── style-extraction/
│ ├── claude_vision_analysis.json
│ ├── gemini_vision_analysis.json
│ ├── codex_vision_analysis.json
│ ├── semantic_style_analysis.json
│ ├── design-tokens.json
│ └── style-cards.json
├── style-consolidation/
│ ├── design-tokens.json (validated)
│ ├── style-guide.md
│ ├── tailwind.config.js
│ └── validation-report.json
└── prototypes/
├── index.html (NEW - preview navigation)
├── compare.html (NEW - side-by-side comparison)
├── PREVIEW.md (NEW - setup instructions)
├── {page}-variant-{n}.html
├── {page}-variant-{n}.css
└── design-tokens.css
```
## 🔄 Workflow Integration
Design phase fits seamlessly between brainstorming and planning:
```
Brainstorming → UI Design → Planning → Execution
↓ ↓ ↓ ↓
synthesis- design-tokens tasks with token-driven
specification + style design implementation
guide context
```
**Optional but recommended** for UI-heavy projects:
- User-facing applications
- Design system creation
- Brand-critical interfaces
- Accessibility compliance projects
## 💡 Benefits
### User Experience
- 🎨 Visual validation before implementation
- ⏸️ Interactive control at critical decision points
- 👁️ Comprehensive analysis from three AI vision sources
- 🌐 Real-time preview with comparison tools
- 🎯 Zero waiting with direct bash execution
### Code Quality
- 🔒 100% CSS values use custom properties
- ♿ WCAG AA validated at design phase
- 🎨 Single source of truth for visual design
- 🧪 Production-ready prototypes (semantic HTML5, responsive, accessible)
### Development Workflow
- 🔄 Seamless integration with existing workflow
- 🚀 Backward compatible (design phase optional)
- 📊 Better planning with design system context
- 🎯 Focused implementation from validated prototypes
## 📚 Documentation
- **README.md**: Updated with UI Design Workflow section
- **README_CN.md**: Chinese documentation for design workflow
- **CHANGELOG.md**: Comprehensive release notes with examples
- **Command Files**: Detailed implementation guides for all 5 commands
## 🔧 Technical Details
**Triple Vision Analysis Flow**:
```
Reference Images
Claude Code (Read tool) → claude_vision_analysis.json
Gemini Vision (wrapper) → gemini_vision_analysis.json
Codex Vision (codex -i) → codex_vision_analysis.json
Main Claude Synthesis → semantic_style_analysis.json
Codex Token Generation → design-tokens.json, style-cards.json
```
**Checkpoint Workflow Pattern**:
```
User: /workflow:design:auto --session WFS-xxx --images "refs/*.png" --pages "dashboard"
Phase 1: style-extract (automatic)
↓ [CHECKPOINT 1: User selects variants]
User: /workflow:design:style-consolidate --session WFS-xxx --variants "variant-1"
Phase 3: ui-generate (automatic)
↓ [CHECKPOINT 2: User confirms prototypes]
User: /workflow:design:design-update --session WFS-xxx --selected-prototypes "dashboard-variant-1"
Phase 5: batch-plan (optional, if --batch-plan flag)
```
## 🆙 Upgrade Instructions
```bash
# Windows (PowerShell)
Invoke-Expression (Invoke-WebRequest -Uri "https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.ps1" -UseBasicParsing).Content
# Linux/macOS (Bash/Zsh)
bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.sh)
```
## 🐛 Bug Fixes & Improvements
- Optimized agent architecture by removing unnecessary wrappers
- Improved execution performance with direct bash commands
- Enhanced documentation consistency across English and Chinese versions
- Updated phase numbering to accommodate new design phase
## 📝 Full Changelog
See [CHANGELOG.md](https://github.com/catlog22/Claude-Code-Workflow/blob/main/CHANGELOG.md) for complete details.
---
**Questions or Issues?**
- 📖 [Documentation](https://github.com/catlog22/Claude-Code-Workflow)
- 🐛 [Report Issues](https://github.com/catlog22/Claude-Code-Workflow/issues)
- 💬 [Discussions](https://github.com/catlog22/Claude-Code-Workflow/discussions)

View File

@@ -5,6 +5,448 @@ 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
This release includes a command rename for better clarity and refactors UI design workflow documentation for improved maintainability.
#### Changed
**Command Renaming**:
- **`/workflow:concept-verify``/workflow:concept-clarify`**: Renamed for clearer intent
- Better reflects the command's purpose of clarifying underspecified areas
- Updated all internal references and documentation
- Command functionality remains unchanged
**explore-auto.md** (formerly `auto.md`):
- **File Reorganization**: Reduced from 540 to 435 lines (19.4% reduction)
- **Merged Duplicate Content**: Consolidated Overview, Coordinator Role, and Execution Model into single "Overview & Execution Model" section
- **Simplified Core Rules**: From verbose descriptions to 5 concise rules
- **Streamlined TodoWrite Pattern**: From detailed steps to concise mode with comments
- **Preserved Functionality**: All 6-phase execution logic, intelligent parsing, interactive confirmation, and matrix mode intact
**imitate-auto.md** (NEW command):
- **File Reorganization**: Reduced from 566 to 475 lines (16.1% reduction)
- **Merged Sections**: Combined Overview, Core Philosophy, Execution Model, and Workflow Position into unified structure
- **Simplified Phase 0.5**: Screenshot capture logic complete but reduced redundant error handling
- **Consolidated Performance**: Merged "Key Differences" and "Performance Benefits" into single comparison table
- **Preserved Functionality**: All 5-phase execution, auto-screenshot mechanism, direct token extraction, and error handling intact
#### Improved
**Documentation Quality**:
- 📚 Clearer structure with merged duplicate concepts
- 🎯 Reduced redundancy across command documentation
- ✨ Consistent formatting and organization patterns
- 📖 Improved maintainability with better content separation
- 🔍 All key functionality points preserved and highlighted
**Total Impact**:
- **explore-auto.md**: 105 lines removed (19.4% reduction)
- **imitate-auto.md**: 91 lines removed (16.1% reduction)
- **Combined**: 196 lines of documentation optimized
- **Zero functionality loss**: All features, workflows, and technical details preserved
## [4.2.0] - 2025-10-09
### 🎯 Multi-Page Support Enhancement
Based on Gemini's analysis of the UI Design Workflow, this version implements four key optimizations to improve the multi-page design experience.
#### Added
- **Cross-Page Consistency Validation**: New `Phase 3.5` in `generate` command automatically validates design consistency (shared components, tokens, accessibility) across multiple pages
- **Side-by-Side Prototype Comparison**: `compare.html` preview tool now includes "Side-by-Side" tab to compare any two prototypes with intelligent consistency hints
- **Batch Prototype Selection**: `compare.html` features "By Style" and "By Layout" buttons for quick bulk prototype selection
#### Changed
- **Enhanced Page Inference**: `auto` command's page detection uses multiple regex patterns with interactive user confirmation
- **Improved Export**: Selection export from `compare.html` is now more structured with detailed metadata
## [4.1.1] - 2025-10-09
### 🔧 Symlink Fix & Agent Optimization
#### Fixed
- **Windows Symbolic Link Creation**: Corrected `auto.md` workflow to use `mklink /D` on Windows, preventing duplicate directories instead of symlinks
#### Changed
- **Agent Allocation Strategy**: `generate.md` now allocates tasks by layout (layout-based) instead of style, improving performance and consistency for high variant counts by having one agent handle one layout strategy across multiple styles
## [4.1.0] - 2025-10-09
### 🔄 Matrix-Only UI Design Workflow
#### Changed
- **Matrix Mode by Default**: UI Design workflow now exclusively uses `style × layout` matrix mode with `--style-variants` and `--layout-variants` as standard parameters
- **Path Standardization**: Standalone design sessions saved to `.workflow/.scratchpad/` adhering to project architecture
- **Simplified Orchestration**: `auto.md` command simplified to use single `SlashCommand` for generation phase, removing complex loop logic
#### Removed
- **Deprecated Parameters**: Removed `--variants` and `--creative-variants` in favor of explicit `--style-variants` and `--layout-variants`
- **Standard/Creative Modes**: Distinction between these modes removed
---
## [4.0.2] - 2025-10-09
### 🔄 UI Design Workflow - Complete Refactoring
**BREAKING CHANGES**: Complete refactoring to pure Claude-native execution, removing all external tool dependencies.
#### Breaking Changes
**Command Path Migration**:
```bash
# ❌ Old (v4.0.1 and earlier)
/workflow:design:style-extract
/workflow:design:style-consolidate
/workflow:design:ui-generate
/workflow:design:design-update
/workflow:design:auto
# ✅ New (v4.0.2)
/workflow:ui-design:extract
/workflow:ui-design:consolidate
/workflow:ui-design:generate
/workflow:ui-design:update
/workflow:ui-design:auto
```
**Parameter Removal**:
- **`--tool` parameter removed**: All commands now use Claude-native execution exclusively
- No more `--tool gemini` or `--tool codex` options
- Simplified command syntax
**Execution Model Changes**:
```bash
# ❌ Old: External CLI tools required
# Required: gemini-wrapper, codex, qwen-wrapper
/workflow:design:style-extract --tool gemini --images "refs/*.png"
/workflow:design:style-consolidate --tool gemini --variants "variant-1,variant-2"
/workflow:design:ui-generate --tool codex --pages "dashboard,auth"
# ✅ New: Pure Claude + agents
/workflow:ui-design:extract --images "refs/*.png" --variants 3
/workflow:ui-design:consolidate --variants "variant-1,variant-2"
/workflow:ui-design:generate --pages "dashboard,auth" --variants 2
```
#### Removed
**External Tool Dependencies**:
- `gemini-wrapper` calls removed from style-extract and style-consolidate
- `codex` calls removed from style-consolidate and ui-generate
- `qwen-wrapper` calls removed entirely
- All `bash()` wrapped CLI tool invocations eliminated
**Intermediate Output Files**:
- `semantic_style_analysis.json` (replaced by embedded data in style-cards.json)
- `initial_analysis.json` (analysis now done in single pass)
- `style-philosophy.md` (integrated into style-guide.md)
- Reduced from 7+ files to 4 essential files per phase
**Execution Modes**:
- "conventional" mode removed from ui-generate (codex dependency)
- "cli" mode removed from style-consolidate (external tool dependency)
- Unified to agent-only execution
#### Changed
**style-extract (`/workflow:ui-design:extract`)**:
- **Before**: Multi-step with gemini-wrapper + codex
- Step 1: Claude analysis → initial_analysis.json
- Step 2: gemini-wrapper → semantic_style_analysis.json
- Step 3: codex → design-tokens.json + tailwind-tokens.js
- Output: 4 files
- **After**: Single-pass Claude analysis
- Step 1: Claude analysis → style-cards.json (with embedded proposed_tokens)
- Output: 1 file
- **New structure**: `style-cards.json` includes complete `proposed_tokens` object per variant
- **Reproducibility**: 100% deterministic with Claude-only execution
**style-consolidate (`/workflow:ui-design:consolidate`)**:
- **Before**: Dual-tool approach
- Step 1: gemini-wrapper → style-philosophy.md
- Step 2: codex → design-tokens.json + validation
- Mode detection: cli vs agent
- **After**: Single-pass Claude synthesis
- Step 1: Claude reads `proposed_tokens` from style-cards.json
- Step 2: Claude generates all 4 files in one prompt
- Output: design-tokens.json, style-guide.md, tailwind.config.js, validation-report.json
- **Removed**: `--tool` parameter and mode detection logic
**ui-generate (`/workflow:ui-design:generate`)**:
- **Before**: Three execution modes
- conventional: codex CLI calls
- agent: Task(conceptual-planning-agent)
- Mode detection based on `--tool` flag
- **After**: Unified agent-only execution
- standard: Single Task(conceptual-planning-agent) for consistent variants
- creative: Parallel Task(conceptual-planning-agent) for diverse layouts
- Only `--variants` or `--creative-variants` determines mode
- **Removed**: `--tool` parameter, conventional mode
**design-update (`/workflow:ui-design:update`)**:
- **Before**: References `style-philosophy.md`
- **After**: Extracts philosophy from `style-guide.md`
- **Changed**: Adapted to new 4-file output structure from consolidate phase
**auto (`/workflow:ui-design:auto`)**:
- **Before**: Passed `--tool` flags to sub-commands
- **After**: No tool parameters, pure orchestration
- **Simplified**: Command construction logic (no mode detection)
- **Examples**: Updated all 3 example flows
#### Added
**Enhanced style-cards.json Structure**:
```json
{
"extraction_metadata": {
"session_id": "WFS-xxx",
"input_mode": "image|text|hybrid",
"timestamp": "ISO-8601",
"variants_count": 3
},
"style_cards": [
{
"id": "variant-1",
"name": "Modern Minimalist",
"description": "...",
"design_philosophy": "...",
"preview": { "primary": "oklch(...)", ... },
"proposed_tokens": {
"colors": { /* complete color system */ },
"typography": { /* complete typography system */ },
"spacing": { /* complete spacing scale */ },
"border_radius": { /* border radius scale */ },
"shadows": { /* shadow system */ },
"breakpoints": { /* responsive breakpoints */ }
}
}
]
}
```
**Unified Output Structure**:
- `style-extraction/`: style-cards.json (1 file)
- `style-consolidation/`: design-tokens.json, style-guide.md, tailwind.config.js, validation-report.json (4 files)
- `prototypes/`: HTML/CSS files + index.html + compare.html + PREVIEW.md
#### Improved
**Performance**:
- **Faster execution**: No external process spawning
- **Reduced I/O**: Fewer intermediate files
- **Parallel efficiency**: Native agent parallelization
**Reliability**:
- **Zero external dependencies**: No gemini-wrapper, codex, or qwen-wrapper required
- **No API failures**: Eliminates external API call failure points
- **Consistent output**: Deterministic JSON structure
**Maintainability**:
- **Simpler codebase**: 5 commands, unified patterns
- **Clear data flow**: style-cards → design-tokens → prototypes
- **Easier debugging**: All logic visible in command files
**Reproducibility**:
- **Deterministic structure**: Same inputs → same output structure
- **Version-controlled logic**: All prompts in .md files
- **No black-box tools**: Complete transparency
#### Migration Guide
**For Standalone Usage**:
```bash
# Old command format
/workflow:design:auto --tool gemini --prompt "Modern blog" --variants 3
# New command format (auto-migrated)
/workflow:ui-design:auto --prompt "Modern blog" --variants 3
```
**For Integrated Workflow Sessions**:
```bash
# Old workflow
/workflow:design:style-extract --session WFS-xxx --tool gemini --images "refs/*.png"
/workflow:design:style-consolidate --session WFS-xxx --tool gemini --variants "variant-1,variant-2"
/workflow:design:ui-generate --session WFS-xxx --tool codex --pages "dashboard,auth"
/workflow:design:design-update --session WFS-xxx
# New workflow (simplified)
/workflow:ui-design:extract --session WFS-xxx --images "refs/*.png" --variants 2
/workflow:ui-design:consolidate --session WFS-xxx --variants "variant-1,variant-2"
/workflow:ui-design:generate --session WFS-xxx --pages "dashboard,auth" --variants 2
/workflow:ui-design:update --session WFS-xxx
```
**Configuration Changes Required**: None - all external tool configurations can be removed
#### Files Changed
**Renamed/Relocated**:
- `.claude/commands/workflow/design/``.claude/commands/workflow/ui-design/`
- All command files updated with new paths
**Modified Commands**:
- `style-extract.md``extract.md` (complete rewrite)
- `style-consolidate.md``consolidate.md` (complete rewrite)
- `ui-generate.md``generate.md` (simplified)
- `design-update.md``update.md` (adapted to new structure)
- `auto.md` (updated orchestration)
**Documentation**:
- Updated all command examples
- Updated parameter descriptions
- Added Key Improvements sections
- Clarified Integration Points
## [4.0.1] - 2025-10-07
### 🎯 Intelligent Page Inference
@@ -21,15 +463,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
**New Examples**:
```bash
# Simplest - pages inferred from prompt
/workflow:design:auto --prompt "Modern blog with home, article and author pages"
/workflow:ui-design:auto --prompt "Modern blog with home, article and author pages"
# Explicit override if needed
/workflow:design:auto --prompt "SaaS app" --pages "dashboard,settings,billing"
/workflow:ui-design:auto --prompt "SaaS app" --pages "dashboard,settings,billing"
```
**Commands Updated**:
- `/workflow:design:auto`: All parameters now optional
- `/workflow:design:ui-generate`: `--pages` optional with smart inference
- `/workflow:ui-design:auto`: All parameters now optional
- `/workflow:ui-design:ui-generate`: `--pages` optional with smart inference
## [4.0.0] - 2025-10-07
@@ -52,18 +494,18 @@ This major release introduces agent-driven creative exploration, unified variant
**Migration Guide**:
```bash
# ❌ Old (v3.5.0 and earlier) - NO LONGER WORKS
/workflow:design:style-extract --session WFS-auth --images "design-refs/*.png"
/workflow:design:ui-generate --session WFS-auth --pages "login,register"
/workflow:ui-design:style-extract --session WFS-auth --images "design-refs/*.png"
/workflow:ui-design:ui-generate --session WFS-auth --pages "login,register"
# ✅ New (v4.0.1) - All parameters optional
/workflow:design:style-extract --images "design-refs/*.png" --variants 3
/workflow:design:ui-generate --variants 2
/workflow:ui-design:style-extract --images "design-refs/*.png" --variants 3
/workflow:ui-design:ui-generate --variants 2
# ✅ Simplest form (pages inferred from prompt)
/workflow:design:auto --prompt "Modern blog with home, article and author pages"
/workflow:ui-design:auto --prompt "Modern blog with home, article and author pages"
# ✅ With agent mode and explicit pages
/workflow:design:auto --prompt "Modern SaaS" --pages "dashboard,settings" --variants 3 --use-agent
/workflow:ui-design:auto --prompt "Modern SaaS" --pages "dashboard,settings" --variants 3 --use-agent
```
**Deprecated Commands**:
@@ -112,23 +554,23 @@ This major release introduces agent-driven creative exploration, unified variant
#### Changed
**New Command Interface** (v4.0.1):
- **`/workflow:design:auto`**:
- **`/workflow:ui-design:auto`**:
- All parameters optional with smart defaults
- `--prompt <desc>`: Design description (infers pages automatically)
- `--images <glob>`: Reference images (default: `design-refs/*`)
- `--pages <list>`: Explicit page override (auto-inferred if omitted)
- `--session <id>`, `--variants <count>`, `--use-agent`, `--batch-plan`
- Examples:
- Minimal: `/workflow:design:auto --prompt "Modern blog with home and article pages"`
- Agent Mode: `/workflow:design:auto --prompt "SaaS dashboard and settings" --variants 3 --use-agent`
- Hybrid: `/workflow:design:auto --images "refs/*.png" --prompt "E-commerce: home, product, cart"`
- Minimal: `/workflow:ui-design:auto --prompt "Modern blog with home and article pages"`
- Agent Mode: `/workflow:ui-design:auto --prompt "SaaS dashboard and settings" --variants 3 --use-agent`
- Hybrid: `/workflow:ui-design:auto --images "refs/*.png" --prompt "E-commerce: home, product, cart"`
- **`/workflow:design:style-extract`**:
- **`/workflow:ui-design:style-extract`**:
- At least one of `--images` or `--prompt` recommended
- All other parameters optional
- Agent mode: Parallel generation of diverse design directions
- **`/workflow:design:ui-generate`**:
- **`/workflow:ui-design:ui-generate`**:
- All parameters optional (pages inferred from session or defaults to ["home"])
- `--pages <list>`: Optional explicit page list
- Agent mode: Parallel layout exploration (F-Pattern, Grid, Asymmetric)
@@ -138,19 +580,19 @@ This major release introduces agent-driven creative exploration, unified variant
**Standalone Quick Prototyping**:
```bash
# Pure text with page inference (simplest)
/workflow:design:auto --prompt "Modern minimalist blog with home, article and author pages, dark theme" --use-agent
/workflow:ui-design:auto --prompt "Modern minimalist blog with home, article and author pages, dark theme" --use-agent
# Pure image with inferred pages
/workflow:design:auto --images "refs/*.png" --variants 2
/workflow:ui-design:auto --images "refs/*.png" --variants 2
# Hybrid input with explicit page override
/workflow:design:auto --images "current-app.png" --prompt "Modernize to Linear.app style" --pages "tasks,settings" --use-agent
/workflow:ui-design:auto --images "current-app.png" --prompt "Modernize to Linear.app style" --pages "tasks,settings" --use-agent
```
**Integrated Workflow Enhancement**:
```bash
# Within existing workflow (pages inferred from synthesis)
/workflow:design:auto --session WFS-app-refresh --images "refs/*.png" --variants 3 --use-agent
/workflow:ui-design:auto --session WFS-app-refresh --images "refs/*.png" --variants 3 --use-agent
```
#### Technical Details
@@ -205,7 +647,7 @@ This release introduces a comprehensive UI design workflow system with triple vi
#### Added
**New UI Design Workflow System**:
- **`/workflow:design:auto`**: Semi-autonomous UI design workflow orchestrator
- **`/workflow:ui-design:auto`**: Semi-autonomous UI design workflow orchestrator
- Interactive checkpoints for user style selection and prototype confirmation
- Optional batch task generation with `--batch-plan` flag
- Pause-and-continue pattern at critical decision points
@@ -226,12 +668,12 @@ This release introduces a comprehensive UI design workflow system with triple vi
**Individual Design Commands**:
**`/workflow:design:style-extract`** - Extract design styles from reference images
- **Usage**: `/workflow:design:style-extract --session <session_id> --images "<glob_pattern>"`
**`/workflow:ui-design:style-extract`** - Extract design styles from reference images
- **Usage**: `/workflow:ui-design:style-extract --session <session_id> --images "<glob_pattern>"`
- **Examples**:
```bash
/workflow:design:style-extract --session WFS-auth --images "design-refs/*.png"
/workflow:design:style-extract --session WFS-dashboard --images "refs/dashboard-*.jpg"
/workflow:ui-design:style-extract --session WFS-auth --images "design-refs/*.png"
/workflow:ui-design:style-extract --session WFS-dashboard --images "refs/dashboard-*.jpg"
```
- **Features**:
- Triple vision analysis (Claude Code + Gemini + Codex)
@@ -241,12 +683,12 @@ This release introduces a comprehensive UI design workflow system with triple vi
- Supports PNG, JPG, WebP image formats
- **Output**: `.design/style-extraction/` with analysis files and 2-3 style variant cards
**`/workflow:design:style-consolidate`** - Consolidate selected style variants
- **Usage**: `/workflow:design:style-consolidate --session <session_id> --variants "<variant_ids>"`
**`/workflow:ui-design:style-consolidate`** - Consolidate selected style variants
- **Usage**: `/workflow:ui-design:style-consolidate --session <session_id> --variants "<variant_ids>"`
- **Examples**:
```bash
/workflow:design:style-consolidate --session WFS-auth --variants "variant-1,variant-3"
/workflow:design:style-consolidate --session WFS-dashboard --variants "variant-2"
/workflow:ui-design:style-consolidate --session WFS-auth --variants "variant-1,variant-3"
/workflow:ui-design:style-consolidate --session WFS-dashboard --variants "variant-2"
```
- **Features**:
- Validates and merges design tokens from selected variants
@@ -256,13 +698,13 @@ This release introduces a comprehensive UI design workflow system with triple vi
- OKLCH color format with fallback
- **Output**: `.design/style-consolidation/` with validated design system files
**`/workflow:design:ui-generate`** - Generate production-ready UI prototypes *(NEW: with preview enhancement)*
- **Usage**: `/workflow:design:ui-generate --session <session_id> --pages "<page_list>" [--variants <count>] [--style-overrides "<path_or_json>"]`
**`/workflow:ui-design:ui-generate`** - Generate production-ready UI prototypes *(NEW: with preview enhancement)*
- **Usage**: `/workflow:ui-design:ui-generate --session <session_id> --pages "<page_list>" [--variants <count>] [--style-overrides "<path_or_json>"]`
- **Examples**:
```bash
/workflow:design:ui-generate --session WFS-auth --pages "login,register"
/workflow:design:ui-generate --session WFS-dashboard --pages "dashboard" --variants 3
/workflow:design:ui-generate --session WFS-auth --pages "login" --style-overrides "overrides.json"
/workflow:ui-design:ui-generate --session WFS-auth --pages "login,register"
/workflow:ui-design:ui-generate --session WFS-dashboard --pages "dashboard" --variants 3
/workflow:ui-design:ui-generate --session WFS-auth --pages "login" --style-overrides "overrides.json"
```
- **Features**:
- Token-driven HTML/CSS generation with Codex
@@ -275,12 +717,12 @@ This release introduces a comprehensive UI design workflow system with triple vi
- **Output**: `.design/prototypes/` with HTML/CSS files and preview tools
- **Preview**: Open `index.html` in browser or start local server for interactive preview
**`/workflow:design:design-update`** - Integrate design system into brainstorming
- **Usage**: `/workflow:design:design-update --session <session_id> [--selected-prototypes "<prototype_ids>"]`
**`/workflow:ui-design:design-update`** - Integrate design system into brainstorming
- **Usage**: `/workflow:ui-design:design-update --session <session_id> [--selected-prototypes "<prototype_ids>"]`
- **Examples**:
```bash
/workflow:design:design-update --session WFS-auth
/workflow:design:design-update --session WFS-auth --selected-prototypes "login-variant-1,register-variant-2"
/workflow:ui-design:design-update --session WFS-auth
/workflow:ui-design:design-update --session WFS-auth --selected-prototypes "login-variant-1,register-variant-2"
```
- **Features**:
- Updates `synthesis-specification.md` with UI/UX guidelines section
@@ -289,12 +731,12 @@ This release introduces a comprehensive UI design workflow system with triple vi
- Merges selected prototype recommendations into brainstorming artifacts
- **Output**: Updated brainstorming files with design system integration
**`/workflow:design:auto`** - Semi-autonomous orchestrator with interactive checkpoints
- **Usage**: `/workflow:design:auto --session <session_id> --images "<glob>" --pages "<list>" [--variants <count>] [--batch-plan]`
**`/workflow:ui-design:auto`** - Semi-autonomous orchestrator with interactive checkpoints
- **Usage**: `/workflow:ui-design:auto --session <session_id> --images "<glob>" --pages "<list>" [--variants <count>] [--batch-plan]`
- **Examples**:
```bash
/workflow:design:auto --session WFS-auth --images "design-refs/*.png" --pages "login,register"
/workflow:design:auto --session WFS-dashboard --images "refs/*.jpg" --pages "dashboard" --variants 3 --batch-plan
/workflow:ui-design:auto --session WFS-auth --images "design-refs/*.png" --pages "login,register"
/workflow:ui-design:auto --session WFS-dashboard --images "refs/*.jpg" --pages "dashboard" --variants 3 --batch-plan
```
- **Features**:
- Orchestrates entire design workflow with pause-and-continue checkpoints
@@ -306,11 +748,11 @@ This release introduces a comprehensive UI design workflow system with triple vi
**Interactive Checkpoint System**:
- **Checkpoint 1 (After style-extract)**: User selects preferred style variants
- Command: `/workflow:design:style-consolidate --session WFS-xxx --variants "variant-1,variant-3"`
- Command: `/workflow:ui-design:style-consolidate --session WFS-xxx --variants "variant-1,variant-3"`
- Workflow pauses until user runs consolidation command
- **Checkpoint 2 (After ui-generate)**: User confirms selected prototypes
- Command: `/workflow:design:design-update --session WFS-xxx --selected-prototypes "page-variant-1,page-variant-2"`
- Command: `/workflow:ui-design:design-update --session WFS-xxx --selected-prototypes "page-variant-1,page-variant-2"`
- Workflow pauses until user runs design-update command
**Design System Features**:
@@ -384,7 +826,7 @@ python -m http.server 8080 # Visit http://localhost:8080
**Updated Documentation**:
- **README.md**: Added UI Design Workflow section in Getting Started
- **README_CN.md**: Chinese documentation updated with design workflow
- **Command Reference**: Added 5 new `/workflow:design:*` commands
- **Command Reference**: Added 5 new `/workflow:ui-design:*` commands
- **Phase Renumbering**: Shifted phases to accommodate new Phase 2 (UI Design)
#### Benefits
@@ -425,15 +867,15 @@ Phase 6: Codex Token Generation → design-tokens.json, style-cards.json
**Checkpoint Workflow Pattern**:
```
User: /workflow:design:auto --session WFS-xxx --images "refs/*.png" --pages "dashboard,auth"
User: /workflow:ui-design:auto --session WFS-xxx --images "refs/*.png" --pages "dashboard,auth"
Phase 1: style-extract (automatic)
↓ [CHECKPOINT 1: User selects style variants]
User: /workflow:design:style-consolidate --session WFS-xxx --variants "variant-1,variant-3"
User: /workflow:ui-design:style-consolidate --session WFS-xxx --variants "variant-1,variant-3"
Phase 3: ui-generate (automatic after Phase 2)
↓ [CHECKPOINT 2: User confirms prototypes]
User: /workflow:design:design-update --session WFS-xxx --selected-prototypes "dashboard-variant-1,auth-variant-2"
User: /workflow:ui-design:design-update --session WFS-xxx --selected-prototypes "dashboard-variant-1,auth-variant-2"
Phase 5: batch-plan (optional, automatic if --batch-plan flag)
```

142
README.md
View File

@@ -2,7 +2,7 @@
<div align="center">
[![Version](https://img.shields.io/badge/version-v3.5.0-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![Version](https://img.shields.io/badge/version-v4.2.1-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey.svg)]()
[![MCP Tools](https://img.shields.io/badge/🔧_MCP_Tools-Experimental-orange.svg)](https://github.com/modelcontextprotocol)
@@ -15,16 +15,13 @@
**Claude Code Workflow (CCW)** is a next-generation multi-agent automation framework that orchestrates complex software development tasks through intelligent workflow management and autonomous execution.
> **🎉 Latest: v3.5.0** - UI Design Workflow with Triple Vision Analysis. See [CHANGELOG.md](CHANGELOG.md) for details.
> **🎉 Latest: v4.2.1** - Documentation Refactoring for UI Design Workflow. See [CHANGELOG.md](CHANGELOG.md) for details.
>
> **What's New in v3.5.0**:
> - 🎨 **UI Design Workflow**: Complete design refinement workflow from style extraction to prototype generation
> - 👁️ **Triple Vision Analysis**: Combines Claude Code + Gemini + Codex vision capabilities for comprehensive style extraction
> - ⏸️ **Interactive Checkpoints**: User selection points for style variants and prototype confirmation
> - 🎯 **Zero Agent Overhead**: Direct bash execution for CLI tools, removing unnecessary agent wrappers
> - 🎨 **Style Customization**: Runtime override support with `--style-overrides` parameter
> - 📦 **Batch Task Generation**: Optional automatic task creation for selected prototypes with `--batch-plan`
> - 🔄 **Semi-Autonomous Workflow**: User-driven continuation at critical design decision points
> **What's New in v4.2.1**:
> - 📚 **Documentation Optimization**: Reduced file sizes by 15-20% while preserving all functionality
> - 🎯 **Clearer Structure**: Merged duplicate concepts and streamlined content organization
> - **Improved Maintainability**: Better content separation and consistent formatting patterns
> - 📖 **Zero Functionality Loss**: All features, workflows, and technical details preserved
---
@@ -253,21 +250,27 @@ MCP (Model Context Protocol) tools provide advanced codebase analysis. **Recomme
**Phase 2: UI Design Refinement** *(Optional for UI-heavy projects)*
```bash
# Extract design styles from reference images and generate prototypes
/workflow:design:auto --session WFS-auth --images "design-refs/*.png" --pages "login,register" --batch-plan
# Matrix Exploration Mode - Multiple style/layout variants (v4.2.1+)
/workflow:ui-design:explore-auto --prompt "Modern blog: home, article, author" --style-variants 3 --layout-variants 2
# Fast Imitation Mode - Single design replication (v4.2.1+)
/workflow:ui-design:imitate-auto --images "refs/design.png" --pages "dashboard,settings"
# With session integration
/workflow:ui-design:explore-auto --session WFS-auth --images "refs/*.png" --style-variants 2 --layout-variants 3
# Or run individual design phases
/workflow:design:style-extract --session WFS-auth --images "refs/*.png"
/workflow:design:style-consolidate --session WFS-auth --variants "variant-1,variant-3"
/workflow:design:ui-generate --session WFS-auth --pages "login,register" --variants 2
/workflow:ui-design:extract --images "refs/*.png" --variants 3
/workflow:ui-design:consolidate --variants "variant-1,variant-3"
/workflow:ui-design:generate --pages "dashboard,auth" --style-variants 2 --layout-variants 2
# Preview generated prototypes (NEW!)
# Option 1: Open .workflow/WFS-auth/.design/prototypes/index.html in browser
# Preview generated prototypes
# Option 1: Open .workflow/WFS-auth/.design/prototypes/compare.html in browser
# Option 2: Start local server
cd .workflow/WFS-auth/.design/prototypes && python -m http.server 8080
# Visit http://localhost:8080 for interactive preview with comparison tools
/workflow:design:design-update --session WFS-auth --selected-prototypes "login-variant-1,register-variant-2"
/workflow:ui-design:update --session WFS-auth --selected-prototypes "dashboard-s1-l2"
```
**Phase 3: Action Planning**
@@ -361,11 +364,12 @@ cd .workflow/WFS-auth/.design/prototypes && python -m http.server 8080
|---|---|
| `/workflow:session:*` | Manage development sessions (`start`, `pause`, `resume`, `list`, `switch`, `complete`). |
| `/workflow:brainstorm:*` | Use role-based agents for multi-perspective planning. |
| `/workflow:design:auto` | **NEW** Semi-autonomous UI design workflow with interactive checkpoints for style and prototype selection. |
| `/workflow:design:style-extract` | **NEW** Extract design styles from reference images using triple vision analysis (Claude + Gemini + Codex). |
| `/workflow:design:style-consolidate` | **NEW** Consolidate selected style variants into validated design tokens and style guide. |
| `/workflow:design:ui-generate` | **NEW** Generate token-driven HTML/CSS prototypes with optional style overrides. |
| `/workflow:design:design-update` | **NEW** Integrate finalized design system into brainstorming artifacts. |
| `/workflow:ui-design:explore-auto` | **v4.2.1** Matrix exploration mode - Generate multiple style × layout variants for comprehensive design exploration. |
| `/workflow:ui-design:imitate-auto` | **v4.2.1** Fast imitation mode - Rapid single-design replication with auto-screenshot and direct token extraction. |
| `/workflow:ui-design:extract` | **v4.2.1** Extract design from images/text using Claude-native analysis. Single-pass variant generation. |
| `/workflow:ui-design:consolidate` | **v4.2.1** Consolidate style variants into validated design tokens using Claude synthesis. |
| `/workflow:ui-design:generate` | **v4.2.1** Generate token-driven HTML/CSS prototypes in matrix mode (style × layout combinations). |
| `/workflow:ui-design:update` | **v4.2.1** Integrate finalized design system into brainstorming artifacts. |
| `/workflow:plan` | Create a detailed, executable plan from a description. |
| `/workflow:tdd-plan` | Create TDD workflow (6 phases) with test coverage analysis and Red-Green-Refactor cycles. |
| `/workflow:execute` | Execute the current workflow plan autonomously. |
@@ -377,50 +381,88 @@ cd .workflow/WFS-auth/.design/prototypes && python -m http.server 8080
| `/workflow:tools:test-concept-enhanced` | Generate test strategy and requirements analysis using Gemini. |
| `/workflow:tools:test-task-generate` | Generate test task JSON with test-fix-cycle specification. |
### **UI Design Workflow Commands (`/workflow:design:*`)** *(v3.5.0+)*
### **UI Design Workflow Commands (`/workflow:ui-design:*`)** *(v4.2.1)*
The design workflow system provides complete UI design refinement from style extraction to prototype generation with interactive preview tools.
The design workflow system provides complete UI design refinement with **pure Claude execution**, **intelligent page inference**, and **zero external dependencies**.
#### Core Commands
**`/workflow:design:auto`** - Complete workflow orchestrator
**`/workflow:ui-design:explore-auto`** - Matrix exploration mode
```bash
# Semi-autonomous workflow with user checkpoints
/workflow:design:auto --session WFS-auth --images "refs/*.png" --pages "login,register"
/workflow:design:auto --session WFS-dash --images "refs/*.jpg" --pages "dashboard" --variants 3 --batch-plan
```
- **Checkpoints**: User selects style variants (Phase 1) and confirms prototypes (Phase 3)
- **Optional**: `--batch-plan` for automatic task generation
# Comprehensive exploration - multiple style × layout variants
/workflow:ui-design:explore-auto --prompt "Modern blog: home, article, author" --style-variants 3 --layout-variants 2
**`/workflow:design:style-extract`** - Triple vision style analysis
# With images and session integration
/workflow:ui-design:explore-auto --session WFS-auth --images "refs/*.png" --style-variants 2 --layout-variants 3
# Text-only mode with page inference
/workflow:ui-design:explore-auto --prompt "E-commerce: home, product, cart" --style-variants 2 --layout-variants 2
```
- **🎯 Matrix Mode**: Generate all style × layout combinations
- **📊 Comprehensive Exploration**: Compare multiple design directions
- **🔍 Interactive Comparison**: Side-by-side comparison with viewport controls
- **✅ Cross-page Validation**: Automatic consistency checks for multi-page designs
- **⚡ Batch Selection**: Quick selection by style or layout
**`/workflow:ui-design:imitate-auto`** - Fast imitation mode
```bash
# Extract design from reference images
/workflow:design:style-extract --session WFS-auth --images "design-refs/*.png"
```
- **Vision Sources**: Claude Code + Gemini + Codex
- **Output**: Style variant cards for user selection
# Rapid single-design replication
/workflow:ui-design:imitate-auto --images "refs/design.png" --pages "dashboard,settings"
**`/workflow:design:style-consolidate`** - Validate and merge tokens
# With session integration
/workflow:ui-design:imitate-auto --session WFS-auth --images "refs/ui.png" --pages "home,product"
# Auto-screenshot from URL (requires Playwright)
/workflow:ui-design:imitate-auto --url "https://example.com" --pages "landing"
```
- **⚡ Speed Optimized**: 5-10x faster than explore-auto
- **📸 Auto-Screenshot**: Automatic URL screenshot capture with Playwright/Chrome
- **🎯 Direct Extraction**: Skip variant selection, go straight to implementation
- **🔧 Single Design Focus**: Best for copying existing designs quickly
**`/workflow:ui-design:extract`** - Style analysis with dual input sources
```bash
# Pure text prompt
/workflow:ui-design:extract --prompt "Modern minimalist, dark theme" --variants 3
# Pure images
/workflow:ui-design:extract --images "refs/*.png" --variants 3
# Hybrid (text guides image analysis)
/workflow:ui-design:extract --images "refs/*.png" --prompt "Linear.app style" --variants 2
```
- **Claude-Native**: Single-pass analysis, no external tools
- **Enhanced Output**: `style-cards.json` with embedded `proposed_tokens`
- **Reproducible**: Deterministic structure, version-controlled logic
- **Output**: 1 file (vs 4+ in previous versions)
**`/workflow:ui-design:consolidate`** - Validate and merge tokens
```bash
# Consolidate selected style variants
/workflow:design:style-consolidate --session WFS-auth --variants "variant-1,variant-3"
/workflow:ui-design:consolidate --session WFS-auth --variants "variant-1,variant-3"
```
- **Claude Synthesis**: Single-pass generation of all design system files
- **Features**: WCAG AA validation, OKLCH colors, W3C token format
- **Output**: `design-tokens.json`, `style-guide.md`, `tailwind.config.js`
- **Output**: `design-tokens.json`, `style-guide.md`, `tailwind.config.js`, `validation-report.json`
**`/workflow:design:ui-generate`** - Generate HTML/CSS prototypes
**`/workflow:ui-design:generate`** - Generate HTML/CSS prototypes
```bash
# Generate prototypes with preview tools
/workflow:design:ui-generate --session WFS-auth --pages "login,register" --variants 2
/workflow:design:ui-generate --session WFS-auth --pages "dashboard" --style-overrides "custom.json"
```
- **🆕 Preview Files**: `index.html` (navigation), `compare.html` (side-by-side), `PREVIEW.md` (instructions)
- **Features**: Token-driven CSS, semantic HTML5, ARIA attributes, responsive design
# Matrix mode - style × layout combinations
/workflow:ui-design:generate --pages "dashboard,auth" --style-variants 2 --layout-variants 3
**`/workflow:design:design-update`** - Integrate design system
# Single page with multiple variants
/workflow:ui-design:generate --pages "home" --style-variants 3 --layout-variants 2
```
- **🎯 Matrix Generation**: Creates all style × layout combinations
- **📊 Multi-page Support**: Consistent design system across pages
- **✅ Consistency Validation**: Automatic cross-page consistency reports (v4.2.0+)
- **🔍 Interactive Preview**: `compare.html` with side-by-side comparison
- **📋 Batch Selection**: Quick selection by style or layout filters
**`/workflow:ui-design:update`** - Integrate design system
```bash
# Update brainstorming artifacts with design system
/workflow:design:design-update --session WFS-auth --selected-prototypes "login-variant-1,register-variant-2"
/workflow:ui-design:update --session WFS-auth --selected-prototypes "login-variant-1"
```
- **Updates**: `synthesis-specification.md`, `ui-designer/style-guide.md`
- **Makes design tokens available for task generation**

View File

@@ -2,7 +2,7 @@
<div align="center">
[![Version](https://img.shields.io/badge/version-v3.5.0-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![Version](https://img.shields.io/badge/version-v4.2.1-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey.svg)]()
[![MCP工具](https://img.shields.io/badge/🔧_MCP工具-实验性-orange.svg)](https://github.com/modelcontextprotocol)
@@ -15,16 +15,13 @@
**Claude Code Workflow (CCW)** 是一个新一代的多智能体自动化开发框架,通过智能工作流管理和自主执行来协调复杂的软件开发任务。
> **🎉 最新版本: v3.5.0** - UI 设计工作流与三重视觉分析。详见 [CHANGELOG.md](CHANGELOG.md)。
> **🎉 最新版本: v4.2.1** - UI 设计工作流文档重构。详见 [CHANGELOG.md](CHANGELOG.md)。
>
> **v3.5.0 版本新特性**:
> - 🎨 **UI 设计工作流**: 从风格提取到原型生成的完整设计精炼工作流
> - 👁️ **三重视觉分析**: 融合 Claude Code + Gemini + Codex 视觉能力进行综合风格提取
> - ⏸️ **交互式检查点**: 用户选择风格变体和原型确认的决策点
> - 🎯 **零智能体开销**: CLI 工具直接 bash 执行,移除不必要的智能体包装
> - 🎨 **风格自定义**: 通过 `--style-overrides` 参数支持运行时样式覆盖
> - 📦 **批量任务生成**: 使用 `--batch-plan` 为选定原型自动创建实现任务
> - 🔄 **半自主工作流**: 在关键设计决策点由用户驱动继续
> **v4.2.1 版本新特性**:
> - 📚 **文档优化**: 文件大小减少 15-20%,同时保留所有功能
> - 🎯 **更清晰的结构**: 合并重复概念,优化内容组织
> - **改进的可维护性**: 更好的内容分离和一致的格式模式
> - 📖 **零功能损失**: 保留所有特性、工作流和技术细节
---
@@ -253,21 +250,27 @@ MCP (模型上下文协议) 工具提供高级代码库分析。**推荐安装**
**阶段 2UI 设计精炼** *(UI 密集型项目可选)*
```bash
# 从参考图像中提取设计风格并生成原型
/workflow:design:auto --session WFS-auth --images "design-refs/*.png" --pages "login,register" --batch-plan
# 矩阵探索模式 - 多个风格×布局变体v4.2.1+
/workflow:ui-design:explore-auto --prompt "现代博客:首页,文章,作者" --style-variants 3 --layout-variants 2
# 快速模仿模式 - 单一设计快速复制v4.2.1+
/workflow:ui-design:imitate-auto --images "refs/design.png" --pages "dashboard,settings"
# 与会话集成
/workflow:ui-design:explore-auto --session WFS-auth --images "refs/*.png" --style-variants 2 --layout-variants 3
# 或者运行单独的设计阶段
/workflow:design:style-extract --session WFS-auth --images "refs/*.png"
/workflow:design:style-consolidate --session WFS-auth --variants "variant-1,variant-3"
/workflow:design:ui-generate --session WFS-auth --pages "login,register" --variants 2
/workflow:ui-design:extract --images "refs/*.png" --variants 3
/workflow:ui-design:consolidate --variants "variant-1,variant-3"
/workflow:ui-design:generate --pages "dashboard,auth" --style-variants 2 --layout-variants 2
# 预览生成的原型(新功能!)
# 选项1在浏览器中打开 .workflow/WFS-auth/.design/prototypes/index.html
# 预览生成的原型
# 选项1在浏览器中打开 .workflow/WFS-auth/.design/prototypes/compare.html
# 选项2启动本地服务器
cd .workflow/WFS-auth/.design/prototypes && python -m http.server 8080
# 访问 http://localhost:8080 获取交互式预览和对比工具
/workflow:design:design-update --session WFS-auth --selected-prototypes "login-variant-1,register-variant-2"
/workflow:ui-design:update --session WFS-auth --selected-prototypes "dashboard-s1-l2"
```
**阶段 3行动规划**
@@ -361,11 +364,12 @@ cd .workflow/WFS-auth/.design/prototypes && python -m http.server 8080
|---|---|
| `/workflow:session:*` | 管理开发会话(`start`, `pause`, `resume`, `list`, `switch`, `complete`)。 |
| `/workflow:brainstorm:*` | 使用基于角色的智能体进行多视角规划。 |
| `/workflow:design:auto` | **新增** 带交互式检查点的半自主 UI 设计工作流,用于风格和原型选择。 |
| `/workflow:design:style-extract` | **新增** 使用三重视觉分析Claude + Gemini + Codex从参考图像提取设计风格。 |
| `/workflow:design:style-consolidate` | **新增** 将选定的风格变体整合为经过验证的设计令牌和风格指南。 |
| `/workflow:design:ui-generate` | **新增** 生成基于令牌的 HTML/CSS 原型,支持可选的风格覆盖。 |
| `/workflow:design:design-update` | **新增** 将最终确定的设计系统集成到头脑风暴产物中。 |
| `/workflow:ui-design:explore-auto` | **v4.2.1** 矩阵探索模式 - 生成多个风格×布局变体,全面探索设计方向。 |
| `/workflow:ui-design:imitate-auto` | **v4.2.1** 快速模仿模式 - 单一设计快速复制,自动截图和直接令牌提取。 |
| `/workflow:ui-design:extract` | **v4.2.1** 使用 Claude 原生分析从图像/文本提取设计。单次生成变体。 |
| `/workflow:ui-design:consolidate` | **v4.2.1** 使用 Claude 合成将风格变体整合为经过验证的设计令牌。 |
| `/workflow:ui-design:generate` | **v4.2.1** 生成矩阵模式(风格×布局组合)的令牌驱动 HTML/CSS 原型。 |
| `/workflow:ui-design:update` | **v4.2.1** 将最终确定的设计系统集成到头脑风暴产物中。 |
| `/workflow:plan` | 从描述创建详细、可执行的计划。 |
| `/workflow:tdd-plan` | 创建 TDD 工作流6 阶段),包含测试覆盖分析和 Red-Green-Refactor 循环。 |
| `/workflow:execute` | 自主执行当前的工作流计划。 |
@@ -377,50 +381,71 @@ cd .workflow/WFS-auth/.design/prototypes && python -m http.server 8080
| `/workflow:tools:test-concept-enhanced` | 使用 Gemini 生成测试策略和需求分析。 |
| `/workflow:tools:test-task-generate` | 生成测试任务 JSON包含 test-fix-cycle 规范。 |
### **UI 设计工作流命令 (`/workflow:design:*`)** *(v3.5.0+)*
### **UI 设计工作流命令 (`/workflow:ui-design:*`)** *(v4.2.1)*
设计工作流系统提供从风格提取到原型生成的完整 UI 设计精炼,配备交互式预览工具
设计工作流系统提供完整 UI 设计精炼,具备**纯 Claude 执行**、**智能页面推断**和**零外部依赖**
#### 核心命令
**`/workflow:design:auto`** - 完整工作流编排器
**`/workflow:ui-design:explore-auto`** - 矩阵探索模式
```bash
# 带用户检查点的半自主工作流
/workflow:design:auto --session WFS-auth --images "refs/*.png" --pages "login,register"
/workflow:design:auto --session WFS-dash --images "refs/*.jpg" --pages "dashboard" --variants 3 --batch-plan
```
- **检查点**: 用户选择风格变体阶段1和确认原型阶段3
- **可选**: `--batch-plan` 用于自动任务生成
# 全面探索 - 多个风格×布局变体
/workflow:ui-design:explore-auto --prompt "现代博客:首页,文章,作者" --style-variants 3 --layout-variants 2
**`/workflow:design:style-extract`** - 三重视觉风格分析
# 与图像和会话集成
/workflow:ui-design:explore-auto --session WFS-auth --images "refs/*.png" --style-variants 2 --layout-variants 3
# 纯文本模式,带页面推断
/workflow:ui-design:explore-auto --prompt "电商:首页,产品,购物车" --style-variants 2 --layout-variants 2
```
- **🎯 矩阵模式**: 生成所有风格×布局组合
- **📊 全面探索**: 比较多个设计方向
- **🔍 交互式对比**: 带视口控制的并排比较
- **✅ 跨页面验证**: 多页面设计的自动一致性检查
- **⚡ 批量选择**: 按风格或布局快速选择
**`/workflow:ui-design:imitate-auto`** - 快速模仿模式
```bash
# 从参考图像提取设计
/workflow:design:style-extract --session WFS-auth --images "design-refs/*.png"
```
- **视觉来源**: Claude Code + Gemini + Codex
- **输出**: 用于用户选择的风格变体卡片
# 快速单一设计复制
/workflow:ui-design:imitate-auto --images "refs/design.png" --pages "dashboard,settings"
**`/workflow:design:style-consolidate`** - 验证和合并令牌
# 与会话集成
/workflow:ui-design:imitate-auto --session WFS-auth --images "refs/ui.png" --pages "home,product"
# 从 URL 自动截图(需要 Playwright
/workflow:ui-design:imitate-auto --url "https://example.com" --pages "landing"
```
- **⚡ 速度优化**: 比 explore-auto 快 5-10 倍
- **📸 自动截图**: 使用 Playwright/Chrome 自动捕获 URL 截图
- **🎯 直接提取**: 跳过变体选择,直接进入实现
- **🔧 单一设计聚焦**: 最适合快速复制现有设计
**`/workflow:ui-design:style-consolidate`** - 验证和合并令牌
```bash
# 整合选定的风格变体
/workflow:design:style-consolidate --session WFS-auth --variants "variant-1,variant-3"
/workflow:ui-design:style-consolidate --session WFS-auth --variants "variant-1,variant-3"
```
- **功能**: WCAG AA 验证、OKLCH 颜色、W3C 令牌格式
- **输出**: `design-tokens.json``style-guide.md``tailwind.config.js`
**`/workflow:design:ui-generate`** - 生成 HTML/CSS 原型
**`/workflow:ui-design:generate`** - 生成 HTML/CSS 原型
```bash
# 生成带预览工具的原型
/workflow:design:ui-generate --session WFS-auth --pages "login,register" --variants 2
/workflow:design:ui-generate --session WFS-auth --pages "dashboard" --style-overrides "custom.json"
```
- **🆕 预览文件**: `index.html`(导航)、`compare.html`(并排对比)、`PREVIEW.md`(说明)
- **功能**: 令牌驱动的 CSS、语义化 HTML5、ARIA 属性、响应式设计
# 矩阵模式 - 风格×布局组合
/workflow:ui-design:generate --pages "dashboard,auth" --style-variants 2 --layout-variants 3
**`/workflow:design:design-update`** - 集成设计系统
# 单页面多变体
/workflow:ui-design:generate --pages "home" --style-variants 3 --layout-variants 2
```
- **🎯 矩阵生成**: 创建所有风格×布局组合
- **📊 多页面支持**: 跨页面一致的设计系统
- **✅ 一致性验证**: 自动跨页面一致性报告v4.2.0+
- **🔍 交互式预览**: `compare.html` 并排比较
- **📋 批量选择**: 按风格或布局过滤器快速选择
**`/workflow:ui-design:update`** - 集成设计系统
```bash
# 使用设计系统更新头脑风暴产物
/workflow:design:design-update --session WFS-auth --selected-prototypes "login-variant-1,register-variant-2"
/workflow:ui-design:update --session WFS-auth --selected-prototypes "dashboard-s1-l2"
```
- **更新**: `synthesis-specification.md``ui-designer/style-guide.md`
- **使设计令牌可用于任务生成**

View File

@@ -1,252 +0,0 @@
# v3.2.3 - Version Management System
## 🎉 Release Date
2025-10-03
## ✨ Overview
This release introduces a comprehensive version management and upgrade notification system, making it easy to track your Claude Code Workflow installation and stay up-to-date with the latest releases.
## 🆕 New Features
### `/version` Command
A powerful new command that provides complete version information and automatic update checking:
**Features:**
- 📊 **Version Display**: Shows both local and global installation versions
- 🌐 **GitHub Integration**: Fetches latest stable release and development commits
- 🔄 **Smart Comparison**: Automatically compares installed version with latest available
- 💡 **Upgrade Recommendations**: Provides installation commands for easy upgrading
-**Fast Execution**: 30-second timeout for network calls, graceful offline handling
**Usage:**
```bash
/version
```
**Example Output:**
```
Installation Status:
- Local: No project-specific installation
- Global: ✅ Installed at ~/.claude
- Version: v3.2.3
- Installed: 2025-10-03T05:01:34Z
Latest Releases:
- Stable: v3.2.3 (2025-10-03T04:10:08Z)
- v3.2.3: Version Management System
- Latest Commit: c5c36a2 (2025-10-03T05:00:06Z)
- fix: Optimize version command API calls and data extraction
Status: ✅ You are on the latest stable version (3.2.3)
```
### Version Tracking System
**Version Files:**
- `.claude/version.json` - Local project installation tracking
- `~/.claude/version.json` - Global installation tracking
**Tracked Information:**
```json
{
"version": "v3.2.3",
"installation_mode": "Global",
"installation_path": "C:\\Users\\username\\.claude",
"source_branch": "main",
"installation_date_utc": "2025-10-03T05:01:34Z"
}
```
### GitHub API Integration
**Endpoints Used:**
- **Latest Release**: `https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest`
- Extracts: tag_name, release name, published date
- **Latest Commit**: `https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/main`
- Extracts: commit SHA, message, author date
**Network Handling:**
- 30-second timeout for slow connections
- Graceful error handling for offline scenarios
- No external dependencies (uses curl and grep/sed)
## 🔄 What's Changed
### Documentation Updates
**Updated Files:**
-`CHANGELOG.md` - Added comprehensive v3.2.3 release notes
-`README.md` - Updated version badge to v3.2.3, added `/version` command
-`README_CN.md` - Updated version badge and command reference (Chinese)
-`.claude/commands/version.md` - Complete implementation guide
**Version References:**
- All version badges updated from v3.2.2 to v3.2.3
- "What's New" sections updated with v3.2.3 features
- Command reference tables include `/version` command
### Installation Scripts Enhancement
**Future Enhancement** (for next release):
- Installation scripts will automatically create `version.json` files
- Track installation mode (local vs global)
- Record installation timestamp
- Support version tracking for both stable and development installations
## 📋 Version Comparison Scenarios
### Scenario 1: Up to Date
```
✅ You are on the latest stable version (3.2.3)
```
### Scenario 2: Upgrade Available
```
⬆️ A newer stable version is available: v3.2.4
Your version: 3.2.3
To upgrade:
PowerShell: iex (iwr -useb https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.ps1)
Bash: bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.sh)
```
### Scenario 3: Development Version
```
✨ You are running a development version (3.3.0-dev)
This is newer than the latest stable release (v3.2.3)
```
## 🛠️ Technical Details
### Implementation Highlights
**Simple Bash Commands:**
- No jq dependency required (uses grep/sed for JSON parsing)
- Cross-platform compatible (Windows Git Bash, Linux, macOS)
- Version comparison using `sort -V` for semantic versioning
- Direct API access using curl with error suppression
**Command Structure:**
```bash
# Check local version
test -f ./.claude/version.json && cat ./.claude/version.json
# Check global version
test -f ~/.claude/version.json && cat ~/.claude/version.json
# Fetch latest release (with timeout)
curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest" 2>/dev/null
# Extract version
grep -o '"tag_name": *"[^"]*"' | cut -d'"' -f4
# Compare versions
printf "%s\n%s" "3.2.2" "3.2.3" | sort -V | tail -n 1
```
## 📊 Benefits
### User Experience
- 🔍 **Quick version check** with single command
- 📊 **Comprehensive information** display (local, global, stable, dev)
- 🔄 **Automatic upgrade notifications** when new versions available
- 📈 **Development version tracking** for cutting-edge features
- 🌐 **GitHub integration** for latest updates
### DevOps
- 📁 **Version tracking** in both local and global installations
- 🕐 **Installation timestamp** for audit trails
- 🔀 **Support for both stable and development** branches
-**Fast execution** with 30-second network timeout
- 🛡️ **Graceful error handling** for offline scenarios
## 🔗 Related Commands
- `/cli:cli-init` - Initialize CLI tool configurations
- `/workflow:session:list` - List workflow sessions
- `/update-memory-full` - Update project documentation
## 📦 Installation
### Fresh Installation
**Windows (PowerShell):**
```powershell
iex (iwr -useb https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.ps1)
```
**Linux/macOS (Bash):**
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.sh)
```
### Upgrade from v3.2.2
Use the same installation commands above. The installer will automatically:
1. Detect your existing installation
2. Back up current files (if using `-BackupAll`)
3. Update to v3.2.3
4. Create/update `version.json` files
## 🐛 Bug Fixes
- Fixed commit message extraction to handle JSON escape sequences
- Improved API endpoint from `/branches/main` to `/commits/main` for reliable commit info
- Added 30-second timeout to all network calls for slow connections
- Enhanced release name and published date extraction
## 📚 Documentation
### New Documentation
- `.claude/commands/version.md` - Complete command implementation guide
- API endpoints and usage
- Timeout configuration
- Error handling scenarios
- Simple bash command examples
### Updated Documentation
- `CHANGELOG.md` - v3.2.3 release notes
- `README.md` - Version badge and command reference
- `README_CN.md` - Chinese version updates
## 🙏 Credits
This release includes contributions and improvements based on:
- GitHub API integration for version detection
- Cross-platform bash command compatibility
- User feedback on installation and upgrade processes
## 📝 Notes
- **Backward Compatible**: All existing commands and workflows continue to work
- **No Breaking Changes**: This is a minor release with new features only
- **Optional Feature**: `/version` command is entirely optional, existing workflows unaffected
## 🚀 What's Next
**Planned for v3.2.4:**
- Enhanced installation script to auto-create version.json
- Version tracking in all installation modes
- Automatic version detection during installation
**Future Enhancements:**
- Auto-update functionality (opt-in)
- Version comparison in workflow sessions
- Release notes display in CLI
---
**Full Changelog**: [v3.2.2...v3.2.3](https://github.com/catlog22/Claude-Code-Workflow/compare/v3.2.2...v3.2.3)
**Installation:**
```bash
# One-line install (recommended)
bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.sh)
# Or use specific version tag
git clone -b v3.2.3 https://github.com/catlog22/Claude-Code-Workflow.git
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)

231
ui-instantiate-analysis.md Normal file
View File

@@ -0,0 +1,231 @@
# UI原型实例化脚本分析报告
## 问题现象
在执行 `ui-instantiate-prototypes.sh` 脚本时,生成了 `style-4` 的原型文件(如 `login-style-4-layout-1.html`),但实际上 `style-consolidation` 目录下只有3个样式目录style-1, style-2, style-3
## 调查结果
### 1. 目录结构验证
```bash
# 实际存在的样式目录
.workflow/.design/run-20251009-210559/style-consolidation/
├── style-1/
├── style-2/
└── style-3/
# 生成的原型文件包含
prototypes/login-style-4-layout-1.html ❌ 引用不存在的 ../style-consolidation/style-4/tokens.css
prototypes/sidebar-style-4-layout-1.html ❌ 引用不存在的 ../style-consolidation/style-4/tokens.css
```
### 2. consolidation-report.json 确认
```json
{
"variant_count": 3, // 明确显示只有3个变体
"variants": [
{"id": "style-1"},
{"id": "style-2"},
{"id": "style-3"}
]
}
```
### 3. PREVIEW.md 显示异常
```markdown
- **Style Variants:** 4 ⚠️ 与实际不符
- **Total Prototypes:** 24 (4 × 3 × 2 = 24)
```
### 4. 脚本auto_detect_style_variants()函数
```bash
# 位置:.claude/scripts/ui-instantiate-prototypes.sh 第52-71行
auto_detect_style_variants() {
local base_path="$1"
local style_dir="$base_path/../style-consolidation"
# 统计style-*目录数量
local count=$(find "$style_dir" -maxdepth 1 -type d -name "style-*" | wc -l)
echo "$count"
}
```
**验证测试**
```bash
cd .workflow/.design/run-20251009-210559/style-consolidation
find . -maxdepth 1 -type d -name "style-*" | wc -l
# 输出3 ✅ 函数逻辑正确
```
## 根本原因分析
### ⚠️ 参数覆盖问题
脚本虽然有自动检测功能,但**允许手动参数覆盖**
```bash
# 自动检测模式(正确)
ui-instantiate-prototypes.sh prototypes/ # 会自动检测到3个样式
# 手动模式(错误来源)
ui-instantiate-prototypes.sh prototypes/ "login,sidebar" 4 3 # 强制指定4个样式变体 ❌
```
### 🔍 实际调用场景
根据工作流命令 `.claude/commands/workflow/ui-design/generate.md` 第79-82行
```bash
# Phase 1: Path Resolution & Context Loading
style_variants = --style-variants OR 3 # 默认为3
```
**推断的问题来源**
1. 工作流命令被手动调用时,传入了 `--style-variants 4`
2. 这个参数被直接传递给 `ui-instantiate-prototypes.sh` 脚本
3. 脚本没有验证参数值与实际目录数量是否匹配
4. 导致生成了引用不存在的style-4目录的HTML文件
## 问题影响
### 生成的style-4文件问题
所有 `*-style-4-*.html` 文件都会出现CSS加载失败
```html
<!-- 文件中的CSS引用 -->
<link rel="stylesheet" href="../style-consolidation/style-4/tokens.css">
<!-- ❌ 该路径不存在,导致样式无法加载 -->
```
### 影响范围
- `login-style-4-layout-{1,2,3}.html` - 3个文件 ❌
- `sidebar-style-4-layout-{1,2,3}.html` - 3个文件 ❌
- 对应的 `*-notes.md` 文件 - 6个说明文件内容错误
## 解决方案
### 方案1重新生成推荐
```bash
cd .workflow/.design/run-20251009-210559/prototypes
# 删除错误的style-4文件
rm -f *-style-4-*
# 重新运行脚本(使用自动检测)
~/.claude/scripts/ui-instantiate-prototypes.sh . --session-id run-20251009-210559
```
### 方案2脚本增强预防
`ui-instantiate-prototypes.sh` 中添加参数验证:
```bash
# 在第239行之后添加
# Validate STYLE_VARIANTS matches actual directories
actual_styles=$(find "$BASE_PATH/../style-consolidation" -maxdepth 1 -type d -name "style-*" | wc -l)
if [ "$STYLE_VARIANTS" -gt "$actual_styles" ]; then
log_warning "Requested $STYLE_VARIANTS style variants, but only found $actual_styles directories"
log_info "Auto-correcting to $actual_styles style variants"
STYLE_VARIANTS=$actual_styles
fi
```
### 方案3工作流命令修复
`.claude/commands/workflow/ui-design/generate.md` 中添加验证:
```bash
# Phase 1: Path Resolution & Context Loading (第79-82行之后)
style_variants = --style-variants OR 3 # Default to 3
# 添加验证逻辑
actual_styles = count_directories({base_path}/style-consolidation/style-*)
IF style_variants > actual_styles:
WARN: "Requested {style_variants} styles, but only {actual_styles} exist"
REPORT: "Auto-correcting to {actual_styles} style variants"
style_variants = actual_styles
VALIDATE: 1 <= style_variants <= 5
```
## 预防措施
1. **优先使用自动检测**
```bash
# ✅ 推荐:让脚本自动检测
ui-instantiate-prototypes.sh prototypes/
# ⚠️ 谨慎:手动指定参数(需确保正确)
ui-instantiate-prototypes.sh prototypes/ "login,sidebar" 3 3
```
2. **验证consolidation输出**
```bash
# 生成原型前,先确认样式数量
jq '.variant_count' style-consolidation/consolidation-report.json
```
3. **使用工作流命令**
```bash
# 工作流命令会自动处理参数验证
/workflow:ui-design:generate --base-path ".workflow/.design/run-xxx"
```
## 技术细节
### 自动检测逻辑流程
```mermaid
graph TD
A[调用脚本] --> B{检查参数数量}
B -->|1个参数| C[自动检测模式]
B -->|4个参数| D[手动模式]
C --> E[检测style目录]
D --> F[使用传入参数]
E --> G[验证目录存在]
F --> G
G -->|不匹配| H[⚠️ 生成错误文件]
G -->|匹配| I[✅ 正常生成]
```
### find命令行为
```bash
# 正确的检测命令
find style-consolidation -maxdepth 1 -type d -name "style-*"
# 输出:
# style-consolidation/style-1
# style-consolidation/style-2
# style-consolidation/style-3
# wc -l 统计行数 = 3 ✅
# 注意style-extraction 不会被匹配(它在父目录)
# find . -maxdepth 1 -type d -name "style-*"
# 只会在当前目录搜索,不会递归到子目录
```
## 总结
### 问题根源
✅ **确认**:脚本被手动调用时传入了错误的 `--style-variants 4` 参数但实际只有3个样式目录存在。
### 脚本行为
✅ **确认**`auto_detect_style_variants()` 函数逻辑正确能够正确检测到3个样式目录。
### 修复优先级
1. 🔴 **立即**删除错误的style-4文件重新生成
2. 🟡 **短期**:在脚本中添加参数验证逻辑
3. 🟢 **长期**:在工作流命令中添加防护验证
### 最佳实践
- 优先使用脚本的自动检测模式
- 在手动指定参数前,先验证 `consolidation-report.json`
- 使用工作流命令而非直接调用脚本

View File

@@ -0,0 +1,425 @@
# UI设计工作流参数清晰度分析报告
## 📋 执行摘要
**问题来源**:用户手动调用 `/workflow:ui-design:generate` 时传入了 `--style-variants 4`但实际只有3个样式目录存在导致生成了引用不存在CSS文件的 `style-4` 原型。
**根本原因**:工作流命令链中参数命名不一致、验证缺失、文档说明不清晰。
## 🔍 关键发现
### 1. 参数命名不一致
| 命令 | 参数名称 | 默认值 | 说明 |
|------|---------|--------|------|
| `extract` | `--variants` | 1 | ⚠️ 未在文档中明确说明默认值 |
| `consolidate` | `--variants` | 所有变体 | ⚠️ 与extract同名但语义不同 |
| `generate` | `--style-variants` | 3 | ⚠️ 名称不一致,默认值说明不清晰 |
**问题**
- `extract``consolidate` 使用 `--variants`,但 `generate` 使用 `--style-variants`
- `--variants` 在两个命令中含义不同:
- `extract`:生成多少个变体
- `consolidate`:处理多少个变体
### 2. 命名转换混淆
```
extract 输出 → consolidate 处理 → generate 使用
variant-1 → style-1/ → login-style-1-layout-1.html
variant-2 → style-2/ → login-style-2-layout-1.html
variant-3 → style-3/ → login-style-3-layout-1.html
```
**问题**
- `variant-N``style-N` 的转换没有文档说明
- 增加了用户的认知负担
- 容易造成混淆和错误
### 3. 验证缺失
#### ❌ 当前状态generate.md 第79-82行
```bash
# Phase 1: Path Resolution & Context Loading
style_variants = --style-variants OR 3 # Default to 3
VALIDATE: 1 <= style_variants <= 5
```
**问题**
- ✅ 验证范围1-5
- ❌ 不验证是否匹配实际目录数量
- ❌ 允许传入 `4` 但实际只有 `3` 个目录
#### ✅ 应有的验证
```bash
style_variants = --style-variants OR 3
actual_styles = count_directories({base_path}/style-consolidation/style-*)
IF style_variants > actual_styles:
WARN: "Requested {style_variants} styles, but only {actual_styles} exist"
REPORT: "Auto-correcting to {actual_styles} style variants"
style_variants = actual_styles
VALIDATE: 1 <= style_variants <= actual_styles
```
### 4. 文档清晰度问题
#### extract.md
**问题点**
- ⚠️ 默认值 `1` 未在 `usage``argument-hint` 中说明
- ⚠️ 输出的 `variant-N` 命名未解释后续转换为 `style-N`
**当前文档**第580行附近
```
"id": "variant-2" # 缺少说明这会成为 style-2 目录
```
#### consolidate.md
**问题点**
- ⚠️ `--variants``extract` 同名但语义不同
- ⚠️ 默认行为(处理所有变体)不够突出
- ⚠️ `variant-N``style-N` 转换未文档化
#### generate.md
**问题点**
- ⚠️ `--style-variants` 名称与前置命令不一致
- ⚠️ 默认值 `3` 的来源和意义不清晰
- ⚠️ 自动检测机制未说明
- ❌ 手动覆盖无验证
**当前文档**第79-82行
```bash
style_variants = --style-variants OR 3 # Default to 3
VALIDATE: 1 <= style_variants <= 5
```
## 💡 改进方案
### 方案1代码层面改进推荐
#### 1.1 统一参数命名
```diff
# extract.md
- usage: /workflow:ui-design:extract [--variants <count>]
+ usage: /workflow:ui-design:extract [--style-variants <count>]
# consolidate.md
- usage: /workflow:ui-design:consolidate [--variants <count>]
+ usage: /workflow:ui-design:consolidate [--style-variants <count>]
# generate.md (保持不变)
usage: /workflow:ui-design:generate [--style-variants <count>]
```
**优点**
- ✅ 全链路参数名称统一
- ✅ 语义清晰style-variants
- ✅ 降低混淆风险
#### 1.2 添加验证逻辑(关键)
##### generate.md 改进
```bash
# Phase 1: Path Resolution & Context Loading
style_variants = --style-variants OR 3 # Default to 3
# 🆕 添加验证逻辑
actual_styles = count_directories({base_path}/style-consolidation/style-*)
IF actual_styles == 0:
ERROR: "No style directories found in {base_path}/style-consolidation/"
SUGGEST: "Run /workflow:ui-design:consolidate first"
EXIT 1
IF style_variants > actual_styles:
WARN: "⚠️ Requested {style_variants} style variants, but only {actual_styles} directories exist"
REPORT: " Auto-correcting to {actual_styles} style variants"
REPORT: " Available styles: {list_directories(style-consolidation/style-*)}"
style_variants = actual_styles
VALIDATE: 1 <= style_variants <= actual_styles
```
##### ui-instantiate-prototypes.sh 改进
在脚本第239行之后添加
```bash
# Validate STYLE_VARIANTS matches actual directories
if [ "$STYLE_VARIANTS" -gt 0 ]; then
actual_styles=$(find "$BASE_PATH/../style-consolidation" -maxdepth 1 -type d -name "style-*" 2>/dev/null | wc -l)
if [ "$actual_styles" -eq 0 ]; then
log_error "No style directories found in style-consolidation/"
log_info "Run /workflow:ui-design:consolidate first"
exit 1
fi
if [ "$STYLE_VARIANTS" -gt "$actual_styles" ]; then
log_warning "Requested $STYLE_VARIANTS style variants, but only found $actual_styles directories"
log_info "Auto-correcting to $actual_styles style variants"
STYLE_VARIANTS=$actual_styles
fi
fi
```
#### 1.3 统一命名约定
##### extract.md 改进
修改输出格式第580行附近
```diff
# style-cards.json 格式
{
"style_cards": [
{
- "id": "variant-1",
+ "id": "style-1",
"name": "Modern Minimalist",
...
}
]
}
```
### 方案2文档层面改进
#### 2.1 extract.md 文档改进
```markdown
## Parameters
- `--style-variants <count>`: Number of style variants to extract. **Default: 1**
- Range: 1-5
- Each variant will become an independent design system (style-1, style-2, etc.)
- Output IDs use `style-N` format for consistency across the workflow
## Output Format
style-cards.json uses `style-N` IDs that directly correspond to directory names
created by the consolidate command:
- `style-1``style-consolidation/style-1/`
- `style-2``style-consolidation/style-2/`
```
#### 2.2 consolidate.md 文档改进
```markdown
## Parameters
- `--style-variants <count>`: Number of style variants to process from style-cards.json.
**Default: all available variants**
- Processes the first N variants from the style-cards array
- Creates separate `style-{n}` directories for each variant
- Range: 1 to count available in style-cards.json
## Naming Convention
Variants from extraction are materialized into style directories:
- Input: `style-cards.json` with `style-1`, `style-2`, `style-3`
- Output: `style-consolidation/style-1/`, `style-2/`, `style-3/` directories
```
#### 2.3 generate.md 文档改进
```markdown
## Parameters
- `--style-variants <count>`: Number of style variants to generate prototypes for.
**Default: 3** (can be overridden)
- Range: 1-5
- ⚠️ **IMPORTANT**: This value MUST match the number of style-* directories in style-consolidation/
- If mismatched, the command will auto-correct to the actual directory count
- Use auto-detection (omit parameter) for safety
## Auto-Detection vs Manual Override
The command uses intelligent auto-detection:
1. **Auto-Detection** (Recommended):
```bash
/workflow:ui-design:generate --base-path ".workflow/.design/run-xxx"
# Automatically counts style-1/, style-2/, style-3/ → uses 3
```
2. **Manual Override** (Use with caution):
```bash
/workflow:ui-design:generate --style-variants 4
# If only 3 styles exist, auto-corrects to 3 with warning
```
3. **Safety Check**:
- Command validates against actual `style-consolidation/style-*` directories
- Prevents generation of prototypes referencing non-existent styles
- Displays warning and auto-corrects if mismatch detected
```
### 方案3用户指南改进
创建 `.claude/commands/workflow/ui-design/README.md`
```markdown
# UI Design Workflow Parameter Guide
## Style Variant Count Flow
### 1. Extract Phase
```bash
/workflow:ui-design:extract --style-variants 3
# Generates: style-cards.json with 3 style variants (style-1, style-2, style-3)
```
### 2. Consolidate Phase
```bash
/workflow:ui-design:consolidate --style-variants 3
# Creates: style-consolidation/style-1/, style-2/, style-3/
```
### 3. Generate Phase
```bash
# ✅ Recommended: Let it auto-detect
/workflow:ui-design:generate --base-path ".workflow/.design/run-xxx"
# ⚠️ Manual: Must match consolidation output
/workflow:ui-design:generate --style-variants 3
```
## ⚠️ Common Mistakes
### Mistake 1: Mismatched Counts
```bash
# ❌ Wrong: Request 4 styles when only 3 exist
/workflow:ui-design:generate --style-variants 4
# Only 3 directories in style-consolidation/ → ERROR
# ✅ Correct: Omit parameter for auto-detection
/workflow:ui-design:generate --base-path ".workflow/.design/run-xxx"
```
### Mistake 2: Naming Confusion
```bash
# ❌ Don't confuse variant-N with style-N
# variant-N was old naming in style-cards.json
# style-N is the current standard across all commands
```
## 🎯 Best Practices
1. **Use auto-detection**: Omit `--style-variants` in generate command
2. **Verify consolidation**: Check `consolidation-report.json` before generating
3. **Use explore-auto**: Automated workflow prevents parameter mismatches
4. **Check directories**: `ls .workflow/.design/run-xxx/style-consolidation/`
```
## 🎯 实施优先级
### 🔴 高优先级(立即实施)
1. **generate.md 添加验证逻辑**
- 防止参数不匹配问题再次发生
- 影响范围:所有手动调用 generate 命令的场景
2. **ui-instantiate-prototypes.sh 添加验证**
- 脚本层面的最后防线
- 影响范围:所有原型生成操作
3. **文档说明默认值和验证机制**
- 降低用户误用风险
- 影响范围:所有新用户和手动操作场景
### 🟡 中优先级(短期改进)
4. **统一参数命名为 --style-variants**
- 提高一致性,减少混淆
- 影响范围:需要更新多个命令文件
5. **extract.md 统一使用 style-N 命名**
- 消除命名转换混淆
- 影响范围:需要更新 style-cards.json 格式
### 🟢 低优先级(长期优化)
6. **创建用户指南 README.md**
- 提供完整的参数使用指南
- 影响范围:文档层面,不影响功能
## 📊 改进效果预测
### 实施前
```
用户手动调用: /workflow:ui-design:generate --style-variants 4
实际目录数: 3
结果: ❌ 生成 login-style-4-layout-1.html 引用不存在的 CSS
```
### 实施后
```
用户手动调用: /workflow:ui-design:generate --style-variants 4
实际目录数: 3
验证检查:
⚠️ Requested 4 style variants, but only 3 directories exist
Available: style-1, style-2, style-3
Auto-correcting to 3 style variants
结果: ✅ 生成正确的 style-1, style-2, style-3 原型,避免错误
```
## 🔧 快速修复指南(针对当前问题)
### 立即修复生成的错误文件
```bash
cd .workflow/.design/run-20251009-210559/prototypes
# 删除错误的 style-4 文件
rm -f *-style-4-*
# 重新生成(使用自动检测)
~/.claude/scripts/ui-instantiate-prototypes.sh . --session-id run-20251009-210559
```
### 预防未来错误
```bash
# ✅ 推荐:使用自动检测
/workflow:ui-design:generate --base-path ".workflow/.design/run-xxx"
# ⚠️ 如果必须手动指定,先验证
jq '.variant_count' .workflow/.design/run-xxx/style-consolidation/consolidation-report.json
# 输出: 3
# 然后使用该数字
/workflow:ui-design:generate --style-variants 3
```
## 📝 总结
**核心问题**
- 参数命名不统一(`--variants` vs `--style-variants`
- 命名转换混淆(`variant-N``style-N`
- 验证缺失(不检查参数是否匹配实际目录)
- 文档不清晰(默认值、自动检测机制说明不足)
**关键改进**
1. ✅ 添加参数验证逻辑(防止不匹配)
2. ✅ 统一参数命名(提高一致性)
3. ✅ 完善文档说明(降低误用风险)
4. ✅ 提供清晰的用户指南
**预期效果**
- 🔒 杜绝参数不匹配问题
- 📈 提高工作流鲁棒性
- 🎓 降低用户学习成本
- 🚀 提升整体用户体验