refactor(ui-design): convert codify-style to orchestrator pattern with enhanced safety

Refactor style codification workflow into orchestrator pattern with three specialized commands:

Changes:
- Refactor codify-style.md as pure orchestrator coordinating sub-commands
  • Delegates to import-from-code for style extraction
  • Calls reference-page-generator for packaging
  • Creates temporary design run as intermediate storage
  • Added --overwrite flag with package protection logic
  • Improved component counting using jq with grep fallback

- Create reference-page-generator.md for multi-component reference pages
  • Generates interactive preview with all components
  • Creates design tokens, style guide, and component patterns
  • Package validation to prevent invalid directory overwrites
  • Outputs to .workflow/reference_style/{package-name}/

- Create style-skill-memory.md for SKILL memory generation
  • Converts style reference packages to SKILL memory
  • Progressive loading levels (0-3) for efficient token usage
  • Intelligent description generation from metadata
  • --regenerate flag support

Improvements based on Gemini analysis:
- Overwrite protection in codify-style prevents accidental data loss
- Reliable component counting via jq JSON parsing (grep fallback)
- Package validation in reference-page-generator ensures data integrity

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
catlog22
2025-11-11 14:30:40 +08:00
parent bc959b1a0f
commit feae69470e
3 changed files with 1669 additions and 0 deletions

View File

@@ -0,0 +1,534 @@
---
name: memory:style-skill-memory
description: Generate SKILL memory package from style reference for easy loading and consistent design system usage
argument-hint: "[package-name] [--regenerate]"
allowed-tools: Bash,Read,Write,TodoWrite
auto-continue: true
---
# Memory: Style SKILL Memory Generator
## Overview
**Purpose**: Convert style reference package into SKILL memory for easy loading and context management.
**Input**: Style reference package at `.workflow/reference_style/{package-name}/`
**Output**: SKILL memory index at `.claude/skills/style-{package-name}/SKILL.md`
**Use Case**: Load design system context when working with UI components, analyzing design patterns, or implementing style guidelines.
---
## Usage
### Command Syntax
```bash
/memory:style-skill-memory [package-name] [--regenerate]
# Arguments
package-name Style reference package name (required)
--regenerate Force regenerate SKILL.md even if it exists (optional)
```
### Usage Examples
```bash
# Generate SKILL memory for package
/memory:style-skill-memory main-app-style-v1
# Regenerate SKILL memory
/memory:style-skill-memory main-app-style-v1 --regenerate
# Package name from current directory or default
/memory:style-skill-memory
```
---
## Execution Process
### Phase 1: Validate Package
**Purpose**: Check if style reference package exists
**TodoWrite** (First Action):
```json
[
{"content": "Validate style reference package", "status": "in_progress", "activeForm": "Validating package"},
{"content": "Read package metadata and documentation", "status": "pending", "activeForm": "Reading metadata"},
{"content": "Generate SKILL.md with progressive loading", "status": "pending", "activeForm": "Generating SKILL.md"}
]
```
**Step 1: Parse Package Name**
```bash
# Get package name from argument or auto-detect
bash(echo "${package_name}" || basename "$(pwd)" | sed 's/^style-//')
```
Store result as `package_name`
**Step 2: Validate Package Exists**
```bash
bash(test -d .workflow/reference_style/${package_name} && echo "exists" || echo "missing")
```
**Error Handling**:
```javascript
if (package_not_exists) {
error("ERROR: Style reference package not found: ${package_name}")
error("HINT: Run '/workflow:ui-design:codify-style' first to create package")
error("Available packages:")
bash(ls -1 .workflow/reference_style/ 2>/dev/null || echo " (none)")
exit(1)
}
```
**Step 3: Check SKILL Already Exists**
```bash
bash(test -f .claude/skills/style-${package_name}/SKILL.md && echo "exists" || echo "missing")
```
**Decision Logic**:
```javascript
if (skill_exists && !regenerate_flag) {
echo("SKILL memory already exists for: ${package_name}")
echo("Use --regenerate to force regeneration")
exit(0)
}
if (regenerate_flag && skill_exists) {
echo("Regenerating SKILL memory for: ${package_name}")
}
```
**Summary Variables**:
- `PACKAGE_NAME`: Style reference package name
- `PACKAGE_DIR`: `.workflow/reference_style/${package_name}`
- `SKILL_DIR`: `.claude/skills/style-${package_name}`
- `REGENERATE`: `true` if --regenerate flag, `false` otherwise
**TodoWrite Update**:
```json
[
{"content": "Validate style reference package", "status": "completed", "activeForm": "Validating package"},
{"content": "Read package metadata and documentation", "status": "in_progress", "activeForm": "Reading metadata"}
]
```
**Next Action**: Continue to Phase 2
---
### Phase 2: Read Package Metadata
**Purpose**: Extract metadata and documentation for SKILL description generation
**Step 1: Read metadata.json**
```bash
Read(file_path=".workflow/reference_style/${package_name}/metadata.json")
```
**Extract Fields**:
- `packageName`
- `version`
- `generatedAt`
- `description`
- `source.design_run`
- `files` (count available files)
**Step 2: Read README.md**
```bash
Read(file_path=".workflow/reference_style/${package_name}/README.md")
```
**Extract Information**:
- Package overview
- Component catalog reference
- Design token categories
**Step 3: Count Components**
```bash
bash(test -f .workflow/reference_style/${package_name}/component-patterns.json && jq '.extraction_metadata.component_count' .workflow/reference_style/${package_name}/component-patterns.json 2>/dev/null || grep -c '"button"\|"input"\|"card"\|"badge"\|"alert"' .workflow/reference_style/${package_name}/component-patterns.json 2>/dev/null || echo 0)
```
Store result as `component_count`
**Step 4: Check Available Files**
```bash
bash(cd .workflow/reference_style/${package_name} && ls -1 *.json *.md *.html *.css 2>/dev/null | wc -l)
```
Store result as `file_count`
**Summary Data**:
- `COMPONENT_COUNT`: Number of components in catalog
- `FILE_COUNT`: Total files in package
- `VERSION`: Package version (from metadata.json)
- `DESCRIPTION`: Package description (from metadata.json)
**TodoWrite Update**:
```json
[
{"content": "Read package metadata and documentation", "status": "completed", "activeForm": "Reading metadata"},
{"content": "Generate SKILL.md with progressive loading", "status": "in_progress", "activeForm": "Generating SKILL.md"}
]
```
**Next Action**: Continue to Phase 3
---
### Phase 3: Generate SKILL.md
**Purpose**: Create SKILL memory index with progressive loading structure
**Step 1: Create SKILL Directory**
```bash
bash(mkdir -p .claude/skills/style-${package_name})
```
**Step 2: Generate Intelligent Description**
**Format**:
```
{Package Name} design system with {component_count} components and interactive preview (located at .workflow/reference_style/{package_name}). Load when working with UI components, design tokens, style guidelines, analyzing design patterns, or implementing visual consistency.
```
**Key Elements**:
- **Component Count**: Emphasize available component catalog
- **Path Reference**: Precise package location
- **Trigger Keywords**: UI components, design tokens, style guidelines, design patterns
- **Action Coverage**: working with, analyzing, implementing
**Example**:
```
main-app-style-v1 design system with 8 components and interactive preview (located at .workflow/reference_style/main-app-style-v1). Load when working with UI components, design tokens, style guidelines, analyzing design patterns, or implementing visual consistency.
```
**Step 3: Write SKILL.md** (Use Write tool)
```markdown
---
name: style-{package_name}
description: {intelligent description from Step 2}
version: {version from metadata.json}
---
# {Package Name} Style SKILL Package
## Documentation: `../../../.workflow/reference_style/{package_name}/`
## Package Overview
Style reference package with comprehensive design system documentation and interactive component preview.
**Package Details**:
- Package: {package_name}
- Version: {version}
- Components: {component_count}
- Files: {file_count}
- Generated: {generatedAt}
## Progressive Loading
### Level 0: Quick Start (~2K tokens)
Essential overview and package information.
**Files**:
- [README](../../../.workflow/reference_style/{package_name}/README.md) - Package overview and usage
- [Metadata](../../../.workflow/reference_style/{package_name}/metadata.json) - Source and package info
**Use when**: Quick reference, understanding package structure
---
### Level 1: Design Tokens (~8K tokens)
Complete design token system with style guidelines.
**Files**:
- [Design Tokens](../../../.workflow/reference_style/{package_name}/design-tokens.json) - Colors, typography, spacing, shadows
- [Style Guide](../../../.workflow/reference_style/{package_name}/style-guide.md) - Design philosophy and usage guidelines
**Use when**: Implementing UI, applying design tokens, style consistency
---
### Level 2: Components & Patterns (~15K tokens)
Full component catalog with patterns, variants, and states.
**Files**:
- Level 1 files
- [Component Patterns](../../../.workflow/reference_style/{package_name}/component-patterns.json) - Component catalog with DOM structures and CSS classes
- [Animation Tokens](../../../.workflow/reference_style/{package_name}/animation-tokens.json) - Animation durations, easing, transitions _(if available)_
**Use when**: Building components, implementing interactions, animation development
---
### Level 3: Complete Reference (~25K tokens)
Everything including interactive preview reference and full documentation.
**Files**:
- All Level 2 files
- [Preview HTML](../../../.workflow/reference_style/{package_name}/preview.html) - Interactive component showcase (reference only)
- [Preview CSS](../../../.workflow/reference_style/{package_name}/preview.css) - Showcase styling (reference only)
**Use when**: Comprehensive analysis, complete design system understanding, implementation validation
---
## Interactive Preview
**Location**: `.workflow/reference_style/{package_name}/preview.html`
**View in Browser**:
```bash
cd .workflow/reference_style/{package_name}
python -m http.server 8080
# Open http://localhost:8080/preview.html
```
**Features**:
- Color palette swatches with values
- Typography scale and combinations
- All components with variants and states
- Spacing, radius, shadow visual examples
- Interactive state demonstrations
- Usage code snippets
---
## Usage Guidelines
### Loading Levels
**Level 0** (2K): Quick reference when you need basic package info
```
Load Level 0 for package overview
```
**Level 1** (8K): Design token implementation
```
Load Level 1 for design tokens and style guide
```
**Level 2** (15K): Component development
```
Load Level 2 for component patterns and animations
```
**Level 3** (25K): Comprehensive understanding
```
Load Level 3 for complete design system reference
```
### Common Use Cases
**Implementing UI Components**:
- Load Level 2 for component patterns
- Reference component-patterns.json for DOM structure and CSS classes
- Apply design tokens from design-tokens.json
**Ensuring Style Consistency**:
- Load Level 1 for design tokens
- Use style-guide.md for design philosophy
- Check preview.html for visual reference
**Analyzing Design Patterns**:
- Load Level 3 for complete analysis
- Review component-patterns.json for architecture
- Check preview.html for implementation examples
**Animation Development**:
- Load Level 2 for animation tokens
- Reference animation-tokens.json for durations and easing
- Apply consistent timing and transitions
---
## Package Structure
```
.workflow/reference_style/{package_name}/
├── README.md # Package overview
├── metadata.json # Package metadata
├── design-tokens.json # Design token system
├── style-guide.md # Style guide documentation
├── component-patterns.json # Component catalog
├── animation-tokens.json # Animation tokens (optional)
├── preview.html # Interactive showcase
└── preview.css # Showcase styling
```
---
## Regeneration
To update this SKILL memory after package changes:
```bash
/memory:style-skill-memory {package_name} --regenerate
```
---
## Related Commands
**Generate Package**:
```bash
/workflow:ui-design:codify-style --source ./src --package-name {package_name}
```
**Update Package**:
Re-run codify-style with same package name to update extraction.
```
**Step 4: Verify SKILL.md Created**
```bash
bash(test -f .claude/skills/style-${package_name}/SKILL.md && echo "success" || echo "failed")
```
**TodoWrite Update**:
```json
[
{"content": "Validate style reference package", "status": "completed", "activeForm": "Validating package"},
{"content": "Read package metadata and documentation", "status": "completed", "activeForm": "Reading metadata"},
{"content": "Generate SKILL.md with progressive loading", "status": "completed", "activeForm": "Generating SKILL.md"}
]
```
**Final Action**: Report completion summary to user
---
## Completion Message
```
✅ SKILL memory generated successfully!
Package: {package_name}
SKILL Location: .claude/skills/style-{package_name}/SKILL.md
Package Details:
- Components: {component_count}
- Files: {file_count}
- Version: {version}
Progressive Loading Levels:
- Level 0: Quick Start (~2K tokens)
- Level 1: Design Tokens (~8K tokens)
- Level 2: Components & Patterns (~15K tokens)
- Level 3: Complete Reference (~25K tokens)
Usage:
Load design system context when working with:
- UI component implementation
- Design token application
- Style consistency validation
- Design pattern analysis
Preview:
Open interactive showcase:
file://{absolute_path}/.workflow/reference_style/{package_name}/preview.html
Next Steps:
1. Load appropriate level based on your task
2. Reference component-patterns.json for implementation
3. Use design-tokens.json for consistent styling
```
---
## Error Handling
### Common Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Package not found | Invalid package name or package doesn't exist | Run codify-style first to create package |
| SKILL already exists | SKILL.md already generated | Use --regenerate to force regeneration |
| Missing metadata.json | Incomplete package | Verify package integrity, re-run codify-style |
| Invalid metadata format | Corrupted metadata.json | Regenerate package with codify-style |
---
## Implementation Details
### Critical Rules
1. **Check Before Generate**: Verify package exists before attempting SKILL generation
2. **Respect Existing SKILL**: Don't overwrite unless --regenerate flag provided
3. **Progressive Loading**: Always include all 4 levels (0-3) with clear token estimates
4. **Intelligent Description**: Extract component count and key features from metadata
### SKILL Description Format
**Template**:
```
{package_name} design system with {component_count} components and interactive preview (located at .workflow/reference_style/{package_name}). Load when working with UI components, design tokens, style guidelines, analyzing design patterns, or implementing visual consistency.
```
**Required Elements**:
- Package name
- Component count
- Location (full path)
- Trigger keywords (UI components, design tokens, style guidelines, design patterns)
- Action verbs (working with, analyzing, implementing)
### Progressive Loading Structure
**Level 0** (~2K tokens):
- README.md
- metadata.json
**Level 1** (~8K tokens):
- Level 0 files
- design-tokens.json
- style-guide.md
**Level 2** (~15K tokens):
- Level 1 files
- component-patterns.json
- animation-tokens.json (if exists)
**Level 3** (~25K tokens):
- All files including preview.html/css
---
## Benefits
- **Fast Context Loading**: Progressive levels for efficient token usage
- **Intelligent Triggering**: Keywords optimize SKILL activation
- **Complete Reference**: All package files accessible through SKILL
- **Easy Regeneration**: Simple --regenerate flag for updates
- **Clear Structure**: Organized levels by use case
## Architecture
```
style-skill-memory
├─ Phase 1: Validate (check package exists, check SKILL exists)
├─ Phase 2: Read Metadata (extract metadata.json, README.md, count components)
└─ Phase 3: Generate SKILL.md (write SKILL with progressive loading)
No external commands called
Direct file reading and writing
Smart description generation from metadata
```

View File

@@ -0,0 +1,478 @@
---
name: workflow:ui-design:codify-style
description: Orchestrator to extract styles from code and generate shareable reference package with preview
argument-hint: "[--source <path>] [--package-name <name>] [--css \"<glob>\"] [--scss \"<glob>\"] [--js \"<glob>\"] [--html \"<glob>\"] [--style-files \"<glob>\"] [--output-dir <path>]"
allowed-tools: SlashCommand,Bash,Read,TodoWrite
auto-continue: true
---
# UI Design: Codify Style (Orchestrator)
## Overview
**Pure Orchestrator**: Coordinates style extraction and reference package generation workflow.
**Role**: Does NOT directly execute agent tasks. Delegates to specialized commands:
1. `/workflow:ui-design:import-from-code` - Extract styles from code
2. `/workflow:ui-design:reference-page-generator` - Generate reference package with preview
**Output**: Shareable, versioned style reference package at `.workflow/reference_style/{package-name}/`
## Auto-Continue Workflow
This command runs **fully autonomously** once triggered. Each phase completes and automatically triggers the next phase without user interaction.
## Core Rules
1. **Start Immediately**: First action is TodoWrite initialization, second action is Phase 1 execution
2. **No Task JSON**: This command does not create task JSON files - delegates to sub-commands
3. **Parse Every Output**: Extract required data from each command output (design run path, session ID)
4. **Auto-Continue**: After completing each phase, update TodoWrite and immediately execute next phase
5. **Track Progress**: Update TodoWrite after EVERY phase completion before starting next phase
---
## Usage
### Command Syntax
```bash
/workflow:ui-design:codify-style [FLAGS]
# Flags
--source <path> Source code directory to analyze (required)
--package-name <name> Name for the style reference package (required)
--css "<glob>" CSS file glob pattern (optional)
--scss "<glob>" SCSS file glob pattern (optional)
--js "<glob>" JavaScript file glob pattern (optional)
--html "<glob>" HTML file glob pattern (optional)
--style-files "<glob>" Universal style file glob (optional)
--output-dir <path> Output directory (default: .workflow/reference_style)
--overwrite Overwrite existing package without prompting (optional)
```
### Usage Examples
```bash
# Basic usage - analyze entire src directory
/workflow:ui-design:codify-style --source ./src --package-name main-app-style-v1
# Specific directories
/workflow:ui-design:codify-style --source ./app --package-name design-system-v2 --css "styles/**/*.scss" --js "theme/*.js"
# Tailwind config extraction
/workflow:ui-design:codify-style --source ./ --package-name tailwind-theme-v1 --js "tailwind.config.js"
# Custom output directory
/workflow:ui-design:codify-style --source ./src --package-name component-lib-v1 --output-dir ./style-references
```
---
## 4-Phase Execution
### Phase 1: Prepare Arguments
**Goal**: Parse command arguments and prepare session
**TodoWrite** (First Action):
```json
[
{"content": "Parse arguments and prepare session", "status": "in_progress", "activeForm": "Parsing arguments"},
{"content": "Call import-from-code to extract styles", "status": "pending", "activeForm": "Extracting styles"},
{"content": "Generate reference pages and documentation", "status": "pending", "activeForm": "Generating reference"},
{"content": "Cleanup temporary files", "status": "pending", "activeForm": "Cleanup"}
]
```
**Step 1: Validate Required Parameters**
```bash
bash(test)
```
Operations:
```javascript
// Validate required parameters
if (!source || !package_name) {
error("ERROR: --source and --package-name are required")
error("USAGE: /workflow:ui-design:codify-style --source <path> --package-name <name>")
exit(1)
}
// Validate package name format (lowercase, alphanumeric, hyphens only)
if (!package_name.match(/^[a-z0-9][a-z0-9-]*$/)) {
error("ERROR: Invalid package name. Use lowercase, alphanumeric, and hyphens only.")
error("EXAMPLE: main-app-style-v1")
exit(1)
}
```
**Step 2: Check Package Overwrite Protection**
```bash
bash(test -d ${output_dir:-".workflow/reference_style"}/${package_name} && echo "exists" || echo "not_exists")
```
**Overwrite Protection Logic**:
```javascript
// Check if package already exists
if (package_exists && !overwrite_flag) {
error("ERROR: Package '${package_name}' already exists at ${output_dir}/${package_name}")
error("HINT: To overwrite, use --overwrite flag")
error("HINT: Or choose a different package name")
error("Existing package contents:")
bash(ls -1 ${output_dir}/${package_name}/ 2>/dev/null | head -10)
exit(1)
}
if (overwrite_flag && package_exists) {
echo("WARNING: Overwriting existing package: ${package_name}")
}
```
**Step 3: Create Temporary Session**
```bash
bash(mkdir -p .workflow && echo "WFS-codify-$(date +%Y%m%d-%H%M%S)")
```
Store result as `temp_session_id`
**Step 4: Create Temporary Design Run**
```bash
bash(mkdir -p .workflow/${temp_session_id} && echo "design-run-$(date +%Y%m%d-%H%M%S)")
```
Store result as `temp_design_run_id`
**Step 5: Prepare Full Design Run Path**
```bash
bash(cd .workflow/${temp_session_id} && mkdir -p ${temp_design_run_id} && pwd)/${temp_design_run_id}
```
Store result as `design_run_path`
**Summary Variables**:
- `SOURCE`: User-provided source path
- `PACKAGE_NAME`: User-provided package name
- `OUTPUT_DIR`: `.workflow/reference_style` (default) or user-specified
- `OVERWRITE`: `true` if --overwrite flag, `false` otherwise
- `CSS`: CSS glob pattern (optional)
- `SCSS`: SCSS glob pattern (optional)
- `JS`: JS glob pattern (optional)
- `HTML`: HTML glob pattern (optional)
- `STYLE_FILES`: Universal style files glob (optional)
- `TEMP_SESSION_ID`: `WFS-codify-{timestamp}`
- `TEMP_DESIGN_RUN_ID`: `design-run-{timestamp}`
- `DESIGN_RUN_PATH`: `.workflow/{temp_session_id}/{temp_design_run_id}`
**TodoWrite Update**:
```json
[
{"content": "Parse arguments and prepare session", "status": "completed", "activeForm": "Parsing arguments"},
{"content": "Call import-from-code to extract styles", "status": "in_progress", "activeForm": "Extracting styles"}
]
```
**Next Action**: Display preparation results → Continue to Phase 2
---
### Phase 2: Call import-from-code
**Goal**: Extract styles from source code using import-from-code command
**Command Construction**:
Build command string with all parameters:
```javascript
let cmd = `/workflow:ui-design:import-from-code --design-id ${temp_design_run_id} --source ${source}`;
// Add optional glob patterns if provided
if (css) cmd += ` --css "${css}"`;
if (scss) cmd += ` --scss "${scss}"`;
if (js) cmd += ` --js "${js}"`;
if (html) cmd += ` --html "${html}"`;
if (style_files) cmd += ` --style-files "${style_files}"`;
```
**Execute Command**:
```bash
SlashCommand(command="${cmd}")
```
**Example Commands**:
```bash
# Basic
/workflow:ui-design:import-from-code --design-id design-run-20250111-123456 --source ./src
# With glob patterns
/workflow:ui-design:import-from-code --design-id design-run-20250111-123456 --source ./src --css "theme/*.css" --js "theme/*.js"
# With style-files
/workflow:ui-design:import-from-code --design-id design-run-20250111-123456 --source ./src --style-files "**/theme.*"
```
**Parse Output**:
The import-from-code command will output design run path. Extract it if needed, or use the pre-constructed path from Phase 1.
**Completion Criteria**:
- `import-from-code` command executed successfully
- Design run created at `${design_run_path}`
- Style extraction files exist:
- `${design_run_path}/style-extraction/style-1/design-tokens.json`
- `${design_run_path}/style-extraction/style-1/style-guide.md`
- `${design_run_path}/animation-extraction/` (optional)
**TodoWrite Update**:
```json
[
{"content": "Call import-from-code to extract styles", "status": "completed", "activeForm": "Extracting styles"},
{"content": "Generate reference pages and documentation", "status": "in_progress", "activeForm": "Generating reference"}
]
```
**Next Action**: Display extraction results → Auto-continue to Phase 3
---
### Phase 3: Generate Reference Package
**Goal**: Generate reference pages and package documentation
**Command**:
```bash
SlashCommand(command="/workflow:ui-design:reference-page-generator --design-run ${design_run_path} --package-name ${package_name} --output-dir ${output_dir}")
```
**Example**:
```bash
/workflow:ui-design:reference-page-generator --design-run .workflow/WFS-codify-20250111-123456/design-run-20250111-123456 --package-name main-app-style-v1 --output-dir .workflow/reference_style
```
**Completion Criteria**:
- `reference-page-generator` command executed successfully
- Reference package created at `${output_dir}/${package_name}/`
- Required files exist:
- `design-tokens.json`
- `component-patterns.json`
- `preview.html`
- `preview.css`
- `metadata.json`
- `README.md`
**TodoWrite Update**:
```json
[
{"content": "Generate reference pages and documentation", "status": "completed", "activeForm": "Generating reference"},
{"content": "Cleanup temporary files", "status": "in_progress", "activeForm": "Cleanup"}
]
```
**Next Action**: Display generation results → Auto-continue to Phase 4
---
### Phase 4: Cleanup & Report
**Goal**: Clean up temporary design run and report completion
**Step 1: Cleanup Temporary Design Run** (Optional)
```bash
bash(rm -rf .workflow/${temp_session_id})
```
Note: Temporary design run is removed as reference package has all needed files.
**Step 2: Verify Package**
```bash
bash(test -d ${output_dir}/${package_name} && echo "exists" || echo "missing")
```
**Step 3: Count Components**
```bash
bash(jq -r '.extraction_metadata.component_count // 0' ${output_dir}/${package_name}/component-patterns.json 2>/dev/null || echo 0)
```
**Fallback** (if jq not available):
```bash
bash(grep -c '"button"\|"input"\|"card"\|"badge"\|"alert"' ${output_dir}/${package_name}/component-patterns.json 2>/dev/null || echo 0)
```
**TodoWrite Update**:
```json
[
{"content": "Parse arguments and prepare session", "status": "completed", "activeForm": "Parsing arguments"},
{"content": "Call import-from-code to extract styles", "status": "completed", "activeForm": "Extracting styles"},
{"content": "Generate reference pages and documentation", "status": "completed", "activeForm": "Generating reference"},
{"content": "Cleanup temporary files", "status": "completed", "activeForm": "Cleanup"}
]
```
**Final Action**: Report completion summary to user
---
## Completion Message
```
✅ Style reference package codified successfully!
Package: {package_name}
Location: {output_dir}/{package_name}/
Generated Files:
✓ design-tokens.json Complete design token system
✓ style-guide.md Detailed style guide
✓ component-patterns.json Component catalog ({component_count} components)
✓ preview.html Interactive multi-component showcase
✓ preview.css Showcase styling
✓ animation-tokens.json Animation tokens {if exists: "✓" else: "○ (not found)"}
✓ metadata.json Package metadata
✓ README.md Package documentation
Source Analysis:
- Source path: {source}
- Extraction complete via import-from-code
Preview Package:
Open the interactive showcase:
file://{absolute_path_to_package}/preview.html
Or use a local server:
cd {output_dir}/{package_name}
python -m http.server 8080
# Then open http://localhost:8080/preview.html
Next Steps:
1. Review preview.html to verify extracted components
2. Generate SKILL memory: /memory:style-skill-memory {package_name}
3. Use package as design reference in future workflows
Cleanup:
✓ Temporary design run removed (all files copied to reference package)
```
---
## Execution Flow Diagram
```
User triggers: /workflow:ui-design:codify-style --source ./src --package-name my-style-v1
[TodoWrite] Initialize 4 phases (Phase 1 = in_progress)
[Execute] Phase 1: Parse arguments, create temp session/design run
[TodoWrite] Phase 1 = completed, Phase 2 = in_progress
[Execute] Phase 2: SlashCommand(/workflow:ui-design:import-from-code ...)
[TodoWrite] Phase 2 = completed, Phase 3 = in_progress
[Execute] Phase 3: SlashCommand(/workflow:ui-design:reference-page-generator ...)
[TodoWrite] Phase 3 = completed, Phase 4 = in_progress
[Execute] Phase 4: Cleanup temp files, verify package
[TodoWrite] Phase 4 = completed
[Report] Display completion summary
```
---
## Error Handling
### Common Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Missing --source or --package-name | Required parameters not provided | Provide both flags |
| Invalid package name | Contains uppercase, special chars | Use lowercase, alphanumeric, hyphens only |
| import-from-code failed | Source path invalid or no files found | Verify source path, check glob patterns |
| reference-page-generator failed | Design run incomplete | Check import-from-code output, verify extraction files |
| Package verification failed | Output directory creation failed | Check file permissions |
### Error Recovery
- If Phase 2 fails: Cleanup temporary session and report error
- If Phase 3 fails: Keep design run for debugging, report error
- User can manually inspect `${design_run_path}` if needed
---
## Implementation Details
### Critical Rules
1. **No User Prompts Between Phases**: Never ask user questions or wait for input between phases
2. **Immediate Phase Transition**: After TodoWrite update, immediately execute next phase command
3. **Status-Driven Execution**: Check TodoList status after each phase
4. **Phase Completion Pattern**:
```
Phase N completes → Update TodoWrite (N=completed, N+1=in_progress) → Execute Phase N+1
```
### Parameter Pass-Through
All glob parameters are passed through to `import-from-code`:
- `--css` → passed to import-from-code
- `--scss` → passed to import-from-code
- `--js` → passed to import-from-code
- `--html` → passed to import-from-code
- `--style-files` → passed to import-from-code
### Output Directory Structure
```
.workflow/
├── reference_style/ # Default output directory
│ └── {package-name}/
│ ├── design-tokens.json
│ ├── style-guide.md
│ ├── component-patterns.json
│ ├── animation-tokens.json (optional)
│ ├── preview.html
│ ├── preview.css
│ ├── metadata.json
│ └── README.md
└── WFS-codify-{timestamp}/ # Temporary session (cleaned up)
└── design-run-{timestamp}/ # Temporary design run (cleaned up)
```
---
## Benefits
- **Pure Orchestrator**: No direct agent execution, delegates to specialized commands
- **Auto-Continue**: Autonomous 4-phase execution without user interaction
- **Code Reuse**: Leverages existing `import-from-code` command
- **Clean Separation**: Each command has single responsibility
- **Easy Maintenance**: Changes to sub-commands automatically apply
- **Flexible**: Supports all import-from-code glob parameters
## Architecture
```
codify-style (orchestrator)
├─ Phase 1: Prepare (bash commands, parameter validation)
├─ Phase 2: /workflow:ui-design:import-from-code (style extraction)
├─ Phase 3: /workflow:ui-design:reference-page-generator (reference package)
└─ Phase 4: Cleanup (remove temp files, report)
No task JSON created by this command
All extraction delegated to import-from-code
All packaging delegated to reference-page-generator
```

View File

@@ -0,0 +1,657 @@
---
name: workflow:ui-design:reference-page-generator
description: Generate multi-component reference pages and documentation from design run extraction
argument-hint: "[--design-run <path>] [--package-name <name>] [--output-dir <path>]"
allowed-tools: Read,Write,Bash,Task,TodoWrite
auto-continue: true
---
# UI Design: Reference Page Generator
## Overview
Converts design run extraction results into shareable, versioned reference package with:
- Interactive multi-component preview (preview.html + preview.css)
- Component pattern extraction (component-patterns.json)
- Package metadata and documentation (metadata.json + README.md)
**Role**: Takes existing design run (from `import-from-code` or other extraction commands) and enhances it with component analysis, preview generation, and packaging.
## Usage
### Command Syntax
```bash
/workflow:ui-design:reference-page-generator [FLAGS]
# Flags
--design-run <path> Design run directory path (required)
--package-name <name> Package name for reference (required)
--output-dir <path> Output directory (default: .workflow/reference_style)
```
### Usage Examples
```bash
# Basic usage
/workflow:ui-design:reference-page-generator --design-run .workflow/WFS-123/design-run-456 --package-name main-app-style-v1
# Custom output directory
/workflow:ui-design:reference-page-generator --design-run .workflow/WFS-123/design-run-456 --package-name main-app-style-v1 --output-dir ./style-references
```
---
## Execution Process
### Phase 0: Setup & Validation
**Purpose**: Validate inputs, prepare output directory
**Operations**:
```bash
# 1. Validate required parameters
if [ -z "$design_run" ] || [ -z "$package_name" ]; then
echo "ERROR: --design-run and --package-name are required"
echo "USAGE: /workflow:ui-design:reference-page-generator --design-run <path> --package-name <name>"
exit 1
fi
# 2. Validate package name format (lowercase, alphanumeric, hyphens only)
if ! [[ "$package_name" =~ ^[a-z0-9][a-z0-9-]*$ ]]; then
echo "ERROR: Invalid package name. Use lowercase, alphanumeric, and hyphens only."
echo "EXAMPLE: main-app-style-v1"
exit 1
fi
# 3. Validate design run exists
if [ ! -d "$design_run" ]; then
echo "ERROR: Design run not found: $design_run"
echo "HINT: Run '/workflow:ui-design:import-from-code' first to create design run"
exit 1
fi
# 4. Check required extraction files exist
required_files=(
"$design_run/style-extraction/style-1/design-tokens.json"
)
for file in "${required_files[@]}"; do
if [ ! -f "$file" ]; then
echo "ERROR: Required file not found: $file"
echo "HINT: Ensure design run has style extraction results"
exit 1
fi
done
# 5. Setup output directory
output_dir="${output_dir:-.workflow/reference_style}"
package_dir="${output_dir}/${package_name}"
mkdir -p "$package_dir"
# 6. Validate existing package (if any)
if [ -d "$package_dir" ] && [ "$(ls -A $package_dir 2>/dev/null)" ]; then
# Directory exists and is not empty
if [ -f "$package_dir/metadata.json" ]; then
# Valid package - safe to overwrite
echo "INFO: Valid package '$package_name' found at $package_dir"
echo "This will overwrite existing package contents."
# Read existing package version for logging
existing_version=$(jq -r '.version // "unknown"' "$package_dir/metadata.json" 2>/dev/null || echo "unknown")
echo " Existing version: $existing_version"
else
# Directory exists but not a valid package - risk of data loss
echo "ERROR: Directory '$package_dir' exists but is not a valid style package"
echo "HINT: Directory exists but missing metadata.json"
echo "HINT: This may not be a style reference package"
echo "Directory contents:"
ls -1 "$package_dir" 2>/dev/null | head -10
echo ""
echo "To proceed, either:"
echo " 1. Remove the directory: rm -rf $package_dir"
echo " 2. Choose a different package name"
exit 1
fi
fi
echo "[Phase 0] Setup Complete"
echo " Design Run: $design_run"
echo " Package: $package_name"
echo " Output: $package_dir"
```
<!-- TodoWrite: Initialize todo list -->
**TodoWrite**:
```json
[
{"content": "Phase 0: 验证和准备", "status": "completed", "activeForm": "验证参数"},
{"content": "Phase 1: 组件模式提取", "status": "in_progress", "activeForm": "提取组件模式"},
{"content": "Phase 2: 生成预览页面", "status": "pending", "activeForm": "生成预览"},
{"content": "Phase 3: 生成元数据和文档", "status": "pending", "activeForm": "生成文档"}
]
```
---
### Phase 1: Component Pattern Extraction
**Purpose**: Run Component Agent to extract UI component patterns from design run
**Agent Task**:
```javascript
Task(ui-design-agent): `
[COMPONENT_PATTERNS_EXTRACTION]
Extract reusable UI component patterns from design run extraction results
MODE: component-analysis | DESIGN_RUN: ${design_run} | OUTPUT: ${package_dir}
## Input Files
**Design Run Path**: ${design_run}
You can read ALL files in the design run directory:
- style-extraction/style-1/design-tokens.json
- animation-extraction/animation-tokens.json (if exists)
- layout-extraction/layout-templates.json (if exists)
- Source code files referenced in extraction metadata
## Extraction Strategy
**Component Identification**:
1. Scan design tokens for component-level styles (component_styles in design-tokens.json)
2. Review layout templates for component structures
3. Identify common UI component patterns (button, input, card, modal, badge, alert, etc.)
4. Extract DOM structure for each component
5. Identify CSS class patterns and variants
6. Map component states (default, hover, active, disabled, focus, error, success)
## Output Requirements
Generate 1 file: ${package_dir}/component-patterns.json
### component-patterns.json Structure:
{
"extraction_metadata": {
"package_name": "${package_name}",
"source_design_run": "${design_run}",
"extraction_time": "ISO8601 timestamp",
"files_analyzed": {
"design_tokens": "path/to/design-tokens.json",
"animation_tokens": "path/to/animation-tokens.json (if exists)",
"layout_templates": "path/to/layout-templates.json (if exists)"
},
"component_count": 8
},
"components": {
"button": {
"base_structure": {
"tag": "button",
"base_classes": ["btn"],
"attributes": {
"type": "button",
"role": "button"
}
},
"variants": {
"primary": {
"classes": ["btn-primary"],
"description": "Main call-to-action button",
"style_tokens": {
"background": "var(--color-brand-primary)",
"color": "var(--color-text-inverse)",
"padding": "var(--spacing-3) var(--spacing-6)",
"border_radius": "var(--border-radius-md)"
}
},
"secondary": {
"classes": ["btn-secondary"],
"description": "Secondary action button",
"style_tokens": {
"background": "var(--color-surface-elevated)",
"color": "var(--color-text-primary)",
"border": "1px solid var(--color-border-default)"
}
}
},
"sizes": {
"sm": {"classes": ["btn-sm"]},
"base": {"classes": []},
"lg": {"classes": ["btn-lg"]}
},
"states": {
"default": {"classes": []},
"hover": {"pseudo": ":hover"},
"active": {"pseudo": ":active"},
"disabled": {"attribute": "disabled", "classes": ["btn-disabled"]}
},
"usage_examples": [
"<button class=\"btn btn-primary\">Primary</button>",
"<button class=\"btn btn-secondary btn-lg\">Large Secondary</button>"
]
},
"input": {
"base_structure": {
"tag": "input",
"base_classes": ["input"],
"attributes": {"type": "text"}
},
"variants": {
"default": {
"classes": ["input-default"],
"description": "Standard text input",
"style_tokens": {
"border": "1px solid var(--color-border-default)",
"padding": "var(--spacing-3)",
"border_radius": "var(--border-radius-md)"
}
}
},
"states": {
"default": {"classes": []},
"focus": {"pseudo": ":focus"},
"error": {"classes": ["input-error"]},
"disabled": {"attribute": "disabled"}
},
"usage_examples": [
"<input class=\"input input-default\" type=\"text\" placeholder=\"Enter text\">"
]
},
"card": {
"base_structure": {
"tag": "div",
"base_classes": ["card"],
"children": [
{"tag": "div", "classes": ["card-header"], "optional": true},
{"tag": "div", "classes": ["card-body"]},
{"tag": "div", "classes": ["card-footer"], "optional": true}
]
},
"variants": {
"default": {
"classes": ["card-default"],
"description": "Standard elevated card",
"style_tokens": {
"background": "var(--color-surface-elevated)",
"padding": "var(--spacing-6)",
"border_radius": "var(--border-radius-lg)",
"box_shadow": "var(--shadow-md)"
}
}
},
"usage_examples": [
"<div class=\"card card-default\"><div class=\"card-body\">Content</div></div>"
]
}
}
}
## Completeness Criteria
- Extract at least 5 core component types (button, input, card, badge, alert, etc.)
- Include all variants and states for each component
- Provide usage examples for each component
- Map style tokens to component styles
## Critical Requirements
- ✅ Read design run extraction files using Read() tool
- ✅ Cross-reference design tokens with component styles
- ✅ Generate comprehensive component patterns catalog
- ✅ Use Write() to save: ${package_dir}/component-patterns.json
- ❌ NO external research or MCP calls
`
```
<!-- TodoWrite: Mark Phase 1 complete, start Phase 2 -->
**TodoWrite**:
```json
[
{"content": "Phase 1: 组件模式提取", "status": "completed", "activeForm": "提取组件模式"},
{"content": "Phase 2: 生成预览页面", "status": "in_progress", "activeForm": "生成预览"}
]
```
---
### Phase 2: Preview Generation
**Purpose**: Generate interactive multi-component preview (preview.html + preview.css)
**Agent Task**:
```javascript
Task(ui-design-agent): `
[PREVIEW_SHOWCASE_GENERATION]
Generate interactive multi-component showcase panel for reference package
PACKAGE_DIR: ${package_dir} | PACKAGE_NAME: ${package_name}
## Input Files (MUST READ ALL)
1. ${package_dir}/component-patterns.json (component patterns - REQUIRED)
2. ${design_run}/style-extraction/style-1/design-tokens.json (design tokens - REQUIRED)
3. ${design_run}/animation-extraction/animation-tokens.json (optional, if exists)
## Generation Task
Create interactive showcase with these sections:
### Section 1: Colors
- Display all color categories as color swatches
- Show hex/rgb values
- Group by: brand, semantic, surface, text, border
### Section 2: Typography
- Display typography scale (font sizes, weights)
- Show typography combinations if available
- Include font family examples
### Section 3: Components
- Render all components from component-patterns.json
- Display all variants side-by-side
- Show all states (default, hover, active, disabled, focus, error)
- Include usage code snippets in <details> tags
### Section 4: Spacing & Layout
- Visual spacing scale
- Border radius examples
- Shadow depth examples
### Section 5: Animations (if available)
- Animation duration examples
- Easing function demonstrations
## Output Requirements
Generate 2 files:
1. ${package_dir}/preview.html
2. ${package_dir}/preview.css
### preview.html Structure:
- Complete standalone HTML file
- Responsive design with mobile-first approach
- Sticky navigation for sections
- Interactive state demonstrations
- Code snippets in collapsible <details> elements
- Footer with package metadata
### preview.css Structure:
- CSS Custom Properties from design-tokens.json
- Typography combination classes
- Component classes from component-patterns.json
- Preview page layout styles
- Interactive demo styles
## Critical Requirements
- ✅ Read ALL input files (component-patterns.json, design-tokens.json, animation-tokens.json if exists)
- ✅ Generate complete, interactive showcase HTML
- ✅ All CSS uses var() references to design tokens
- ✅ Display ALL components from component-patterns.json
- ✅ Display ALL variants and states for each component
- ✅ Include usage code snippets
- ✅ Use Write() to save both files:
- ${package_dir}/preview.html
- ${package_dir}/preview.css
- ❌ NO external research or MCP calls
`
```
<!-- TodoWrite: Mark Phase 2 complete, start Phase 3 -->
**TodoWrite**:
```json
[
{"content": "Phase 2: 生成预览页面", "status": "completed", "activeForm": "生成预览"},
{"content": "Phase 3: 生成元数据和文档", "status": "in_progress", "activeForm": "生成文档"}
]
```
---
### Phase 3: Metadata & Documentation Generation
**Purpose**: Create package metadata and documentation
**Operations**:
```bash
echo "[Phase 3] Generating package metadata and documentation"
# 1. Copy design tokens to package directory
cp "${design_run}/style-extraction/style-1/design-tokens.json" "${package_dir}/design-tokens.json"
cp "${design_run}/style-extraction/style-1/style-guide.md" "${package_dir}/style-guide.md" 2>/dev/null || true
# 2. Copy animation tokens if exists
if [ -f "${design_run}/animation-extraction/animation-tokens.json" ]; then
cp "${design_run}/animation-extraction/animation-tokens.json" "${package_dir}/animation-tokens.json"
fi
# 3. Get Git information (if in git repo)
git_commit=""
git_repo=""
if git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
git_commit=$(git rev-parse HEAD 2>/dev/null || echo "")
git_repo=$(git config --get remote.origin.url 2>/dev/null || echo "")
fi
# 4. Get source path from design run metadata
source_path=$(grep -Po '"extraction_source":\s*"\K[^"]+' "${design_run}/style-extraction/style-1/design-tokens.json" 2>/dev/null || echo "code_import")
# 5. Generate metadata.json
cat > "${package_dir}/metadata.json" <<EOF
{
"packageName": "${package_name}",
"version": "1.0.0",
"generatedAt": "$(date -u +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || date)",
"source": {
"type": "git",
"repository": "${git_repo}",
"commit": "${git_commit}",
"design_run": "${design_run}"
},
"description": "Style reference package extracted from design run",
"files": {
"design_tokens": "design-tokens.json",
"style_guide": "style-guide.md",
"component_patterns": "component-patterns.json",
"animation_tokens": "animation-tokens.json",
"preview_html": "preview.html",
"preview_css": "preview.css"
},
"usage": {
"command": "/workflow:ui-design:codify-style --package-name ${package_name}",
"skill_memory": "/memory:style-skill-memory ${package_name}",
"description": "Reference this package for consistent design system usage"
}
}
EOF
echo " ✓ metadata.json created"
# 6. Generate README.md
cat > "${package_dir}/README.md" <<'EOFREADME'
# ${package_name}
Style reference package with interactive component preview.
## Contents
- **design-tokens.json**: Complete design token system
- **style-guide.md**: Detailed style guide documentation
- **component-patterns.json**: Reusable component patterns
- **preview.html**: Interactive component showcase
- **preview.css**: Showcase styling
- **animation-tokens.json**: Animation tokens (if available)
- **metadata.json**: Package metadata
## Usage
### Preview Package
Open `preview.html` in a browser to view the interactive component showcase.
```bash
# Using local server
cd ${package_dir}
python -m http.server 8080
# Then open http://localhost:8080/preview.html
```
### Use in Workflow
Reference this package in UI design workflows or generate SKILL memory:
```bash
# Generate SKILL memory for easy loading
/memory:style-skill-memory ${package_name}
```
## Package Information
- **Generated**: $(date)
- **Source**: Design run extraction
- **Version**: 1.0.0
## Component Catalog
See `component-patterns.json` for complete component catalog with variants, states, and usage examples.
## Design Tokens
All design tokens are available as CSS custom properties. See `design-tokens.json` for complete token reference.
EOFREADME
echo " ✓ README.md created"
# 7. Verify all files exist
echo "[Phase 3] Verifying package files"
required_files=(
"design-tokens.json"
"component-patterns.json"
"preview.html"
"preview.css"
"metadata.json"
"README.md"
)
missing_files=()
for file in "${required_files[@]}"; do
if [ ! -f "${package_dir}/${file}" ]; then
missing_files+=("$file")
fi
done
if [ ${#missing_files[@]} -gt 0 ]; then
echo " ❌ ERROR: Missing required files: ${missing_files[*]}"
exit 1
fi
echo " ✓ All required files present"
# 8. Count component patterns (use jq for reliable parsing)
component_count=$(jq -r '.extraction_metadata.component_count // 0' "${package_dir}/component-patterns.json" 2>/dev/null || grep -c '"button"\|"input"\|"card"\|"badge"\|"alert"' "${package_dir}/component-patterns.json" 2>/dev/null || echo 0)
echo " ✓ Package complete with ${component_count} components"
```
<!-- TodoWrite: Mark all complete -->
**TodoWrite**:
```json
[
{"content": "Phase 0: 验证和准备", "status": "completed", "activeForm": "验证参数"},
{"content": "Phase 1: 组件模式提取", "status": "completed", "activeForm": "提取组件模式"},
{"content": "Phase 2: 生成预览页面", "status": "completed", "activeForm": "生成预览"},
{"content": "Phase 3: 生成元数据和文档", "status": "completed", "activeForm": "生成文档"}
]
```
---
## Output Structure
```
${output_dir}/
└── ${package_name}/
├── design-tokens.json # Design token system (copied from design run)
├── style-guide.md # Style guide (copied from design run)
├── component-patterns.json # Component patterns (NEW)
├── animation-tokens.json # Animation tokens (optional, copied from design run)
├── preview.html # Interactive showcase (NEW)
├── preview.css # Showcase styling (NEW)
├── metadata.json # Package metadata (NEW)
└── README.md # Package documentation (NEW)
```
## Completion Message
```
✅ Reference package generated successfully!
Package: {package_name}
Location: {package_dir}
Generated Files:
✓ design-tokens.json Design token system
✓ style-guide.md Style guide documentation
✓ component-patterns.json Component catalog ({component_count} components)
✓ preview.html Interactive multi-component showcase
✓ preview.css Showcase styling
✓ animation-tokens.json Animation tokens {if exists: "✓" else: "○ (not found)"}
✓ metadata.json Package metadata
✓ README.md Package documentation
Preview Package:
Open the interactive showcase:
file://{absolute_path_to_package_dir}/preview.html
Or use a local server:
cd {package_dir}
python -m http.server 8080
# Then open http://localhost:8080/preview.html
Next Steps:
1. Review preview.html to verify components
2. Generate SKILL memory: /memory:style-skill-memory {package_name}
3. Use package as design reference in future workflows
```
## Error Handling
### Common Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Missing --design-run or --package-name | Required parameters not provided | Provide both flags |
| Invalid package name | Contains uppercase, special chars | Use lowercase, alphanumeric, hyphens only |
| Design run not found | Incorrect path or design run doesn't exist | Verify design run path, run import-from-code first |
| Missing extraction files | Design run incomplete | Ensure design run has style-extraction results |
| Component extraction failed | No components found | Review design tokens for component_styles |
| Preview generation failed | Invalid design tokens | Check design-tokens.json format |
---
## Integration with Workflow
This command is typically called by the `codify-style` orchestrator, but can also be run standalone:
**Standalone Usage**:
```bash
# Step 1: Extract styles from code
/workflow:ui-design:import-from-code --design-id design-run-123 --source ./src
# Step 2: Generate reference package
/workflow:ui-design:reference-page-generator --design-run .workflow/WFS-xxx/design-run-123 --package-name main-app-style-v1
```
**Orchestrator Usage** (via codify-style):
```bash
# Orchestrator handles both steps automatically
/workflow:ui-design:codify-style --source ./src --package-name main-app-style-v1
```