Refactor UI design workflows to unify input parameters and enhance detection logic

- Updated `explore-auto.md`, `imitate-auto.md`, and `import-from-code.md` to replace legacy parameters with a unified `--input` parameter for better clarity and functionality.
- Enhanced input detection logic to support glob patterns, file paths, and text descriptions, allowing for more flexible input combinations.
- Deprecated old parameters (`--images`, `--prompt`, etc.) with warnings and provided clear migration paths.
- Improved error handling for missing inputs and validation of existing directories in `reference-page-generator.md`.
- Streamlined command execution phases to utilize new input structures across workflows.
This commit is contained in:
catlog22
2025-11-11 15:30:53 +08:00
parent feae69470e
commit 0767d6f2d3
5 changed files with 671 additions and 371 deletions

View File

@@ -1,34 +1,47 @@
--- ---
name: workflow:ui-design:codify-style name: workflow:ui-design:codify-style
description: Orchestrator to extract styles from code and generate shareable reference package with preview 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>]" argument-hint: "<path> [--package-name <name>] [--css \"<glob>\"] [--scss \"<glob>\"] [--js \"<glob>\"] [--html \"<glob>\"] [--style-files \"<glob>\"] [--output-dir <path>]"
allowed-tools: SlashCommand,Bash,Read,TodoWrite allowed-tools: SlashCommand,Bash,Read,TodoWrite
auto-continue: true auto-continue: true
--- ---
# UI Design: Codify Style (Orchestrator) # UI Design: Codify Style (Orchestrator)
## Overview ## Overview & Execution Model
**Pure Orchestrator**: Coordinates style extraction and reference package generation workflow. **Fully autonomous orchestrator**: Coordinates style extraction from codebase and generates shareable reference packages.
**Role**: Does NOT directly execute agent tasks. Delegates to specialized commands: **Pure Orchestrator Pattern**: Does NOT directly execute agent tasks. Delegates to specialized commands:
1. `/workflow:ui-design:import-from-code` - Extract styles from code 1. `/workflow:ui-design:import-from-code` - Extract styles from source code
2. `/workflow:ui-design:reference-page-generator` - Generate reference package with preview 2. `/workflow:ui-design:reference-page-generator` - Generate versioned reference package with interactive preview
**Output**: Shareable, versioned style reference package at `.workflow/reference_style/{package-name}/` **Output**: Shareable, versioned style reference package at `.workflow/reference_style/{package-name}/`
## Auto-Continue Workflow **Autonomous Flow** (⚠️ CONTINUOUS EXECUTION - DO NOT STOP):
1. User triggers: `/workflow:ui-design:codify-style <path> --package-name <name>`
2. Phase 0: Parameter validation & preparation → **IMMEDIATELY triggers Phase 1**
3. Phase 1 (import-from-code) → **Execute phase (blocks until finished)** → Auto-continues to Phase 2
4. Phase 2 (reference-page-generator) → **Execute phase (blocks until finished)** → Auto-continues to Phase 3
5. Phase 3 (cleanup & verification) → Reports completion
This command runs **fully autonomously** once triggered. Each phase completes and automatically triggers the next phase without user interaction. **Phase Transition Mechanism**:
- **Phase 0 (Validation)**: Validate parameters, prepare workspace → IMMEDIATELY triggers Phase 1
- **Phase 1-3 (Autonomous)**: `SlashCommand` is BLOCKING - execution pauses until the command finishes
- When each phase finishes executing: Automatically process output and execute next phase
- No user interaction required after initial command
**Auto-Continue Mechanism**: TodoWrite tracks phase status. When each phase finishes executing, you MUST immediately construct and execute the next phase command. No user intervention required. The workflow is NOT complete until reaching Phase 3.
## Core Rules ## Core Rules
1. **Start Immediately**: First action is TodoWrite initialization, second action is Phase 1 execution 1. **Start Immediately**: TodoWrite initialization → Phase 0 validation Phase 1 execution
2. **No Task JSON**: This command does not create task JSON files - delegates to sub-commands 2. **No Task JSON**: This command does not create task JSON files - pure orchestrator pattern
3. **Parse Every Output**: Extract required data from each command output (design run path, session ID) 3. **Parse & Pass**: Extract required data from each command output (design run path, metadata)
4. **Auto-Continue**: After completing each phase, update TodoWrite and immediately execute next phase 4. **Intelligent Validation**: Smart parameter validation with user-friendly error messages
5. **Track Progress**: Update TodoWrite after EVERY phase completion before starting next phase 5. **Safety First**: Package overwrite protection, existence checks, fallback error handling
6. **Track Progress**: Update TodoWrite after EVERY phase completion before starting next phase
7. **⚠️ CRITICAL: DO NOT STOP** - This is a continuous multi-phase workflow. Each SlashCommand execution blocks until finished, then you MUST immediately execute the next phase. Workflow is NOT complete until Phase 3.
--- ---
@@ -37,329 +50,529 @@ This command runs **fully autonomously** once triggered. Each phase completes an
### Command Syntax ### Command Syntax
```bash ```bash
/workflow:ui-design:codify-style [FLAGS] /workflow:ui-design:codify-style <path> [OPTIONS]
# Flags # Required
--source <path> Source code directory to analyze (required) <path> Source code directory or file to analyze
--package-name <name> Name for the style reference package (required)
--css "<glob>" CSS file glob pattern (optional) # Optional
--scss "<glob>" SCSS file glob pattern (optional) --package-name <name> Custom name for the style reference package
--js "<glob>" JavaScript file glob pattern (optional) (default: auto-generated from directory name)
--html "<glob>" HTML file glob pattern (optional) --css "<glob>" CSS file glob pattern
--style-files "<glob>" Universal style file glob (optional) --scss "<glob>" SCSS file glob pattern
--js "<glob>" JavaScript file glob pattern
--html "<glob>" HTML file glob pattern
--style-files "<glob>" Universal style file glob (matches all style files)
--output-dir <path> Output directory (default: .workflow/reference_style) --output-dir <path> Output directory (default: .workflow/reference_style)
--overwrite Overwrite existing package without prompting (optional) --overwrite Overwrite existing package without prompting
``` ```
### Usage Examples ### Usage Examples
```bash ```bash
# Basic usage - analyze entire src directory # Simplest usage - single path parameter
/workflow:ui-design:codify-style --source ./src --package-name main-app-style-v1 /workflow:ui-design:codify-style ./src
# Auto-generates package name: "src-style-v1"
# Specific directories # With custom package name
/workflow:ui-design:codify-style --source ./app --package-name design-system-v2 --css "styles/**/*.scss" --js "theme/*.js" /workflow:ui-design:codify-style ./app --package-name design-system-v2
# Specific file patterns
/workflow:ui-design:codify-style ./app --css "styles/**/*.scss" --js "theme/*.js"
# Tailwind config extraction # Tailwind config extraction
/workflow:ui-design:codify-style --source ./ --package-name tailwind-theme-v1 --js "tailwind.config.js" /workflow:ui-design:codify-style ./ --js "tailwind.config.js" --package-name tailwind-theme-v1
# Custom output directory # Custom output directory
/workflow:ui-design:codify-style --source ./src --package-name component-lib-v1 --output-dir ./style-references /workflow:ui-design:codify-style ./src --package-name component-lib-v1 --output-dir ./style-references
# Overwrite existing package
/workflow:ui-design:codify-style ./src --overwrite
``` ```
--- ---
## 4-Phase Execution ## 4-Phase Execution
### Phase 1: Prepare Arguments ### Phase 0: Intelligent Parameter Validation & Session Preparation
**Goal**: Parse command arguments and prepare session **Goal**: Validate parameters, check safety constraints, prepare session, and get user confirmation
**TodoWrite** (First Action): **TodoWrite** (First Action):
```json ```json
[ [
{"content": "Parse arguments and prepare session", "status": "in_progress", "activeForm": "Parsing arguments"}, {"content": "Validate parameters and prepare session", "status": "in_progress", "activeForm": "Validating parameters"},
{"content": "Call import-from-code to extract styles", "status": "pending", "activeForm": "Extracting styles"}, {"content": "Extract styles from source code", "status": "pending", "activeForm": "Extracting styles"},
{"content": "Generate reference pages and documentation", "status": "pending", "activeForm": "Generating reference"}, {"content": "Generate reference package with preview", "status": "pending", "activeForm": "Generating reference"},
{"content": "Cleanup temporary files", "status": "pending", "activeForm": "Cleanup"} {"content": "Cleanup and verify package", "status": "pending", "activeForm": "Cleanup and verification"}
] ]
``` ```
**Step 1: Validate Required Parameters** **Step 0a: Parse and Validate Required Parameters**
```bash ```bash
bash(test) # Parse positional path parameter (first non-flag argument)
source_path = FIRST_POSITIONAL_ARG
# Validate source path
IF NOT source_path:
REPORT: "❌ ERROR: Missing required parameter: <path>"
REPORT: "USAGE: /workflow:ui-design:codify-style <path> [OPTIONS]"
REPORT: "EXAMPLE: /workflow:ui-design:codify-style ./src"
REPORT: "EXAMPLE: /workflow:ui-design:codify-style ./app --package-name design-system-v2"
EXIT 1
# Validate source path existence
TRY:
source_exists = Bash(test -d "${source_path}" && echo "exists" || echo "not_exists")
IF source_exists != "exists":
REPORT: "❌ ERROR: Source directory not found: ${source_path}"
REPORT: "Please provide a valid directory path."
EXIT 1
CATCH error:
REPORT: "❌ ERROR: Cannot validate source path: ${error}"
EXIT 1
source = source_path
STORE: source
# Auto-generate package name if not provided
IF NOT --package-name:
# Extract directory name from path
dir_name = Bash(basename "${source}")
# Normalize to package name format (lowercase, replace special chars with hyphens)
normalized_name = dir_name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
# Add version suffix
package_name = "${normalized_name}-style-v1"
REPORT: "📋 Auto-generated package name: ${package_name}"
REPORT: " (from directory: ${dir_name})"
ELSE:
package_name = --package-name
# Validate custom package name format (lowercase, alphanumeric, hyphens only)
IF NOT package_name MATCHES /^[a-z0-9][a-z0-9-]*$/:
REPORT: "❌ ERROR: Invalid package name format: ${package_name}"
REPORT: "Requirements:"
REPORT: " • Must start with lowercase letter or number"
REPORT: " • Only lowercase letters, numbers, and hyphens allowed"
REPORT: " • No spaces or special characters"
REPORT: "EXAMPLES: main-app-style-v1, design-system-v2, component-lib-v1"
EXIT 1
STORE: package_name, output_dir (default: ".workflow/reference_style"), overwrite_flag
``` ```
Operations: **Step 0b: Intelligent Package Safety Check**
```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
bash(test -d ${output_dir:-".workflow/reference_style"}/${package_name} && echo "exists" || echo "not_exists") # Set default output directory
output_dir = --output-dir OR ".workflow/reference_style"
package_path = "${output_dir}/${package_name}"
TRY:
package_exists = Bash(test -d "${package_path}" && echo "exists" || echo "not_exists")
IF package_exists == "exists":
IF NOT --overwrite:
REPORT: "❌ ERROR: Package '${package_name}' already exists at ${package_path}/"
REPORT: "Use --overwrite flag to replace, or choose a different package name"
EXIT 1
ELSE:
REPORT: "⚠️ Overwriting existing package: ${package_name}"
CATCH error:
REPORT: "⚠️ Warning: Cannot check package existence: ${error}"
REPORT: "Continuing with package creation..."
``` ```
**Overwrite Protection Logic**: **Step 0c: Session Preparation**
```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
bash(mkdir -p .workflow && echo "WFS-codify-$(date +%Y%m%d-%H%M%S)") # Create temporary session for processing
TRY:
temp_session_id = Bash(mkdir -p .workflow && echo "WFS-codify-$(date +%Y%m%d-%H%M%S)")
temp_design_run_id = Bash(mkdir -p .workflow/${temp_session_id} && echo "design-run-$(date +%Y%m%d-%H%M%S)")
# Create design run directory and get absolute path
Bash(mkdir -p .workflow/${temp_session_id}/${temp_design_run_id})
design_run_path = Bash(cd .workflow/${temp_session_id}/${temp_design_run_id} && pwd)
REPORT: "📦 Temporary workspace created: ${design_run_path}"
CATCH error:
REPORT: "❌ ERROR: Failed to create temporary workspace: ${error}"
EXIT 1
STORE: temp_session_id, temp_design_run_id, design_run_path
# Display configuration summary (informational only, no user prompt)
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "📋 Starting Style Codification"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "Source: ${source}"
REPORT: "Package: ${package_name}"
REPORT: "Output: ${package_path}/"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: ""
``` ```
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**: **Summary Variables**:
- `SOURCE`: User-provided source path - `SOURCE`: Validated source directory path
- `PACKAGE_NAME`: User-provided package name - `PACKAGE_NAME`: Validated package name (lowercase, alphanumeric, hyphens)
- `PACKAGE_PATH`: Full output path `${output_dir}/${package_name}`
- `OUTPUT_DIR`: `.workflow/reference_style` (default) or user-specified - `OUTPUT_DIR`: `.workflow/reference_style` (default) or user-specified
- `OVERWRITE`: `true` if --overwrite flag, `false` otherwise - `OVERWRITE`: `true` if --overwrite flag present
- `CSS`: CSS glob pattern (optional) - `CSS/SCSS/JS/HTML/STYLE_FILES`: Optional glob patterns
- `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_SESSION_ID`: `WFS-codify-{timestamp}`
- `TEMP_DESIGN_RUN_ID`: `design-run-{timestamp}` - `TEMP_DESIGN_RUN_ID`: `design-run-{timestamp}`
- `DESIGN_RUN_PATH`: `.workflow/{temp_session_id}/{temp_design_run_id}` - `DESIGN_RUN_PATH`: Absolute path to temporary workspace
**TodoWrite Update**: **TodoWrite Update**:
```json ```json
[ [
{"content": "Parse arguments and prepare session", "status": "completed", "activeForm": "Parsing arguments"}, {"content": "Validate parameters and prepare session", "status": "completed", "activeForm": "Validating parameters"},
{"content": "Call import-from-code to extract styles", "status": "in_progress", "activeForm": "Extracting styles"} {"content": "Extract styles from source code", "status": "in_progress", "activeForm": "Extracting styles"}
] ]
``` ```
**Next Action**: Display preparation results → Continue to Phase 2 **Next Action**: Validation complete → **IMMEDIATELY execute Phase 1** (auto-continue)
--- ---
### Phase 2: Call import-from-code ### Phase 1: Style Extraction from Source Code
**Goal**: Extract styles from source code using import-from-code command **Goal**: Extract design tokens, style patterns, and component styles from codebase
**Command Construction**: **Command Construction**:
Build command string with all parameters: ```bash
```javascript # Build command with all parameters
let cmd = `/workflow:ui-design:import-from-code --design-id ${temp_design_run_id} --source ${source}`; command_parts = ["/workflow:ui-design:import-from-code"]
command_parts.append("--design-id \"${temp_design_run_id}\"")
command_parts.append("--source \"${source}\"")
// Add optional glob patterns if provided # Add optional glob patterns
if (css) cmd += ` --css "${css}"`; IF --css:
if (scss) cmd += ` --scss "${scss}"`; command_parts.append("--css \"${css}\"")
if (js) cmd += ` --js "${js}"`; IF --scss:
if (html) cmd += ` --html "${html}"`; command_parts.append("--scss \"${scss}\"")
if (style_files) cmd += ` --style-files "${style_files}"`; IF --js:
command_parts.append("--js \"${js}\"")
IF --html:
command_parts.append("--html \"${html}\"")
IF --style-files:
command_parts.append("--style-files \"${style_files}\"")
command = " ".join(command_parts)
REPORT: ""
REPORT: "🎨 Phase 1: Style Extraction"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "Analyzing source code for design patterns..."
REPORT: "Source: ${source}"
IF glob_patterns:
REPORT: "Patterns: ${', '.join(glob_patterns)}"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
``` ```
**Execute Command**: **Execute Command**:
```bash ```bash
SlashCommand(command="${cmd}") TRY:
SlashCommand(command)
# Verify extraction outputs
tokens_path = "${design_run_path}/style-extraction/style-1/design-tokens.json"
guide_path = "${design_run_path}/style-extraction/style-1/style-guide.md"
tokens_exists = Bash(test -f "${tokens_path}" && echo "exists" || echo "missing")
guide_exists = Bash(test -f "${guide_path}" && echo "exists" || echo "missing")
IF tokens_exists != "exists" OR guide_exists != "exists":
REPORT: "⚠️ WARNING: Expected extraction files not found"
REPORT: "Tokens: ${tokens_exists} | Guide: ${guide_exists}"
REPORT: "Continuing with available outputs..."
ELSE:
REPORT: ""
REPORT: "✅ Phase 1 Complete: Style extraction successful"
REPORT: " → Design tokens: ${tokens_path}"
REPORT: " → Style guide: ${guide_path}"
# Optional: Check for animation tokens
anim_path = "${design_run_path}/animation-extraction/animation-tokens.json"
anim_exists = Bash(test -f "${anim_path}" && echo "exists" || echo "missing")
IF anim_exists == "exists":
REPORT: " → Animation tokens: ${anim_path}"
CATCH error:
REPORT: "❌ ERROR: Style extraction failed"
REPORT: "Error: ${error}"
REPORT: ""
REPORT: "Possible causes:"
REPORT: " • Source directory contains no style files"
REPORT: " • Glob patterns don't match any files"
REPORT: " • Invalid file formats in source directory"
REPORT: ""
REPORT: "Cleaning up temporary workspace..."
Bash(rm -rf .workflow/${temp_session_id})
EXIT 1
``` ```
**Example Commands**: **Example Commands**:
```bash ```bash
# Basic # Basic extraction
/workflow:ui-design:import-from-code --design-id design-run-20250111-123456 --source ./src /workflow:ui-design:import-from-code --design-id design-run-20250111-123456 --source ./src
# With glob patterns # With specific file patterns
/workflow:ui-design:import-from-code --design-id design-run-20250111-123456 --source ./src --css "theme/*.css" --js "theme/*.js" /workflow:ui-design:import-from-code --design-id design-run-20250111-123456 --source ./src --css "theme/*.css" --js "theme/*.js"
# With style-files # Universal style files
/workflow:ui-design:import-from-code --design-id design-run-20250111-123456 --source ./src --style-files "**/theme.*" /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**: **Completion Criteria**:
- `import-from-code` command executed successfully - `import-from-code` command executed successfully
- Design run created at `${design_run_path}` - Design run created at `${design_run_path}`
- Style extraction files exist: - ✅ Required files exist:
- `${design_run_path}/style-extraction/style-1/design-tokens.json` - `design-tokens.json` - Complete design token system
- `${design_run_path}/style-extraction/style-1/style-guide.md` - `style-guide.md` - Style documentation
- `${design_run_path}/animation-extraction/` (optional) - ⭕ Optional files:
- `animation-tokens.json` - Animation specifications
- `component-patterns.json` - Component catalog
**TodoWrite Update**: **TodoWrite Update**:
```json ```json
[ [
{"content": "Call import-from-code to extract styles", "status": "completed", "activeForm": "Extracting styles"}, {"content": "Validate parameters and prepare session", "status": "completed", "activeForm": "Validating parameters"},
{"content": "Generate reference pages and documentation", "status": "in_progress", "activeForm": "Generating reference"} {"content": "Extract styles from source code", "status": "completed", "activeForm": "Extracting styles"},
{"content": "Generate reference package with preview", "status": "in_progress", "activeForm": "Generating reference"}
] ]
``` ```
**Next Action**: Display extraction results → Auto-continue to Phase 3 **Next Action**: Extraction verified → **IMMEDIATELY execute Phase 2** (auto-continue)
**⚠️ CRITICAL**: SlashCommand blocks until import-from-code finishes. When it returns, IMMEDIATELY update TodoWrite and execute Phase 2.
--- ---
### Phase 3: Generate Reference Package ### Phase 2: Reference Package Generation
**Goal**: Generate reference pages and package documentation **Goal**: Generate shareable reference package with interactive preview and documentation
**Command**: **Command Construction**:
```bash ```bash
SlashCommand(command="/workflow:ui-design:reference-page-generator --design-run ${design_run_path} --package-name ${package_name} --output-dir ${output_dir}") command = "/workflow:ui-design:reference-page-generator " +
"--design-run \"${design_run_path}\" " +
"--package-name \"${package_name}\" " +
"--output-dir \"${output_dir}\""
REPORT: ""
REPORT: "📦 Phase 2: Reference Package Generation"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "Creating shareable reference package..."
REPORT: "Package: ${package_name}"
REPORT: "Output: ${package_path}/"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
``` ```
**Example**: **Execute Command**:
```bash ```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 TRY:
SlashCommand(command)
# Verify package outputs
required_files = [
"design-tokens.json",
"component-patterns.json",
"preview.html",
"preview.css",
"metadata.json",
"README.md"
]
missing_files = []
FOR file IN required_files:
file_path = "${package_path}/${file}"
exists = Bash(test -f "${file_path}" && echo "exists" || echo "missing")
IF exists != "exists":
missing_files.append(file)
IF missing_files.length > 0:
REPORT: "⚠️ WARNING: Some expected files are missing:"
FOR file IN missing_files:
REPORT: "${file}"
REPORT: ""
REPORT: "Package may be incomplete. Continuing with cleanup..."
ELSE:
REPORT: ""
REPORT: "✅ Phase 2 Complete: Reference package generated"
REPORT: " → Design tokens: design-tokens.json"
REPORT: " → Component patterns: component-patterns.json"
REPORT: " → Interactive preview: preview.html"
REPORT: " → Documentation: README.md"
REPORT: " → Metadata: metadata.json"
CATCH error:
REPORT: "❌ ERROR: Reference package generation failed"
REPORT: "Error: ${error}"
REPORT: ""
REPORT: "This may indicate:"
REPORT: " • Incomplete style extraction in Phase 1"
REPORT: " • Invalid design-run path"
REPORT: " • Insufficient permissions for output directory"
REPORT: ""
REPORT: "Cleaning up temporary workspace..."
Bash(rm -rf .workflow/${temp_session_id})
EXIT 1
```
**Example Command**:
```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**: **Completion Criteria**:
- `reference-page-generator` command executed successfully - `reference-page-generator` executed successfully
- Reference package created at `${output_dir}/${package_name}/` - Reference package created at `${package_path}/`
- Required files exist: - ✅ All required files present:
- `design-tokens.json` - `design-tokens.json` - Complete design token system
- `component-patterns.json` - `component-patterns.json` - Component catalog
- `preview.html` - `preview.html` - Interactive multi-component showcase
- `preview.css` - `preview.css` - Showcase styling
- `metadata.json` - `metadata.json` - Package metadata and version info
- `README.md` - `README.md` - Package documentation and usage guide
- ⭕ Optional files:
- `animation-tokens.json` - Animation specifications (if available from extraction)
**TodoWrite Update**: **TodoWrite Update**:
```json ```json
[ [
{"content": "Generate reference pages and documentation", "status": "completed", "activeForm": "Generating reference"}, {"content": "Validate parameters and prepare session", "status": "completed", "activeForm": "Validating parameters"},
{"content": "Cleanup temporary files", "status": "in_progress", "activeForm": "Cleanup"} {"content": "Extract styles from source code", "status": "completed", "activeForm": "Extracting styles"},
{"content": "Generate reference package with preview", "status": "completed", "activeForm": "Generating reference"},
{"content": "Cleanup and verify package", "status": "in_progress", "activeForm": "Cleanup and verification"}
] ]
``` ```
**Next Action**: Display generation results → Auto-continue to Phase 4 **Next Action**: Package verified → **IMMEDIATELY execute Phase 3** (auto-continue)
**⚠️ CRITICAL**: SlashCommand blocks until reference-page-generator finishes. When it returns, IMMEDIATELY update TodoWrite and execute Phase 3.
--- ---
### Phase 4: Cleanup & Report ### Phase 3: Cleanup & Verification
**Goal**: Clean up temporary design run and report completion **Goal**: Clean up temporary workspace and report completion
**Step 1: Cleanup Temporary Design Run** (Optional) **Operations**:
```bash ```bash
bash(rm -rf .workflow/${temp_session_id}) REPORT: ""
``` REPORT: "🧹 Phase 3: Cleanup & Verification"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
Note: Temporary design run is removed as reference package has all needed files. # Cleanup temporary workspace
TRY:
Bash(rm -rf .workflow/${temp_session_id})
REPORT: "✅ Temporary workspace cleaned"
CATCH error:
REPORT: "⚠️ Warning: Failed to cleanup temporary files: ${error}"
**Step 2: Verify Package** # Quick verification (reference-page-generator already validated outputs)
package_exists = Bash(test -d "${package_path}" && echo "exists" || echo "missing")
```bash IF package_exists != "exists":
bash(test -d ${output_dir}/${package_name} && echo "exists" || echo "missing") REPORT: "❌ ERROR: Package generation failed - directory not found"
``` EXIT 1
**Step 3: Count Components** # Get absolute path and component count for final report
absolute_package_path = Bash(cd "${package_path}" && pwd 2>/dev/null || echo "${package_path}")
component_count = Bash(jq -r '.extraction_metadata.component_count // "unknown"' "${package_path}/component-patterns.json" 2>/dev/null || echo "unknown")
anim_exists = Bash(test -f "${package_path}/animation-tokens.json" && echo "✓" || echo "○")
```bash REPORT: "✅ Package verified: ${package_path}/"
bash(jq -r '.extraction_metadata.component_count // 0' ${output_dir}/${package_name}/component-patterns.json 2>/dev/null || echo 0) REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
```
**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**: **TodoWrite Update**:
```json ```json
[ [
{"content": "Parse arguments and prepare session", "status": "completed", "activeForm": "Parsing arguments"}, {"content": "Validate parameters and prepare session", "status": "completed", "activeForm": "Validating parameters"},
{"content": "Call import-from-code to extract styles", "status": "completed", "activeForm": "Extracting styles"}, {"content": "Extract styles from source code", "status": "completed", "activeForm": "Extracting styles"},
{"content": "Generate reference pages and documentation", "status": "completed", "activeForm": "Generating reference"}, {"content": "Generate reference package with preview", "status": "completed", "activeForm": "Generating reference"},
{"content": "Cleanup temporary files", "status": "completed", "activeForm": "Cleanup"} {"content": "Cleanup and verify package", "status": "completed", "activeForm": "Cleanup and verification"}
] ]
``` ```
**Final Action**: Report completion summary to user **Final Action**: Display completion summary to user
--- ---
## Completion Message ## Completion Message
``` ```
✅ Style reference package codified successfully! ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ STYLE REFERENCE PACKAGE GENERATED SUCCESSFULLY
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Package: {package_name} 📦 Package: {package_name}
Location: {output_dir}/{package_name}/ 📂 Location: {absolute_package_path}/
📄 Source: {source}
Generated Files: Generated Files:
✓ design-tokens.json Complete design token system ✓ design-tokens.json Design token system
✓ style-guide.md Detailed style guide ✓ style-guide.md Style documentation
✓ component-patterns.json Component catalog ({component_count} components) ✓ component-patterns.json Component catalog ({component_count} components)
✓ preview.html Interactive multi-component showcase ✓ preview.html Interactive showcase
✓ preview.css Showcase styling ✓ preview.css Showcase styling
animation-tokens.json Animation tokens {if exists: "✓" else: "○ (not found)"} {anim_exists} animation-tokens.json Animation tokens
✓ metadata.json Package metadata ✓ metadata.json Package metadata
✓ README.md Package documentation ✓ README.md Documentation
Source Analysis: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
- Source path: {source} 🌐 Preview Package
- Extraction complete via import-from-code ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Preview Package: file://{absolute_package_path}/preview.html
Open the interactive showcase:
file://{absolute_path_to_package}/preview.html
Or use a local server: Or use local server:
cd {output_dir}/{package_name} cd {package_path} && python -m http.server 8080
python -m http.server 8080
# Then open http://localhost:8080/preview.html
Next Steps: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. Review preview.html to verify extracted components 📋 Next Steps
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. Review preview.html to verify components and design tokens
2. Generate SKILL memory: /memory:style-skill-memory {package_name} 2. Generate SKILL memory: /memory:style-skill-memory {package_name}
3. Use package as design reference in future workflows 3. Use in workflows: /workflow:ui-design:explore-auto --prompt "Use {package_name} style"
Cleanup: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✓ Temporary design run removed (all files copied to reference package) ```
---
## TodoWrite Pattern
```javascript
// Initialize IMMEDIATELY after user confirms in Phase 0 to track multi-phase execution
TodoWrite({todos: [
{"content": "Validate parameters and prepare session", "status": "in_progress", "activeForm": "Validating parameters"},
{"content": "Extract styles from source code", "status": "pending", "activeForm": "Extracting styles"},
{"content": "Generate reference package with preview", "status": "pending", "activeForm": "Generating reference"},
{"content": "Cleanup and verify package", "status": "pending", "activeForm": "Cleanup and verification"}
]})
// ⚠️ CRITICAL: When each phase finishes, you MUST:
// 1. SlashCommand blocks and returns when phase finishes executing
// 2. Update current phase: status → "completed"
// 3. Update next phase: status → "in_progress"
// 4. IMMEDIATELY execute next phase command (auto-continue)
// This ensures continuous workflow tracking and prevents premature stopping
``` ```
--- ---
@@ -367,27 +580,46 @@ Cleanup:
## Execution Flow Diagram ## Execution Flow Diagram
``` ```
User triggers: /workflow:ui-design:codify-style --source ./src --package-name my-style-v1 User triggers: /workflow:ui-design:codify-style ./src --package-name my-style-v1
[TodoWrite] Initialize 4 phases (Phase 1 = in_progress) [Phase 0] TodoWrite initialization (4 phases)
[Execute] Phase 1: Parse arguments, create temp session/design run [Phase 0] Parameter validation & preparation
├─ Parse positional path parameter
├─ Validate source directory exists
├─ Auto-generate or validate package name
│ • If --package-name provided: validate format
│ • If not provided: auto-generate from directory name
├─ Check package overwrite protection (fail if exists without --overwrite)
├─ Create temporary workspace
└─ Display configuration summary
[TodoWrite] Phase 1 = completed, Phase 2 = in_progress [Phase 0 Complete] → TodoWrite(Phase 0 = completed, Phase 1 = in_progress)
↓ (IMMEDIATELY auto-continue)
[Phase 1] SlashCommand(/workflow:ui-design:import-from-code ...)
├─ Extract design tokens from source code
├─ Generate style guide
├─ Extract component patterns
└─ Verify extraction outputs
↓ (blocks until finished)
[Phase 1 Complete] → TodoWrite(Phase 1 = completed, Phase 2 = in_progress)
↓ (IMMEDIATELY auto-continue)
[Phase 2] SlashCommand(/workflow:ui-design:reference-page-generator ...)
├─ Generate design-tokens.json
├─ Generate component-patterns.json
├─ Create preview.html + preview.css
├─ Generate metadata.json
└─ Create README.md
↓ (blocks until finished)
[Phase 2 Complete] → TodoWrite(Phase 2 = completed, Phase 3 = in_progress)
↓ (IMMEDIATELY auto-continue)
[Phase 3] Cleanup & Verification
├─ Remove temporary workspace
├─ Verify package directory
├─ Extract component count
└─ Display completion summary
[Execute] Phase 2: SlashCommand(/workflow:ui-design:import-from-code ...) [Phase 3 Complete] → TodoWrite(Phase 3 = completed)
[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
``` ```
--- ---
@@ -456,23 +688,42 @@ All glob parameters are passed through to `import-from-code`:
## Benefits ## Benefits
- **Simplified Interface**: Single path parameter with intelligent defaults
- **Auto-Generation**: Package names auto-generated from directory names
- **Pure Orchestrator**: No direct agent execution, delegates to specialized commands - **Pure Orchestrator**: No direct agent execution, delegates to specialized commands
- **Auto-Continue**: Autonomous 4-phase execution without user interaction - **Auto-Continue**: Autonomous 4-phase execution without user interaction
- **Code Reuse**: Leverages existing `import-from-code` command - **Safety First**: Overwrite protection, validation checks, error handling
- **Code Reuse**: Leverages existing `import-from-code` and `reference-page-generator` commands
- **Clean Separation**: Each command has single responsibility - **Clean Separation**: Each command has single responsibility
- **Easy Maintenance**: Changes to sub-commands automatically apply - **Easy Maintenance**: Changes to sub-commands automatically apply
- **Flexible**: Supports all import-from-code glob parameters - **Flexible**: Supports all import-from-code glob parameters for custom file patterns
## Architecture ## Architecture
``` ```
codify-style (orchestrator) codify-style (orchestrator - simplified interface)
├─ Phase 1: Prepare (bash commands, parameter validation) ├─ Phase 0: Intelligent Validation
├─ Phase 2: /workflow:ui-design:import-from-code (style extraction) ├─ Parse positional path parameter
├─ Phase 3: /workflow:ui-design:reference-page-generator (reference package) │ ├─ Auto-generate package name (if not provided)
└─ Phase 4: Cleanup (remove temp files, report) │ ├─ Safety checks (overwrite protection)
│ └─ User confirmation
├─ Phase 1: /workflow:ui-design:import-from-code (style extraction)
│ ├─ Extract design tokens from source code
│ ├─ Generate style guide
│ └─ Extract component patterns
├─ Phase 2: /workflow:ui-design:reference-page-generator (reference package)
│ ├─ Generate shareable package
│ ├─ Create interactive preview
│ └─ Generate documentation
└─ Phase 3: Cleanup & Verification
├─ Remove temporary workspace
├─ Verify package integrity
└─ Report completion
No task JSON created by this command Design Principles:
All extraction delegated to import-from-code ✓ No task JSON created by this command
All packaging delegated to reference-page-generator All extraction delegated to import-from-code
✓ All packaging delegated to reference-page-generator
✓ Pure orchestration with intelligent defaults
✓ Single path parameter for maximum simplicity
``` ```

View File

@@ -1,7 +1,7 @@
--- ---
name: explore-auto name: explore-auto
description: Interactive exploratory UI design workflow with style-centric batch generation, creates design variants from prompts/images with parallel execution and user selection description: Interactive exploratory UI design workflow with style-centric batch generation, creates design variants from prompts/images with parallel execution and user selection
argument-hint: "[--prompt "<desc>"] [--images "<glob>"] [--targets "<list>"] [--target-type "page|component"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--batch-plan]"" argument-hint: "[--input "<value>"] [--targets "<list>"] [--target-type "page|component"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--batch-plan]"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*), Task(conceptual-planning-agent) allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*), Task(conceptual-planning-agent)
--- ---
@@ -49,6 +49,24 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
## Parameter Requirements ## Parameter Requirements
**Recommended Parameter**:
- `--input "<value>"`: Unified input source (auto-detects type)
- **Glob pattern** (images): `"design-refs/*"`, `"screenshots/*.png"`
- **File/directory path** (code): `"./src/components"`, `"/path/to/styles"`
- **Text description** (prompt): `"modern dashboard with 3 styles"`, `"minimalist design"`
- **Combination**: `"design-refs/* modern dashboard"` (glob + description)
- Multiple inputs: Separate with `|``"design-refs/*|modern style"`
**Detection Logic**:
- Contains `*` or matches existing files → **glob pattern** (images)
- Existing file/directory path → **code import**
- Pure text without paths → **design prompt**
- Contains `|` separator → **multiple inputs** (glob|prompt or path|prompt)
**Legacy Parameters** (deprecated, use `--input` instead):
- `--images "<glob>"`: Reference image paths (shows deprecation warning)
- `--prompt "<description>"`: Design description (shows deprecation warning)
**Optional Parameters** (all have smart defaults): **Optional Parameters** (all have smart defaults):
- `--targets "<list>"`: Comma-separated targets (pages/components) to generate (inferred from prompt/session if omitted) - `--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) - `--target-type "page|component|auto"`: Explicitly set target type (default: `auto` - intelligent detection)
@@ -58,19 +76,17 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
- **Tablet**: 768×1024px - Hybrid touch/mouse layouts - **Tablet**: 768×1024px - Hybrid touch/mouse layouts
- **Responsive**: 1920×1080px base with mobile-first breakpoints - **Responsive**: 1920×1080px base with mobile-first breakpoints
- `--session <id>`: Workflow session ID (standalone mode if omitted) - `--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) - `--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) - `--layout-variants <count>`: Layout variants per style (default: inferred or 3, range: 1-5)
- `--batch-plan`: Auto-generate implementation tasks after design-update - `--batch-plan`: Auto-generate implementation tasks after design-update
**Legacy Parameters** (maintained for backward compatibility): **Legacy Target Parameters** (maintained for backward compatibility):
- `--pages "<list>"`: Alias for `--targets` with `--target-type page` - `--pages "<list>"`: Alias for `--targets` with `--target-type page`
- `--components "<list>"`: Alias for `--targets` with `--target-type component` - `--components "<list>"`: Alias for `--targets` with `--target-type component`
**Input Rules**: **Input Rules**:
- Must provide at least one: `--images` or `--prompt` or `--targets` - Must provide: `--input` OR (legacy: `--images`/`--prompt`) OR `--targets`
- Multiple parameters can be combined for guided analysis - `--input` can combine multiple input types
- If `--targets` not provided, intelligently inferred from prompt/session - If `--targets` not provided, intelligently inferred from prompt/session
**Supported Target Types**: **Supported Target Types**:
@@ -109,25 +125,61 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
## 6-Phase Execution ## 6-Phase Execution
### Phase 0a: Intelligent Path Detection & Source Selection ### Phase 0a: Parameter Parsing & Input Detection
```bash ```bash
# Step 1: Detect if prompt/images contain existing file paths # Step 0: Parse and normalize parameters
images_input = null
prompt_text = null
# Handle legacy parameters with deprecation warning
IF --images OR --prompt:
WARN: "⚠️ DEPRECATION: --images and --prompt are deprecated. Use --input instead."
WARN: " Example: --input \"design-refs/*\" or --input \"modern dashboard\""
images_input = --images
prompt_text = --prompt
# Parse unified --input parameter
IF --input:
# Split by | separator for multiple inputs
input_parts = split(--input, "|")
FOR part IN input_parts:
part = trim(part)
# Detection logic
IF contains(part, "*") OR glob_matches_files(part):
# Glob pattern detected → images
images_input = part
ELSE IF file_or_directory_exists(part):
# File/directory path → will be handled in code detection
IF NOT prompt_text:
prompt_text = part
ELSE:
prompt_text = prompt_text + " " + part
ELSE:
# Pure text → prompt
IF NOT prompt_text:
prompt_text = part
ELSE:
prompt_text = prompt_text + " " + part
# Step 1: Detect design source from parsed inputs
code_files_detected = false code_files_detected = false
code_base_path = null code_base_path = null
has_visual_input = false has_visual_input = false
IF --prompt: IF prompt_text:
# Extract potential file paths from prompt # Extract potential file paths from prompt
potential_paths = extract_paths_from_text(--prompt) potential_paths = extract_paths_from_text(prompt_text)
FOR path IN potential_paths: FOR path IN potential_paths:
IF file_or_directory_exists(path): IF file_or_directory_exists(path):
code_files_detected = true code_files_detected = true
code_base_path = path code_base_path = path
BREAK BREAK
IF --images: IF images_input:
# Check if images parameter points to existing files # Check if images parameter points to existing files
IF glob_matches_files(--images): IF glob_matches_files(images_input):
has_visual_input = true has_visual_input = true
# Step 2: Determine design source strategy # Step 2: Determine design source strategy
@@ -148,9 +200,9 @@ STORE: design_source, code_base_path, has_visual_input
### Phase 0a-2: Intelligent Prompt Parsing ### Phase 0a-2: Intelligent Prompt Parsing
```bash ```bash
# Parse variant counts from prompt or use explicit/default values # Parse variant counts from prompt or use explicit/default values
IF --prompt AND (NOT --style-variants OR NOT --layout-variants): IF prompt_text AND (NOT --style-variants OR NOT --layout-variants):
style_variants = regex_extract(prompt, r"(\d+)\s*style") OR --style-variants OR 3 style_variants = regex_extract(prompt_text, r"(\d+)\s*style") OR --style-variants OR 3
layout_variants = regex_extract(prompt, r"(\d+)\s*layout") OR --layout-variants OR 3 layout_variants = regex_extract(prompt_text, r"(\d+)\s*layout") OR --layout-variants OR 3
ELSE: ELSE:
style_variants = --style-variants OR 3 style_variants = --style-variants OR 3
layout_variants = --layout-variants OR 3 layout_variants = --layout-variants OR 3
@@ -172,14 +224,14 @@ IF --device-type AND --device-type != "auto":
device_source = "explicit" device_source = "explicit"
ELSE: ELSE:
# Step 2: Prompt analysis # Step 2: Prompt analysis
IF --prompt: IF prompt_text:
device_keywords = { device_keywords = {
"desktop": ["desktop", "web", "laptop", "widescreen", "large screen"], "desktop": ["desktop", "web", "laptop", "widescreen", "large screen"],
"mobile": ["mobile", "phone", "smartphone", "ios", "android"], "mobile": ["mobile", "phone", "smartphone", "ios", "android"],
"tablet": ["tablet", "ipad", "medium screen"], "tablet": ["tablet", "ipad", "medium screen"],
"responsive": ["responsive", "adaptive", "multi-device", "cross-platform"] "responsive": ["responsive", "adaptive", "multi-device", "cross-platform"]
} }
detected_device = detect_device_from_prompt(--prompt, device_keywords) detected_device = detect_device_from_prompt(prompt_text, device_keywords)
IF detected_device: IF detected_device:
device_type = detected_device device_type = detected_device
device_source = "prompt_inference" device_source = "prompt_inference"
@@ -222,7 +274,8 @@ Write({base_path}/.run-metadata.json): {
"architecture": "style-centric-batch-generation", "architecture": "style-centric-batch-generation",
"parameters": { "style_variants": ${style_variants}, "layout_variants": ${layout_variants}, "parameters": { "style_variants": ${style_variants}, "layout_variants": ${layout_variants},
"targets": "${inferred_target_list}", "target_type": "${target_type}", "targets": "${inferred_target_list}", "target_type": "${target_type}",
"prompt": "${prompt_text}", "images": "${images_pattern}", "prompt": "${prompt_text}", "images": "${images_input}",
"input": "${--input}",
"device_type": "${device_type}", "device_source": "${device_source}" }, "device_type": "${device_type}", "device_source": "${device_source}" },
"status": "in_progress", "status": "in_progress",
"performance_mode": "optimized" "performance_mode": "optimized"
@@ -247,8 +300,8 @@ ELSE IF --targets:
target_type = --target-type != "auto" ? --target-type : detect_target_type(target_list) target_type = --target-type != "auto" ? --target-type : detect_target_type(target_list)
# Step 3: Prompt analysis (Claude internal analysis) # Step 3: Prompt analysis (Claude internal analysis)
ELSE IF --prompt: ELSE IF prompt_text:
analysis_result = analyze_prompt("{prompt_text}") # Extract targets, types, purpose analysis_result = analyze_prompt(prompt_text) # Extract targets, types, purpose
target_list = analysis_result.targets target_list = analysis_result.targets
target_type = analysis_result.primary_type OR detect_target_type(target_list) target_type = analysis_result.primary_type OR detect_target_type(target_list)
target_source = "prompt_analysis" target_source = "prompt_analysis"
@@ -427,8 +480,8 @@ IF design_source IN ["code_only", "hybrid"]:
IF design_source == "visual_only" OR needs_visual_supplement: IF design_source == "visual_only" OR needs_visual_supplement:
REPORT: "🎨 Phase 1: Style Extraction (variants: {style_variants})" REPORT: "🎨 Phase 1: Style Extraction (variants: {style_variants})"
command = "/workflow:ui-design:style-extract --design-id \"{design_id}\" " + command = "/workflow:ui-design:style-extract --design-id \"{design_id}\" " +
(--images ? "--images \"{images}\" " : "") + (images_input ? "--images \"{images_input}\" " : "") +
(--prompt ? "--prompt \"{prompt}\" " : "") + (prompt_text ? "--prompt \"{prompt_text}\" " : "") +
"--variants {style_variants} --interactive" "--variants {style_variants} --interactive"
SlashCommand(command) SlashCommand(command)
ELSE: ELSE:
@@ -456,11 +509,11 @@ IF should_extract_animation:
# Build command with available inputs # Build command with available inputs
command_parts = [f"/workflow:ui-design:animation-extract --design-id \"{design_id}\""] command_parts = [f"/workflow:ui-design:animation-extract --design-id \"{design_id}\""]
IF --images: IF images_input:
command_parts.append(f"--images \"{--images}\"") command_parts.append(f"--images \"{images_input}\"")
IF --prompt: IF prompt_text:
command_parts.append(f"--prompt \"{--prompt}\"") command_parts.append(f"--prompt \"{prompt_text}\"")
command_parts.append("--interactive") command_parts.append("--interactive")
@@ -481,8 +534,8 @@ targets_string = ",".join(inferred_target_list)
IF (design_source == "visual_only" OR needs_visual_supplement) OR (NOT layout_complete): IF (design_source == "visual_only" OR needs_visual_supplement) OR (NOT layout_complete):
REPORT: "🚀 Phase 2.5: Layout Extraction ({targets_string}, variants: {layout_variants}, device: {device_type})" REPORT: "🚀 Phase 2.5: Layout Extraction ({targets_string}, variants: {layout_variants}, device: {device_type})"
command = "/workflow:ui-design:layout-extract --design-id \"{design_id}\" " + command = "/workflow:ui-design:layout-extract --design-id \"{design_id}\" " +
(--images ? "--images \"{images}\" " : "") + (images_input ? "--images \"{images_input}\" " : "") +
(--prompt ? "--prompt \"{prompt}\" " : "") + (prompt_text ? "--prompt \"{prompt_text}\" " : "") +
"--targets \"{targets_string}\" --variants {layout_variants} --device-type \"{device_type}\" --interactive" "--targets \"{targets_string}\" --variants {layout_variants} --device-type \"{device_type}\" --interactive"
SlashCommand(command) SlashCommand(command)
ELSE: ELSE:

View File

@@ -1,7 +1,7 @@
--- ---
name: imitate-auto name: imitate-auto
description: UI design workflow with direct code/image input for design token extraction and prototype generation description: UI design workflow with direct code/image input for design token extraction and prototype generation
argument-hint: "[--images "<glob>"] [--prompt "<desc>"] [--session <id>]" argument-hint: "[--input "<value>"] [--session <id>]"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*) allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*)
--- ---
@@ -42,26 +42,34 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*)
## Parameter Requirements ## Parameter Requirements
**Optional Parameters** (at least one of --images or --prompt required): **Recommended Parameter**:
- `--images "<glob>"`: Reference image paths (e.g., `"design-refs/*"`, `"screenshots/*.png"`) - `--input "<value>"`: Unified input source (auto-detects type)
- Glob patterns supported - **Glob pattern** (images): `"design-refs/*"`, `"screenshots/*.png"`
- Multiple images can be matched - **File/directory path** (code): `"./src/components"`, `"/path/to/styles"`
- **Text description** (prompt): `"Focus on dark mode"`, `"Emphasize minimalist design"`
- **Combination**: `"design-refs/* modern dashboard style"` (glob + description)
- Multiple inputs: Separate with `|``"design-refs/*|modern style"`
- `--prompt "<desc>"`: Design description or file path **Detection Logic**:
- Can contain file paths (automatically detected) - Contains `*` or matches existing files → **glob pattern** (images)
- Influences extract command analysis focus - Existing file/directory path → **code import**
- Example: `"Focus on dark mode"`, `"Emphasize minimalist design"` - Pure text without paths → **design prompt**
- Example with path: `"Use design from ./src/components"` - Contains `|` separator → **multiple inputs** (glob|prompt or path|prompt)
- `--session <id>` (Optional): Workflow session ID **Legacy Parameters** (deprecated, use `--input` instead):
- `--images "<glob>"`: Reference image paths (shows deprecation warning)
- `--prompt "<desc>"`: Design description (shows deprecation warning)
**Optional Parameters**:
- `--session <id>`: Workflow session ID
- Integrate into existing session (`.workflow/WFS-{session}/`) - Integrate into existing session (`.workflow/WFS-{session}/`)
- Enable automatic design system integration (Phase 4) - Enable automatic design system integration (Phase 4)
- If not provided: standalone mode (`.workflow/.design/`) - If not provided: standalone mode (`.workflow/.design/`)
**Input Rules**: **Input Rules**:
- Must provide at least one: `--images` or `--prompt` - Must provide: `--input` OR (legacy: `--images`/`--prompt`)
- Multiple parameters can be combined for guided analysis - `--input` can combine multiple input types
- File paths in `--prompt` are automatically detected and imported - File paths are automatically detected and trigger code import
## Execution Modes ## Execution Modes
@@ -89,26 +97,67 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*)
## 5-Phase Execution ## 5-Phase Execution
### Phase 0: Intelligent Path Detection & Initialization ### Phase 0: Parameter Parsing & Input Detection
```bash ```bash
# Step 1: Detect design source from inputs # Step 0: Parse and normalize parameters
images_input = null
prompt_text = null
# Handle legacy parameters with deprecation warning
IF --images OR --prompt:
WARN: "⚠️ DEPRECATION: --images and --prompt are deprecated. Use --input instead."
WARN: " Example: --input \"design-refs/*\" or --input \"modern dashboard\""
images_input = --images
prompt_text = --prompt
# Parse unified --input parameter
IF --input:
# Split by | separator for multiple inputs
input_parts = split(--input, "|")
FOR part IN input_parts:
part = trim(part)
# Detection logic
IF contains(part, "*") OR glob_matches_files(part):
# Glob pattern detected → images
images_input = part
ELSE IF file_or_directory_exists(part):
# File/directory path → will be handled in code detection
IF NOT prompt_text:
prompt_text = part
ELSE:
prompt_text = prompt_text + " " + part
ELSE:
# Pure text → prompt
IF NOT prompt_text:
prompt_text = part
ELSE:
prompt_text = prompt_text + " " + part
# Validation
IF NOT images_input AND NOT prompt_text:
ERROR: "No input provided. Use --input with glob pattern, file path, or text description"
EXIT 1
# Step 1: Detect design source from parsed inputs
code_files_detected = false code_files_detected = false
code_base_path = null code_base_path = null
has_visual_input = false has_visual_input = false
IF --prompt: IF prompt_text:
# Extract potential file paths from prompt # Extract potential file paths from prompt
potential_paths = extract_paths_from_text(--prompt) potential_paths = extract_paths_from_text(prompt_text)
FOR path IN potential_paths: FOR path IN potential_paths:
IF file_or_directory_exists(path): IF file_or_directory_exists(path):
code_files_detected = true code_files_detected = true
code_base_path = path code_base_path = path
BREAK BREAK
IF --images: IF images_input:
# Check if images parameter points to existing files # Check if images parameter points to existing files
IF glob_matches_files(--images): IF glob_matches_files(images_input):
has_visual_input = true has_visual_input = true
# Step 2: Determine design source strategy # Step 2: Determine design source strategy
@@ -150,8 +199,9 @@ metadata = {
"parameters": { "parameters": {
"design_source": design_source, "design_source": design_source,
"code_base_path": code_base_path, "code_base_path": code_base_path,
"images": --images OR null, "images": images_input OR null,
"prompt": --prompt OR null "prompt": prompt_text OR null,
"input": --input OR null # Store original --input for reference
}, },
"status": "in_progress" "status": "in_progress"
} }
@@ -289,13 +339,13 @@ ELSE:
# Build command with available inputs # Build command with available inputs
command_parts = [f"/workflow:ui-design:style-extract --design-id \"{design_id}\""] command_parts = [f"/workflow:ui-design:style-extract --design-id \"{design_id}\""]
IF --images: IF images_input:
command_parts.append(f"--images \"{--images}\"") command_parts.append(f"--images \"{images_input}\"")
IF --prompt: IF prompt_text:
extraction_prompt = --prompt extraction_prompt = prompt_text
IF design_source == "hybrid": IF design_source == "hybrid":
extraction_prompt = f"{--prompt} (supplement code-imported tokens)" extraction_prompt = f"{prompt_text} (supplement code-imported tokens)"
command_parts.append(f"--prompt \"{extraction_prompt}\"") command_parts.append(f"--prompt \"{extraction_prompt}\"")
command_parts.extend(["--variants 1", "--refine", "--interactive"]) command_parts.extend(["--variants 1", "--refine", "--interactive"])
@@ -319,11 +369,11 @@ ELSE:
# Build command with available inputs # Build command with available inputs
command_parts = [f"/workflow:ui-design:animation-extract --design-id \"{design_id}\""] command_parts = [f"/workflow:ui-design:animation-extract --design-id \"{design_id}\""]
IF --images: IF images_input:
command_parts.append(f"--images \"{--images}\"") command_parts.append(f"--images \"{images_input}\"")
IF --prompt: IF prompt_text:
command_parts.append(f"--prompt \"{--prompt}\"") command_parts.append(f"--prompt \"{prompt_text}\"")
command_parts.extend(["--refine", "--interactive"]) command_parts.extend(["--refine", "--interactive"])
@@ -346,11 +396,11 @@ ELSE:
# Build command with available inputs # Build command with available inputs
command_parts = [f"/workflow:ui-design:layout-extract --design-id \"{design_id}\""] command_parts = [f"/workflow:ui-design:layout-extract --design-id \"{design_id}\""]
IF --images: IF images_input:
command_parts.append(f"--images \"{--images}\"") command_parts.append(f"--images \"{images_input}\"")
IF --prompt: IF prompt_text:
command_parts.append(f"--prompt \"{--prompt}\"") command_parts.append(f"--prompt \"{prompt_text}\"")
# Default target if not specified # Default target if not specified
command_parts.append("--targets \"home\"") command_parts.append("--targets \"home\"")

View File

@@ -1,7 +1,7 @@
--- ---
name: workflow:ui-design:import-from-code name: workflow:ui-design:import-from-code
description: Import design system from code files (CSS/JS/HTML/SCSS) using parallel agent analysis with final synthesis description: Import design system from code files (CSS/JS/HTML/SCSS) using parallel agent analysis with final synthesis
argument-hint: "[--design-id <id>] [--session <id>] [--source <path>] [--css \"<glob>\"] [--js \"<glob>\"] [--scss \"<glob>\"] [--html \"<glob>\"] [--style-files \"<glob>\"]" argument-hint: "[--design-id <id>] [--session <id>] [--source <path>] [--files \"<glob>\"] [--css \"<glob>\"] [--js \"<glob>\"] [--scss \"<glob>\"] [--html \"<glob>\"] [--style-files \"<glob>\"]"
allowed-tools: Read,Write,Bash,Glob,Grep,Task,TodoWrite allowed-tools: Read,Write,Bash,Glob,Grep,Task,TodoWrite
auto-continue: true auto-continue: true
--- ---
@@ -37,6 +37,9 @@ Extract design system tokens from source code files (CSS/SCSS/JS/TS/HTML) using
--design-id <id> Design run ID to import into (must exist) --design-id <id> Design run ID to import into (must exist)
--session <id> Session ID (uses latest design run in session) --session <id> Session ID (uses latest design run in session)
--source <path> Source code directory to analyze (required) --source <path> Source code directory to analyze (required)
--files "<glob>" Universal file glob pattern (recommended, replaces all below)
# Legacy parameters (deprecated, use --files instead)
--css "<glob>" CSS file glob pattern (e.g., "theme/*.css") --css "<glob>" CSS file glob pattern (e.g., "theme/*.css")
--scss "<glob>" SCSS file glob pattern (e.g., "styles/*.scss") --scss "<glob>" SCSS file glob pattern (e.g., "styles/*.scss")
--js "<glob>" JavaScript file glob pattern (e.g., "theme/*.js") --js "<glob>" JavaScript file glob pattern (e.g., "theme/*.js")
@@ -47,23 +50,20 @@ Extract design system tokens from source code files (CSS/SCSS/JS/TS/HTML) using
### Usage Examples ### Usage Examples
```bash ```bash
# Import into specific design run # Simple usage - auto-discover all style files
/workflow:ui-design:import-from-code --design-id design-run-20250109-12345 --source ./src /workflow:ui-design:import-from-code --design-id design-run-20250109-12345 --source ./src
# Import into session's latest design run # Recommended: Use --files for custom patterns
/workflow:ui-design:import-from-code --session WFS-20250109-12345 --source ./src /workflow:ui-design:import-from-code --session WFS-20250109-12345 --source ./src --files "**/theme.*"
# Target specific directories # Target specific file patterns
/workflow:ui-design:import-from-code --session WFS-20250109-12345 --source ./src --css "theme/*.css" --js "theme/*.js" /workflow:ui-design:import-from-code --design-id design-run-20250109-12345 --source ./src --files "**/{theme,style,color}.*"
# Tailwind config only # Tailwind config only
/workflow:ui-design:import-from-code --design-id design-run-20250109-12345 --source ./ --js "tailwind.config.js" /workflow:ui-design:import-from-code --design-id design-run-20250109-12345 --source ./ --files "tailwind.config.js"
# CSS framework import # Legacy syntax (still supported, but --files recommended)
/workflow:ui-design:import-from-code --session WFS-20250109-12345 --source ./src --css "styles/**/*.scss" --html "components/**/*.html" /workflow:ui-design:import-from-code --session WFS-20250109-12345 --source ./src --css "theme/*.css" --js "theme/*.js"
# Universal style files
/workflow:ui-design:import-from-code --design-id design-run-20250109-12345 --source ./src --style-files "**/theme.*"
``` ```
--- ---
@@ -123,56 +123,13 @@ echo " Output: $base_path"
] ]
``` ```
**File Discovery Logic**: **File Discovery Behavior**:
```bash - **With `--files`**: Discovers all files matching the glob pattern, then categorizes by extension
# 2. Discover files by type - **With legacy parameters**: Uses individual globs for CSS/SCSS/JS/HTML (shows deprecation warning)
cd "$source" || exit 1 - **Auto-discover (default)**: Finds all CSS/SCSS/HTML files and theme-related JS/TS files
- **Exclusions**: Automatically excludes `node_modules/` and `dist/` directories
# CSS files - **Output**: Categorized file lists saved to `.intermediates/import-analysis/`
if [ -n "$css" ]; then
find . -type f -name "*.css" | grep -E "$css" > "$intermediates_dir/css-files.txt"
elif [ -n "$style_files" ]; then
find . -type f -name "*.css" | grep -E "$style_files" > "$intermediates_dir/css-files.txt"
else
find . -type f -name "*.css" -not -path "*/node_modules/*" -not -path "*/dist/*" > "$intermediates_dir/css-files.txt"
fi
# SCSS files
if [ -n "$scss" ]; then
find . -type f \( -name "*.scss" -o -name "*.sass" \) | grep -E "$scss" > "$intermediates_dir/scss-files.txt"
elif [ -n "$style_files" ]; then
find . -type f \( -name "*.scss" -o -name "*.sass" \) | grep -E "$style_files" > "$intermediates_dir/scss-files.txt"
else
find . -type f \( -name "*.scss" -o -name "*.sass" \) -not -path "*/node_modules/*" -not -path "*/dist/*" > "$intermediates_dir/scss-files.txt"
fi
# JavaScript files (theme/style related)
if [ -n "$js" ]; then
find . -type f \( -name "*.js" -o -name "*.ts" -o -name "*.jsx" -o -name "*.tsx" \) | grep -E "$js" > "$intermediates_dir/js-files.txt"
elif [ -n "$style_files" ]; then
find . -type f \( -name "*.js" -o -name "*.ts" -o -name "*.jsx" -o -name "*.tsx" \) | grep -E "$style_files" > "$intermediates_dir/js-files.txt"
else
# Look for common theme/style file patterns
find . -type f \( -name "*.js" -o -name "*.ts" -o -name "*.jsx" -o -name "*.tsx" \) -not -path "*/node_modules/*" -not -path "*/dist/*" | \
grep -iE "(theme|style|color|token|design)" > "$intermediates_dir/js-files.txt" || touch "$intermediates_dir/js-files.txt"
fi
# HTML files
if [ -n "$html" ]; then
find . -type f \( -name "*.html" -o -name "*.htm" \) | grep -E "$html" > "$intermediates_dir/html-files.txt"
else
find . -type f \( -name "*.html" -o -name "*.htm" \) -not -path "*/node_modules/*" -not -path "*/dist/*" > "$intermediates_dir/html-files.txt"
fi
# 3. Count discovered files
css_count=$(wc -l < "$intermediates_dir/css-files.txt" 2>/dev/null || echo 0)
scss_count=$(wc -l < "$intermediates_dir/scss-files.txt" 2>/dev/null || echo 0)
js_count=$(wc -l < "$intermediates_dir/js-files.txt" 2>/dev/null || echo 0)
html_count=$(wc -l < "$intermediates_dir/html-files.txt" 2>/dev/null || echo 0)
echo "[Phase 0] Discovered: CSS=$css_count, SCSS=$scss_count, JS=$js_count, HTML=$html_count"
```
<!-- TodoWrite: Mark Phase 0 complete, start Phase 1 --> <!-- TodoWrite: Mark Phase 0 complete, start Phase 1 -->

View File

@@ -85,38 +85,27 @@ for file in "${required_files[@]}"; do
fi fi
done done
# 5. Setup output directory # 5. Setup output directory and validate
output_dir="${output_dir:-.workflow/reference_style}" output_dir="${output_dir:-.workflow/reference_style}"
package_dir="${output_dir}/${package_name}" package_dir="${output_dir}/${package_name}"
mkdir -p "$package_dir" # Check if package directory exists and is not empty
# 6. Validate existing package (if any)
if [ -d "$package_dir" ] && [ "$(ls -A $package_dir 2>/dev/null)" ]; then if [ -d "$package_dir" ] && [ "$(ls -A $package_dir 2>/dev/null)" ]; then
# Directory exists and is not empty # Directory exists - check if it's a valid package or just a directory
if [ -f "$package_dir/metadata.json" ]; then if [ -f "$package_dir/metadata.json" ]; then
# Valid package - safe to overwrite # 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") existing_version=$(jq -r '.version // "unknown"' "$package_dir/metadata.json" 2>/dev/null || echo "unknown")
echo " Existing version: $existing_version" echo "INFO: Overwriting existing package '$package_name' (version: $existing_version)"
else else
# Directory exists but not a valid package - risk of data loss # Directory exists but not a valid package
echo "ERROR: Directory '$package_dir' exists but is not a valid style package" echo "ERROR: Directory '$package_dir' exists but is not a valid package"
echo "HINT: Directory exists but missing metadata.json" echo "Use a different package name or remove the directory manually"
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 exit 1
fi fi
fi fi
mkdir -p "$package_dir"
echo "[Phase 0] Setup Complete" echo "[Phase 0] Setup Complete"
echo " Design Run: $design_run" echo " Design Run: $design_run"
echo " Package: $package_name" echo " Package: $package_name"