feat: Add imitate-auto-v3 workflow for high-speed multi-page UI replication

- Introduced a new workflow named `imitate-auto-v3` that allows for batch screenshot capture and optional token refinement.
- Implemented a comprehensive 5-phase execution protocol to handle initialization, screenshot capture, style extraction, token processing, and UI generation.
- Added support for multiple target URLs through a `--url-map` parameter, enhancing flexibility in design replication.
- Included optional parameters for session management and token refinement, allowing users to customize their workflow experience.
- Enhanced error handling and reporting throughout the workflow to ensure clarity and ease of debugging.
- Deprecated the previous `imitate-auto.md` workflow in favor of this more robust version.
This commit is contained in:
catlog22
2025-10-11 11:42:33 +08:00
parent f07e77e9fa
commit 2fcd44e856
7 changed files with 2500 additions and 6 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,533 @@
---
name: capture
description: Batch screenshot capture for UI design workflows using MCP or local fallback
usage: /workflow:ui-design:capture --url-map "<map>" [--base-path <path>] [--session <id>]
examples:
- /workflow:ui-design:capture --url-map "home:https://linear.app, pricing:https://linear.app/pricing"
- /workflow:ui-design:capture --session WFS-auth --url-map "dashboard:https://app.com/dash"
- /workflow:ui-design:capture --base-path ".workflow/.design/run-20250110" --url-map "hero:https://example.com#hero"
allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*), mcp__browser__screenshot(*)
---
# Batch Screenshot Capture Command
## Overview
独立的批量截图命令支持MCP优先策略和多级降级机制。可被其他工作流复用。
## Core Philosophy
- **MCP优先**优先使用mcp__browser__screenshot如果可用
- **智能降级**MCP失败 → Playwright → Chrome → 手动上传
- **批量处理**一次处理多个URL并行截图
- **结构化输出**按target_name组织截图文件
- **错误容忍**:部分失败不阻塞整体流程
## Execution Protocol
### Phase 0: 初始化和路径解析
```bash
# 确定base path
IF --base-path:
base_path = {provided_base_path}
ELSE IF --session:
# 查找session最新design run
session_design_dirs = Glob(".workflow/WFS-{session}/design-*")
IF session_design_dirs:
base_path = most_recent(session_design_dirs)
ELSE:
# 创建新的design run
run_id = "run-$(date +%Y%m%d-%H%M%S)"
base_path = ".workflow/WFS-{session}/design-{run_id}"
ELSE:
# Standalone模式
run_id = "run-$(date +%Y%m%d-%H%M%S)"
base_path = ".workflow/.design/{run_id}"
# 创建截图目录
screenshot_dir = "{base_path}/screenshots"
Bash(mkdir -p "{screenshot_dir}")
REPORT: "📸 Batch Screenshot Capture"
REPORT: " Output: {screenshot_dir}/"
# 解析url-map
url_map_string = {--url-map} # "home:https://a.com, pricing:https://a.com/pricing"
# 解析逻辑
url_entries = []
FOR pair IN split(url_map_string, ","):
pair = pair.strip()
IF ":" NOT IN pair:
ERROR: "Invalid url-map format: '{pair}'"
ERROR: "Expected format: 'target:url'"
ERROR: "Example: 'home:https://example.com, pricing:https://example.com/pricing'"
EXIT 1
target, url = pair.split(":", 1)
target = target.strip().lower().replace(" ", "-")
url = url.strip()
# 验证target名称
IF NOT regex_match(target, r"^[a-z0-9][a-z0-9_-]*$"):
ERROR: "Invalid target name: '{target}'"
ERROR: "Target names must start with alphanumeric and contain only [a-z0-9_-]"
EXIT 1
# 验证URL格式
IF NOT (url.startswith("http://") OR url.startswith("https://")):
WARN: "URL '{url}' does not start with http:// or https://"
WARN: "Prepending https:// automatically"
url = f"https://{url}"
url_entries.append({"target": target, "url": url})
VALIDATE: len(url_entries) > 0, "url-map must contain at least one target:url pair"
total_targets = len(url_entries)
REPORT: " Targets: {total_targets}"
FOR entry IN url_entries:
REPORT: " • {entry.target}: {entry.url}"
TodoWrite({todos: [
{content: "Initialize and parse url-map", status: "completed", activeForm: "Initializing"},
{content: "MCP batch screenshot capture", status: "pending", activeForm: "Capturing via MCP"},
{content: "Local tool fallback (if needed)", status: "pending", activeForm: "Local fallback"},
{content: "Verify and summarize results", status: "pending", activeForm: "Verifying"}
]})
```
### Phase 1: MCP批量截图优先策略
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 Phase 1: MCP Batch Screenshot"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 检测MCP工具可用性
mcp_available = check_tool_availability("mcp__browser__screenshot")
success_captures = []
failed_captures = []
IF mcp_available:
REPORT: "✓ MCP browser screenshot tool detected"
# 构建MCP调用参数
urls = [entry.url for entry in url_entries]
file_prefixes = [entry.target for entry in url_entries]
TRY:
# MCP批量截图调用
REPORT: " Calling MCP for {len(urls)} URLs..."
result = mcp__browser__screenshot({
urls: urls,
output_dir: screenshot_dir,
file_prefix: file_prefixes,
full_page: true,
viewport: "1920,1080",
timeout: 30000
})
# 处理MCP返回结果
success_count = len(result.success)
failed_count = len(result.failed)
REPORT: " MCP capture complete: {success_count} succeeded, {failed_count} failed"
FOR item IN result.success:
success_captures.append(item.target)
REPORT: " ✓ {item.target}.png"
FOR item IN result.failed:
failed_captures.append({"target": item.target, "url": item.url, "error": item.error})
REPORT: " ✗ {item.target}: {item.error}"
# 如果有部分失败标记需要fallback
IF failed_count > 0:
failed_targets = [item.target for item in result.failed]
REPORT: " → {failed_count} failed, proceeding to local fallback..."
TodoWrite(mark_completed: "MCP batch screenshot capture", mark_in_progress: "Local tool fallback")
GOTO Phase 2 (fallback_targets = failed_targets)
ELSE:
REPORT: "✅ All screenshots captured via MCP"
TodoWrite(mark_completed: "MCP batch screenshot capture", mark_completed: "Local tool fallback", mark_in_progress: "Verify results")
GOTO Phase 3 (verification)
CATCH error:
REPORT: "⚠️ MCP call failed: {error}"
REPORT: " Falling back to local tools for all targets"
failed_targets = [entry.target for entry in url_entries]
TodoWrite(mark_completed: "MCP batch screenshot capture", mark_in_progress: "Local tool fallback")
GOTO Phase 2 (fallback_targets = failed_targets)
ELSE:
REPORT: " MCP browser screenshot tool not available"
REPORT: " Using local tool fallback strategy"
failed_targets = [entry.target for entry in url_entries]
TodoWrite(mark_completed: "MCP batch screenshot capture", mark_in_progress: "Local tool fallback")
GOTO Phase 2 (fallback_targets = failed_targets)
```
### Phase 2: Local工具降级Playwright → Chrome
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🔧 Phase 2: Local Tool Fallback"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 仅处理Phase 1失败的targets
targets_to_capture = [entry for entry in url_entries if entry.target IN fallback_targets]
REPORT: "Processing {len(targets_to_capture)} target(s) with local tools..."
# 检测本地工具(检查可执行文件,不触发安装)
playwright_path = Bash(which playwright 2>/dev/null || echo "")
chrome_path = Bash(which google-chrome 2>/dev/null || which chrome 2>/dev/null || which chromium 2>/dev/null || echo "")
playwright_available = playwright_path != ""
chrome_available = chrome_path != ""
REPORT: " Tool availability:"
REPORT: " Playwright: {playwright_available ? '✓ Available' : '✗ Not found'}"
REPORT: " Chrome: {chrome_available ? '✓ Available' : '✗ Not found'}"
local_success = []
local_failed = []
FOR entry IN targets_to_capture:
target = entry.target
url = entry.url
output_file = "{screenshot_dir}/{target}.png"
captured = false
method_used = null
# 尝试Playwright
IF playwright_available AND NOT captured:
TRY:
REPORT: " Trying Playwright for '{target}'..."
Bash({playwright_path} screenshot "{url}" "{output_file}" --full-page --timeout 30000)
IF exists(output_file) AND file_size(output_file) > 1000: # >1KB验证有效
captured = true
method_used = "Playwright"
local_success.append(target)
success_captures.append(target)
REPORT: " ✓ {target}.png (Playwright, {file_size(output_file)/1024:.1f} KB)"
CATCH error:
REPORT: " ⚠️ Playwright failed: {error}"
# 尝试Chrome
IF chrome_available AND NOT captured:
TRY:
REPORT: " Trying Chrome for '{target}'..."
Bash({chrome_path} --headless --disable-gpu --screenshot="{output_file}" --window-size=1920,1080 "{url}")
IF exists(output_file) AND file_size(output_file) > 1000:
captured = true
method_used = "Chrome"
local_success.append(target)
success_captures.append(target)
REPORT: " ✓ {target}.png (Chrome, {file_size(output_file)/1024:.1f} KB)"
CATCH error:
REPORT: " ⚠️ Chrome failed: {error}"
# 标记彻底失败
IF NOT captured:
local_failed.append(entry)
failed_captures.append({"target": target, "url": url, "error": "All local tools failed"})
REPORT: " ✗ {target}: All tools failed"
REPORT: ""
REPORT: "Local fallback summary:"
REPORT: " Succeeded: {len(local_success)}/{len(targets_to_capture)}"
REPORT: " Failed: {len(local_failed)}/{len(targets_to_capture)}"
# 如果仍有失败,进入手动模式
IF len(local_failed) > 0:
TodoWrite(mark_completed: "Local tool fallback", mark_in_progress: "Manual upload mode")
GOTO Phase 2.5 (manual_upload)
ELSE:
TodoWrite(mark_completed: "Local tool fallback", mark_in_progress: "Verify results")
GOTO Phase 3 (verification)
```
### Phase 2.5: 手动上传降级
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "⚠️ Phase 2.5: Manual Screenshot Required"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "Failed to auto-capture {len(local_failed)} target(s):"
REPORT: ""
FOR entry IN local_failed:
REPORT: " {entry.target}:"
REPORT: " URL: {entry.url}"
REPORT: " Save to: {screenshot_dir}/{entry.target}.png"
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "📋 Manual Steps:"
REPORT: " 1. Visit each URL above in your browser"
REPORT: " 2. Take full-page screenshot (Browser DevTools or extensions)"
REPORT: " 3. Save screenshot to specified path"
REPORT: " 4. Return here and choose an option"
REPORT: ""
REPORT: "Options:"
REPORT: " • Type 'ready' : I've uploaded screenshot(s), continue workflow"
REPORT: " • Type 'skip' : Skip failed screenshots, continue with available"
REPORT: " • Type 'abort' : Cancel entire capture workflow"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
user_response = WAIT_FOR_USER_INPUT()
MATCH user_response.lower():
"ready" | "done" | "ok" | "continue":
# 验证手动上传的文件
manual_uploaded = []
REPORT: "🔍 Checking for manual screenshots..."
FOR entry IN local_failed:
expected_path = f"{screenshot_dir}/{entry.target}.png"
IF exists(expected_path) AND file_size(expected_path) > 1000:
manual_uploaded.append(entry.target)
success_captures.append(entry.target)
REPORT: " ✓ {entry.target}.png (manual, {file_size(expected_path)/1024:.1f} KB)"
ELSE:
REPORT: " ✗ {entry.target}.png not found or invalid"
IF len(manual_uploaded) > 0:
REPORT: "✅ Detected {len(manual_uploaded)} manual screenshot(s)"
# 移除已上传的targets from failed list
failed_captures = [f for f in failed_captures if f.target NOT IN manual_uploaded]
ELSE:
REPORT: "⚠️ No valid manual screenshots detected"
REPORT: " Proceeding with available screenshots only"
TodoWrite(mark_completed: "Manual upload mode", mark_in_progress: "Verify results")
GOTO Phase 3
"skip" | "s":
REPORT: "⏭️ Skipping {len(local_failed)} failed screenshot(s)"
REPORT: " Proceeding with {len(success_captures)} available screenshot(s)"
TodoWrite(mark_completed: "Manual upload mode", mark_in_progress: "Verify results")
GOTO Phase 3
"abort" | "cancel" | "exit":
ERROR: "Workflow aborted by user"
TodoWrite(mark_failed: "Manual upload mode")
EXIT 1
_:
REPORT: "⚠️ Invalid input '{user_response}', interpreting as 'skip'"
REPORT: " Proceeding with available screenshots"
TodoWrite(mark_completed: "Manual upload mode", mark_in_progress: "Verify results")
GOTO Phase 3
```
### Phase 3: 验证和总结
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "✅ Phase 3: Verification & Summary"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 扫描实际截图文件
captured_files = Glob("{screenshot_dir}/*.{png,jpg,jpeg,webp}")
captured_targets_actual = [extract_basename_without_ext(f) for f in captured_files]
# 与请求对比
total_requested = len(url_entries)
total_captured = len(captured_targets_actual)
missing_targets = [entry.target for entry in url_entries if entry.target NOT IN captured_targets_actual]
REPORT: "📊 Capture Summary:"
REPORT: " Total requested: {total_requested}"
REPORT: " Successfully captured: {total_captured}"
REPORT: " Success rate: {(total_captured / total_requested * 100):.1f}%"
IF missing_targets:
REPORT: ""
REPORT: "⚠️ Missing screenshots ({len(missing_targets)}):"
FOR target IN missing_targets:
REPORT: " • {target}"
ELSE:
REPORT: ""
REPORT: "✅ All requested screenshots captured!"
# 生成capture元数据
metadata = {
"timestamp": current_timestamp(),
"total_requested": total_requested,
"total_captured": total_captured,
"success_rate": round(total_captured / total_requested * 100, 2),
"screenshots": []
}
FOR entry IN url_entries:
target = entry.target
url = entry.url
is_captured = target IN captured_targets_actual
screenshot_info = {
"target": target,
"url": url,
"captured": is_captured
}
IF is_captured:
file_path = f"{screenshot_dir}/{target}.png"
screenshot_info["path"] = file_path
screenshot_info["size_kb"] = round(file_size(file_path) / 1024, 2)
# 查找捕获方法
IF target IN [s.target for s in result.success if mcp_available]:
screenshot_info["method"] = "MCP"
ELSE IF target IN local_success:
screenshot_info["method"] = "Local (Playwright/Chrome)"
ELSE:
screenshot_info["method"] = "Manual"
ELSE:
screenshot_info["path"] = null
screenshot_info["error"] = next((f.error for f in failed_captures if f.target == target), "Unknown error")
metadata.screenshots.append(screenshot_info)
# 写入元数据文件
metadata_path = "{screenshot_dir}/capture-metadata.json"
Write(metadata_path, JSON.stringify(metadata, null, 2))
REPORT: ""
REPORT: "📁 Output:"
REPORT: " Directory: {screenshot_dir}/"
REPORT: " Metadata: capture-metadata.json"
TodoWrite(mark_completed: "Verify and summarize results")
```
### Phase 4: 完成
```javascript
TodoWrite({todos: [
{content: "Initialize and parse url-map", status: "completed", activeForm: "Initializing"},
{content: "MCP batch screenshot capture", status: "completed", activeForm: "MCP capture"},
{content: "Local tool fallback (if needed)", status: "completed", activeForm: "Local fallback"},
{content: "Verify and summarize results", status: "completed", activeForm: "Verifying"}
]});
```
**Completion Message**:
```
✅ Batch Screenshot Capture Complete!
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Capture Summary
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Requested: {total_requested} screenshots
Captured: {total_captured} screenshots
Success Rate: {success_rate}%
Capture Methods:
{IF mcp_available AND mcp_success_count > 0:
• MCP: {mcp_success_count} screenshot(s)
}
{IF local_success_count > 0:
• Local tools: {local_success_count} screenshot(s)
}
{IF manual_count > 0:
• Manual upload: {manual_count} screenshot(s)
}
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📂 Output Structure
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
{screenshot_dir}/
├── {target1}.png ({size1} KB)
├── {target2}.png ({size2} KB)
{FOR each captured screenshot}
└── capture-metadata.json
{IF missing_targets:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ Missing Screenshots ({len(missing_targets)})
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
{FOR target IN missing_targets:
• {target} - {get_error_for_target(target)}
}
💡 Tip: Re-run capture command for failed targets:
/workflow:ui-design:capture --base-path "{base_path}" --url-map "{build_failed_url_map()}"
}
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚀 Next Steps
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. Extract design style from captured screenshots:
/workflow:ui-design:extract --base-path "{base_path}" --images "{screenshot_dir}/*.png" --mode imitate --variants 1
2. Or continue with full imitate workflow:
(capture is automatically called by /workflow:ui-design:imitate-auto-v3)
```
## MCP API设计假设实现
```typescript
// 假设的MCP工具签名
mcp__browser__screenshot({
urls: string[], // 要截图的URL列表
output_dir: string, // 输出目录
file_prefix: string[], // 文件名前缀列表对应urls
full_page?: boolean, // 全页截图默认true
viewport?: string, // 视口大小(默认"1920,1080"
timeout?: number // 每个URL的超时默认30000ms
}): {
success: Array<{
target: string, // file_prefix对应的target名称
url: string, // 成功截图的URL
path: string // 生成的截图文件路径
}>,
failed: Array<{
target: string, // file_prefix对应的target名称
url: string, // 失败的URL
error: string // 错误信息
}>
}
```
**注意事项**
- 如果`mcp__browser__screenshot`工具不存在,命令会自动降级到本地工具
- MCP工具应该支持并行截图以提高性能
- 返回结果应该区分成功和失败,允许部分失败
## Error Handling
- **无效url-map格式**:清晰的错误信息+格式示例
- **MCP不可用**静默降级到本地工具Playwright/Chrome
- **所有自动工具失败**:进入交互式手动上传模式
- **部分失败**:记录成功项,继续流程(非阻塞),提供重试建议
## Key Features
1. **MCP优先策略** - 使用托管工具提高可靠性和一致性
2. **多级降级机制** - MCP → Playwright → Chrome → 手动上传
3. **批量并行处理** - 一次处理多个URLMCP支持并行
4. **错误容忍设计** - 部分失败不阻塞整体流程
5. **高度可复用** - 可被imitate-auto-v3、explore-auto等工作流调用
6. **结构化输出** - capture-metadata.json记录完整捕获信息
7. **交互式降级** - 手动模式提供清晰的用户指导
8. **智能路径管理** - 支持session集成和standalone模式
## Integration Points
- **Input**: `--url-map` (target:url pairs) + `--base-path` or `--session`
- **Output**: `{base_path}/screenshots/*.png` + `capture-metadata.json`
- **Callers**: `/workflow:ui-design:imitate-auto-v3`, potentially `/workflow:ui-design:explore-auto-v2`
- **Next Command**: `/workflow:ui-design:extract --images "{screenshot_dir}/*.png"`

View File

@@ -13,13 +13,14 @@ allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*), Task(*)
# Design System Consolidation Command
## Overview
Consolidate user-selected style variants into **independent production-ready design systems**. This command serves as the **Style Planning Phase**, focusing exclusively on design tokens and style guides for the subsequent generation phase.
Consolidate user-selected style variants into **independent production-ready design systems**. This command serves as the **Style Refinement Phase**, transforming raw token proposals from `extract` into finalized, production-ready design tokens and style guides for the subsequent generation phase.
## Core Philosophy
- **Style System Focus**: Exclusively handles design system consolidation
- **System Refinement, Not Generation**: Consumes proposed tokens from `extract` to create finalized design systems; does NOT generate UI prototypes or CSS stylesheets (that's generate's job)
- **Agent-Driven**: Uses ui-design-agent for multi-file generation efficiency
- **Separate Design Systems**: Generates N independent design systems (one per variant)
- **Token Refinement**: Refines `proposed_tokens` from each variant into complete systems
- **Token Refinement**: Refines `proposed_tokens` from each variant into complete, production-ready systems
- **Intelligent Synthesis**: Ensures completeness and consistency
- **Production-Ready**: Complete design system(s) with documentation
- **Matrix-Ready**: Provides style variants for style × layout matrix exploration in generate phase

View File

@@ -14,11 +14,12 @@ allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*)
# Style Extraction Command
## Overview
Extract design style elements from reference images or text prompts using Claude's built-in analysis capabilities. Generates a single, comprehensive `style-cards.json` file containing multiple design variants with complete token proposals.
Extract design style elements from reference images or text prompts using Claude's built-in analysis capabilities. Generates a single, comprehensive `style-cards.json` file containing multiple design variants with complete token **proposals** (raw, unrefined data for consolidation phase).
## Core Philosophy
- **Claude-Native**: 100% Claude-driven analysis, no external tools
- **Single Output**: Only `style-cards.json` with embedded token proposals
- **Token Proposals, Not Final Systems**: Outputs raw token data proposals; does NOT create final CSS or separate design systems (that's consolidate's job)
- **Sequential Execution**: Generate multiple style variants in one pass
- **Flexible Input**: Images, text prompts, or both (hybrid mode)
- **Reproducible**: Deterministic output structure

View File

@@ -114,6 +114,131 @@ ELSE:
synthesis_spec = null
```
### Phase 1.2: Token源智能检测
```bash
REPORT: "🔍 Phase 1.2: Detecting token sources for {style_variants} style(s)..."
token_sources = {} # {style_id: {path: str, quality: str, source: str}}
consolidated_count = 0
proposed_count = 0
FOR style_id IN range(1, style_variants + 1):
# 优先级1Consolidated tokens完整refinement from consolidate command
consolidated_path = "{base_path}/style-consolidation/style-{style_id}/design-tokens.json"
IF exists(consolidated_path):
token_sources[style_id] = {
"path": consolidated_path,
"quality": "consolidated",
"source": "consolidate command"
}
consolidated_count += 1
REPORT: " ✓ Style-{style_id}: Using consolidated tokens (production-ready)"
CONTINUE
# 优先级2Proposed tokens from style-cards.jsonfast-track from extract command
style_cards_path = "{base_path}/style-extraction/style-cards.json"
IF exists(style_cards_path):
# 读取style-cards.json
style_cards_data = Read(style_cards_path)
# 验证variant index有效
IF style_id <= len(style_cards_data.style_cards):
variant_index = style_id - 1
variant = style_cards_data.style_cards[variant_index]
proposed_tokens = variant.proposed_tokens
# 创建临时consolidation目录兼容现有逻辑
temp_consolidation_dir = "{base_path}/style-consolidation/style-{style_id}"
Bash(mkdir -p "{temp_consolidation_dir}")
# 写入proposed tokensFast Token Adaptation
temp_tokens_path = "{temp_consolidation_dir}/design-tokens.json"
Write(temp_tokens_path, JSON.stringify(proposed_tokens, null, 2))
# 创建简化style guide可选but recommended
simple_guide_content = f"""# Design System: {variant.name}
## Design Philosophy
{variant.design_philosophy}
## Description
{variant.description}
## Design Tokens
Complete token specification in `design-tokens.json`.
**Note**: Using proposed tokens from extraction phase (fast-track mode).
For production-ready refinement with philosophy-driven token generation, run `/workflow:ui-design:consolidate` first.
## Color Preview
- Primary: {variant.preview.primary if variant.preview else "N/A"}
- Background: {variant.preview.background if variant.preview else "N/A"}
## Typography Preview
- Heading Font: {variant.preview.font_heading if variant.preview else "N/A"}
- Border Radius: {variant.preview.border_radius if variant.preview else "N/A"}
"""
Write("{temp_consolidation_dir}/style-guide.md", simple_guide_content)
token_sources[style_id] = {
"path": temp_tokens_path,
"quality": "proposed",
"source": "extract command (fast adaptation)"
}
proposed_count += 1
REPORT: " ✓ Style-{style_id}: Using proposed tokens (fast-track)"
REPORT: " Source: {variant.name} from style-cards.json"
WARN: " ⚠️ Tokens not refined - for production quality, run consolidate first"
CONTINUE
ELSE:
ERROR: "style-cards.json exists but does not contain variant {style_id}"
ERROR: " style-cards.json has {len(style_cards_data.style_cards)} variants, but requested style-{style_id}"
SUGGEST: " Reduce --style-variants to {len(style_cards_data.style_cards)} or run extract with more variants"
EXIT 1
# 优先级3错误处理无可用token源
ERROR: "No token source found for style-{style_id}"
ERROR: " Expected either:"
ERROR: " 1. {consolidated_path} (from /workflow:ui-design:consolidate)"
ERROR: " 2. {style_cards_path} (from /workflow:ui-design:extract)"
ERROR: ""
SUGGEST: "Run one of the following commands first:"
SUGGEST: " - /workflow:ui-design:extract --base-path \"{base_path}\" --images \"refs/*.png\" --variants {style_variants}"
SUGGEST: " - /workflow:ui-design:consolidate --base-path \"{base_path}\" --variants {style_variants}"
EXIT 1
# 汇总报告Token sources
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "📊 Token Source Summary:"
REPORT: " Total style variants: {style_variants}"
REPORT: " Consolidated (production-ready): {consolidated_count}/{style_variants}"
REPORT: " Proposed (fast-track): {proposed_count}/{style_variants}"
IF proposed_count > 0:
REPORT: ""
REPORT: "💡 Production Quality Tip:"
REPORT: " Fast-track mode is active for {proposed_count} style(s) using proposed tokens."
REPORT: " For production-ready quality with philosophy-driven refinement:"
REPORT: " /workflow:ui-design:consolidate --base-path \"{base_path}\" --variants {style_variants}"
REPORT: ""
REPORT: " Benefits of consolidate:"
REPORT: " • Philosophy-driven token refinement"
REPORT: " • WCAG AA accessibility validation"
REPORT: " • Complete design system documentation"
REPORT: " • Token gap filling and consistency checks"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# Store token_sources for use in Phase 2
STORE: token_sources, consolidated_count, proposed_count
```
### Phase 1.5: Target Layout Inspiration
```bash
REPORT: "💡 Gathering layout inspiration for {len(target_list)} targets..."
@@ -433,6 +558,11 @@ Design Quality:
✅ Style-Aware Structure: {IF design_space_analysis: 'YES - HTML adapts to design_attributes' ELSE: 'Standard semantic structure'}
✅ Focused generation: Each agent handles single target × single style
✅ Self-Contained CSS: Direct design token usage (no var() dependencies)
✅ Token Quality: {consolidated_count} consolidated, {proposed_count} proposed
{IF proposed_count > 0:
Fast-track mode active: {proposed_count} style(s) using proposed tokens
💡 For production quality: /workflow:ui-design:consolidate --base-path "{base_path}" --variants {style_variants}
}
Output Files:
- Layout Inspirations: {len(target_list)} simple text files

View File

@@ -0,0 +1,621 @@
---
name: imitate-auto-v3
description: High-speed multi-page UI replication with batch screenshot and optional token refinement
usage: /workflow:ui-design:imitate-auto-v3 --url-map "<map>" [--session <id>] [--refine-tokens] [--prompt "<desc>"]
examples:
- /workflow:ui-design:imitate-auto-v3 --url-map "home:https://linear.app, features:https://linear.app/features"
- /workflow:ui-design:imitate-auto-v3 --session WFS-payment --url-map "pricing:https://stripe.com/pricing"
- /workflow:ui-design:imitate-auto-v3 --url-map "dashboard:https://app.com/dash" --refine-tokens
- /workflow:ui-design:imitate-auto-v3 --url-map "home:https://example.com, about:https://example.com/about" --prompt "Focus on minimalist design"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*)
---
# UI Design Imitate-Auto Workflow (V3)
## Overview & Philosophy
**批量多页面快速复现工作流**通过编排器模式组合capture、extract、generate-v2命令实现高效的批量页面复制。
## Parameter Requirements
### Required Parameters
- `--url-map "<map>"` (必需): 目标页面映射
- 格式:`"target1:url1, target2:url2, ..."`
- 示例:`"home:https://linear.app, pricing:https://linear.app/pricing"`
- 第一个target作为主要样式来源
### Optional Parameters
- `--session <id>` (可选): 工作流会话ID
- 集成到现有会话(`.workflow/WFS-{session}/`
- 启用自动设计系统集成Phase 5
- 如不提供standalone模式`.workflow/.design/`
- `--refine-tokens` (可选, 默认: false): 启用完整token refinement
- `false` (默认): 快速路径跳过consolidate~30-60s faster
- `true`: 生产质量执行完整consolidatephilosophy-driven refinement
- `--prompt "<desc>"` (可选): 样式提取指导
- 影响extract命令的分析重点
- 示例:`"Focus on dark mode"`, `"Emphasize minimalist design"`
## 5-Phase Execution Protocol
### Phase 0: 初始化和目标解析
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 UI Design Imitate-Auto V3"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 生成run ID
run_id = "run-$(date +%Y%m%d-%H%M%S)"
# 确定base path和session mode
IF --session:
session_id = {provided_session}
base_path = ".workflow/WFS-{session_id}/design-{run_id}"
session_mode = "integrated"
REPORT: "Mode: Integrated (Session: {session_id})"
ELSE:
session_id = null
base_path = ".workflow/.design/{run_id}"
session_mode = "standalone"
REPORT: "Mode: Standalone"
# 创建base目录
Bash(mkdir -p "{base_path}")
# 解析url-map
url_map_string = {--url-map}
VALIDATE: url_map_string is not empty, "--url-map parameter is required"
# 解析target:url pairs
url_map = {} # {target_name: url}
target_names = []
FOR pair IN split(url_map_string, ","):
pair = pair.strip()
IF ":" NOT IN pair:
ERROR: "Invalid url-map format: '{pair}'"
ERROR: "Expected format: 'target:url'"
ERROR: "Example: 'home:https://example.com, pricing:https://example.com/pricing'"
EXIT 1
target, url = pair.split(":", 1)
target = target.strip().lower().replace(" ", "-")
url = url.strip()
url_map[target] = url
target_names.append(target)
VALIDATE: len(target_names) > 0, "url-map must contain at least one target:url pair"
primary_target = target_names[0] # 第一个作为主要样式来源
refine_tokens_mode = --refine-tokens OR false
# 写入元数据
metadata = {
"workflow": "imitate-auto-v3",
"run_id": run_id,
"session_id": session_id,
"timestamp": current_timestamp(),
"parameters": {
"url_map": url_map,
"refine_tokens": refine_tokens_mode,
"prompt": --prompt OR null
},
"targets": target_names,
"status": "in_progress"
}
Write("{base_path}/.run-metadata.json", JSON.stringify(metadata, null, 2))
REPORT: ""
REPORT: "Configuration:"
REPORT: " Targets: {len(target_names)} pages"
REPORT: " Primary source: '{primary_target}' ({url_map[primary_target]})"
REPORT: " All targets: {', '.join(target_names)}"
REPORT: " Token refinement: {refine_tokens_mode ? 'Enabled (production quality)' : 'Disabled (fast-track)'}"
IF --prompt:
REPORT: " Prompt guidance: \"{--prompt}\""
REPORT: ""
# 初始化TodoWrite
TodoWrite({todos: [
{content: "Initialize and parse url-map", status: "completed", activeForm: "Initializing"},
{content: f"Batch screenshot capture ({len(target_names)} targets)", status: "pending", activeForm: "Capturing screenshots"},
{content: "Extract unified design system", status: "pending", activeForm: "Extracting style"},
{content: refine_tokens_mode ? "Refine design tokens via consolidate" : "Fast token adaptation (skip consolidate)", status: "pending", activeForm: "Processing tokens"},
{content: f"Generate UI for {len(target_names)} targets", status: "pending", activeForm: "Generating UI"},
{content: session_id ? "Integrate design system" : "Standalone completion", status: "pending", activeForm: "Completing"}
]})
```
### Phase 1: 批量截图捕获
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 Phase 1: Batch Screenshot Capture"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 构建url-map字符串传递给capture命令
url_map_command_string = ",".join([f"{name}:{url}" for name, url in url_map.items()])
# 调用capture命令
capture_command = f"/workflow:ui-design:capture --base-path \"{base_path}\" --url-map \"{url_map_command_string}\""
REPORT: "Calling capture command..."
REPORT: f" Command: {capture_command}"
TRY:
SlashCommand(capture_command)
CATCH error:
ERROR: "Screenshot capture failed: {error}"
ERROR: "Cannot proceed without screenshots"
EXIT 1
# capture命令输出到: {base_path}/screenshots/{target}.png + capture-metadata.json
# 验证截图结果
screenshot_metadata_path = "{base_path}/screenshots/capture-metadata.json"
IF NOT exists(screenshot_metadata_path):
ERROR: "capture command did not generate metadata file"
ERROR: "Expected: {screenshot_metadata_path}"
EXIT 1
screenshot_metadata = Read(screenshot_metadata_path)
captured_count = screenshot_metadata.total_captured
total_requested = screenshot_metadata.total_requested
missing_count = total_requested - captured_count
REPORT: ""
REPORT: "✅ Phase 1 complete:"
REPORT: " Captured: {captured_count}/{total_requested} screenshots ({(captured_count/total_requested*100):.1f}%)"
IF missing_count > 0:
missing_targets = [s.target for s in screenshot_metadata.screenshots if not s.captured]
WARN: " ⚠️ Missing {missing_count} screenshots: {', '.join(missing_targets)}"
WARN: " Proceeding with available screenshots for extract phase"
# 如果所有截图都失败,终止
IF captured_count == 0:
ERROR: "No screenshots captured - cannot proceed"
ERROR: "Please check URLs and tool availability"
EXIT 1
TodoWrite(mark_completed: f"Batch screenshot capture ({len(target_names)} targets)",
mark_in_progress: "Extract unified design system")
```
### Phase 2: 统一设计系统提取
```bash
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 Phase 2: Extract Unified Design System"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 使用所有截图作为输入,提取单一设计系统
images_glob = f"{base_path}/screenshots/*.{{png,jpg,jpeg,webp}}"
# 构建extraction prompt
IF --prompt:
user_guidance = {--prompt}
extraction_prompt = f"Extract a single, high-fidelity design system that accurately imitates the visual style from the '{primary_target}' page. Use other screenshots for component consistency. User guidance: {user_guidance}"
ELSE:
extraction_prompt = f"Extract a single, high-fidelity design system that accurately imitates the visual style from the '{primary_target}' page. Use other screenshots to ensure component and pattern consistency across all pages."
# 调用extract命令imitate模式单变体
extract_command = f"/workflow:ui-design:extract --base-path \"{base_path}\" --images \"{images_glob}\" --prompt \"{extraction_prompt}\" --mode imitate --variants 1"
REPORT: "Calling extract command..."
REPORT: f" Mode: imitate (high-fidelity single style)"
REPORT: f" Primary source: '{primary_target}'"
REPORT: f" Images: {images_glob}"
TRY:
SlashCommand(extract_command)
CATCH error:
ERROR: "Style extraction failed: {error}"
ERROR: "Cannot proceed without design system"
EXIT 1
# extract输出到: {base_path}/style-extraction/style-cards.json
# 验证提取结果
style_cards_path = "{base_path}/style-extraction/style-cards.json"
IF NOT exists(style_cards_path):
ERROR: "extract command did not generate style-cards.json"
ERROR: "Expected: {style_cards_path}"
EXIT 1
style_cards = Read(style_cards_path)
IF len(style_cards.style_cards) != 1:
ERROR: "Expected single variant in imitate mode, got {len(style_cards.style_cards)}"
EXIT 1
extracted_style = style_cards.style_cards[0]
REPORT: ""
REPORT: "✅ Phase 2 complete:"
REPORT: " Style: '{extracted_style.name}'"
REPORT: " Philosophy: {extracted_style.design_philosophy}"
REPORT: " Tokens: {count_tokens(extracted_style.proposed_tokens)} proposed tokens"
TodoWrite(mark_completed: "Extract unified design system",
mark_in_progress: refine_tokens_mode ? "Refine design tokens via consolidate" : "Fast token adaptation")
```
### Phase 3: Token处理条件性Consolidate
```bash
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 Phase 3: Token Processing"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
IF refine_tokens_mode:
# 路径A完整consolidate生产级质量
REPORT: "🔧 Using full consolidate for production-ready tokens"
REPORT: " Benefits:"
REPORT: " • Philosophy-driven token refinement"
REPORT: " • WCAG AA accessibility validation"
REPORT: " • Complete design system documentation"
REPORT: " • Token gap filling and consistency checks"
REPORT: ""
consolidate_command = f"/workflow:ui-design:consolidate --base-path \"{base_path}\" --variants 1"
REPORT: f"Calling consolidate command..."
TRY:
SlashCommand(consolidate_command)
CATCH error:
ERROR: "Token consolidation failed: {error}"
ERROR: "Cannot proceed without refined tokens"
EXIT 1
# consolidate输出到: {base_path}/style-consolidation/style-1/design-tokens.json
tokens_path = "{base_path}/style-consolidation/style-1/design-tokens.json"
IF NOT exists(tokens_path):
ERROR: "consolidate command did not generate design-tokens.json"
ERROR: "Expected: {tokens_path}"
EXIT 1
REPORT: ""
REPORT: "✅ Full consolidate complete"
REPORT: " Output: style-consolidation/style-1/"
REPORT: " Quality: Production-ready"
token_quality = "production-ready (consolidated)"
time_spent_estimate = "~60s"
ELSE:
# 路径BFast Token Adaptation快速路径
REPORT: "⚡ Fast token adaptation (skipping consolidate for speed)"
REPORT: " Note: Using proposed tokens from extraction phase"
REPORT: " For production quality, re-run with --refine-tokens flag"
REPORT: ""
# 直接复制proposed_tokens到consolidation目录
style_cards = Read("{base_path}/style-extraction/style-cards.json")
proposed_tokens = style_cards.style_cards[0].proposed_tokens
# 创建目录并写入tokens
consolidation_dir = "{base_path}/style-consolidation/style-1"
Bash(mkdir -p "{consolidation_dir}")
tokens_path = f"{consolidation_dir}/design-tokens.json"
Write(tokens_path, JSON.stringify(proposed_tokens, null, 2))
# 创建简化style guide
variant = style_cards.style_cards[0]
simple_guide = f"""# Design System: {variant.name}
## Design Philosophy
{variant.design_philosophy}
## Description
{variant.description}
## Design Tokens
All tokens in `design-tokens.json` follow OKLCH color space.
**Note**: Generated in fast-track imitate mode using proposed tokens from extraction.
For production-ready quality with philosophy-driven refinement, re-run with `--refine-tokens` flag.
## Color Preview
- Primary: {variant.preview.primary if variant.preview else "N/A"}
- Background: {variant.preview.background if variant.preview else "N/A"}
## Typography Preview
- Heading Font: {variant.preview.font_heading if variant.preview else "N/A"}
## Token Categories
{list_token_categories(proposed_tokens)}
"""
Write(f"{consolidation_dir}/style-guide.md", simple_guide)
REPORT: "✅ Fast adaptation complete (~2s vs ~60s with consolidate)"
REPORT: " Output: style-consolidation/style-1/"
REPORT: " Quality: Proposed (not refined)"
REPORT: " Time saved: ~30-60s"
token_quality = "proposed (fast-track)"
time_spent_estimate = "~2s"
REPORT: ""
REPORT: "Token processing summary:"
REPORT: " Path: {refine_tokens_mode ? 'Full consolidate' : 'Fast adaptation'}"
REPORT: " Quality: {token_quality}"
REPORT: " Time: {time_spent_estimate}"
TodoWrite(mark_completed: refine_tokens_mode ? "Refine design tokens via consolidate" : "Fast token adaptation",
mark_in_progress: f"Generate UI for {len(target_names)} targets")
```
### Phase 4: 批量UI生成
```bash
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 Phase 4: Batch UI Generation"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 构建targets字符串
targets_string = ",".join(target_names)
# 调用generate-v2智能token源检测会自动选择tokens
generate_command = f"/workflow:ui-design:generate-v2 --base-path \"{base_path}\" --targets \"{targets_string}\" --target-type page --style-variants 1 --layout-variants 1"
REPORT: "Calling generate-v2 command..."
REPORT: f" Targets: {targets_string}"
REPORT: f" Configuration: 1 style × 1 layout × {len(target_names)} pages"
REPORT: f" Token source: generate-v2 will auto-detect ({token_quality})"
TRY:
SlashCommand(generate_command)
CATCH error:
ERROR: "UI generation failed: {error}"
ERROR: "Design tokens may be invalid"
EXIT 1
# generate-v2输出到: {base_path}/prototypes/{target}-style-1-layout-1.html
# 验证生成结果
prototypes_dir = "{base_path}/prototypes"
generated_html_files = Glob(f"{prototypes_dir}/*-style-1-layout-1.html")
generated_count = len(generated_html_files)
REPORT: ""
REPORT: "✅ Phase 4 complete:"
REPORT: " Generated: {generated_count} HTML prototypes"
REPORT: " Targets: {', '.join(target_names)}"
REPORT: " Output: {prototypes_dir}/"
IF generated_count < len(target_names):
WARN: " ⚠️ Expected {len(target_names)} prototypes, generated {generated_count}"
WARN: " Some targets may have failed - check generate-v2 output"
TodoWrite(mark_completed: f"Generate UI for {len(target_names)} targets",
mark_in_progress: session_id ? "Integrate design system" : "Standalone completion")
```
### Phase 5: 设计系统集成
```bash
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 Phase 5: Design System Integration"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
IF session_id:
REPORT: "Integrating design system into session {session_id}..."
update_command = f"/workflow:ui-design:update --session {session_id}"
TRY:
SlashCommand(update_command)
CATCH error:
WARN: "Design system integration failed: {error}"
WARN: "Prototypes are still available at {base_path}/prototypes/"
# 不终止因为prototypes已经生成
REPORT: "✅ Design system integrated into session {session_id}"
ELSE:
REPORT: " Standalone mode: Skipping integration"
REPORT: " Prototypes available at: {base_path}/prototypes/"
REPORT: " To integrate later:"
REPORT: " 1. Create a workflow session"
REPORT: " 2. Copy design-tokens.json to session artifacts"
# 更新元数据
metadata = Read("{base_path}/.run-metadata.json")
metadata.status = "completed"
metadata.completion_time = current_timestamp()
metadata.outputs = {
"screenshots": f"{base_path}/screenshots/",
"style_system": f"{base_path}/style-consolidation/style-1/",
"prototypes": f"{base_path}/prototypes/",
"token_quality": token_quality,
"captured_count": captured_count,
"generated_count": generated_count
}
Write("{base_path}/.run-metadata.json", JSON.stringify(metadata, null, 2))
TodoWrite(mark_completed: session_id ? "Integrate design system" : "Standalone completion")
```
### Phase 6: 完成报告
```javascript
TodoWrite({todos: [
{content: "Initialize and parse url-map", status: "completed", activeForm: "Initializing"},
{content: f"Batch screenshot capture ({len(target_names)} targets)", status: "completed", activeForm: "Capturing"},
{content: "Extract unified design system", status: "completed", activeForm: "Extracting"},
{content: refine_tokens_mode ? "Refine design tokens via consolidate" : "Fast token adaptation", status: "completed", activeForm: "Processing"},
{content: f"Generate UI for {len(target_names)} targets", status: "completed", activeForm: "Generating"},
{content: session_id ? "Integrate design system" : "Standalone completion", status: "completed", activeForm: "Completing"}
]});
```
**Completion Message**:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ UI Design Imitate-Auto V3 Complete!
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
━━━ 📊 Workflow Summary ━━━
Mode: Batch Multi-Page Replication
Session: {session_id or "standalone"}
Run ID: {run_id}
Phase 1 - Screenshot Capture: ✅ {captured_count}/{total_requested} screenshots
{IF captured_count < total_requested: f"⚠️ {total_requested - captured_count} missing" ELSE: "All targets captured"}
Phase 2 - Style Extraction: ✅ Single unified design system
Style: {extracted_style.name}
Philosophy: {extracted_style.design_philosophy[:80]}...
Phase 3 - Token Processing: ✅ {token_quality}
{IF refine_tokens_mode:
"Full consolidate (~60s)"
"Quality: Production-ready with philosophy-driven refinement"
ELSE:
"Fast adaptation (~2s, saved ~30-60s)"
"Quality: Proposed tokens (for production, use --refine-tokens)"
}
Phase 4 - UI Generation: ✅ {generated_count} pages generated
Targets: {', '.join(target_names)}
Configuration: 1 style × 1 layout × {generated_count} pages
Phase 5 - Integration: {IF session_id: "✅ Integrated into session" ELSE: "⏭️ Standalone mode"}
━━━ 📂 Output Structure ━━━
{base_path}/
├── screenshots/ # {captured_count} screenshots
│ ├── {target1}.png
│ ├── {target2}.png
│ └── capture-metadata.json
├── style-extraction/ # Design analysis
│ └── style-cards.json
├── style-consolidation/ # {token_quality}
│ └── style-1/
│ ├── design-tokens.json
│ └── style-guide.md
└── prototypes/ # {generated_count} HTML/CSS files
├── {target1}-style-1-layout-1.html + .css
├── {target2}-style-1-layout-1.html + .css
├── compare.html # Interactive preview
└── index.html # Quick navigation
━━━ ⚡ Performance ━━━
Total workflow time: ~{estimate_total_time()} minutes
Screenshot capture: ~{capture_time}
Style extraction: ~{extract_time}
Token processing: ~{token_processing_time}
UI generation: ~{generate_time}
vs imitate-auto v1: ✅ Batch support ({len(target_names)} pages vs 1 page limit)
vs explore-auto: ✅ ~2-3× faster (single style focus{" + skipped consolidate" if not refine_tokens_mode else ""})
━━━ 🌐 Next Steps ━━━
1. Preview prototypes:
• Interactive matrix: Open {base_path}/prototypes/compare.html
• Quick navigation: Open {base_path}/prototypes/index.html
{IF session_id:
2. Create implementation tasks:
/workflow:plan --session {session_id}
3. Generate tests (if needed):
/workflow:test-gen {session_id}
ELSE:
2. To integrate into a workflow session:
• Create session: /workflow:session:start
• Copy design-tokens.json to session artifacts
3. Explore prototypes in {base_path}/prototypes/ directory
}
{IF NOT refine_tokens_mode:
💡 Production Quality Tip:
Fast-track mode used proposed tokens for speed.
For production-ready quality with full token refinement:
/workflow:ui-design:imitate-auto-v3 --url-map "{url_map_command_string}" --refine-tokens {f"--session {session_id}" if session_id else ""}
}
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
## TodoWrite Pattern
```javascript
// Initialize (Phase 0)
TodoWrite({todos: [
{content: "Initialize and parse url-map", status: "in_progress", activeForm: "Initializing"},
{content: "Batch screenshot capture", status: "pending", activeForm: "Capturing screenshots"},
{content: "Extract unified design system", status: "pending", activeForm: "Extracting style"},
{content: refine_tokens ? "Refine tokens via consolidate" : "Fast token adaptation", status: "pending", activeForm: "Processing tokens"},
{content: "Generate UI for all targets", status: "pending", activeForm: "Generating UI"},
{content: "Integrate design system", status: "pending", activeForm: "Integrating"}
]})
// Update after each phase: Mark current completed, next in_progress
```
## Error Handling
### Pre-execution Checks
- **url-map format validation**: Clear error message with format example
- **Empty url-map**: Error and exit
- **Invalid target names**: Regex validation with suggestions
### Phase-Specific Errors
- **Screenshot capture failure (Phase 1)**:
- If total_captured == 0: Terminate workflow
- If partial failure: Warn but continue with available screenshots
- **Style extraction failure (Phase 2)**:
- If extract fails: Terminate with clear error
- If style-cards.json missing: Terminate with debugging info
- **Token processing failure (Phase 3)**:
- Consolidate mode: Terminate if consolidate fails
- Fast mode: Validate proposed_tokens exist before copying
- **UI generation failure (Phase 4)**:
- If generate-v2 fails: Terminate with error
- If generated_count < target_count: Warn but proceed
- **Integration failure (Phase 5)**:
- Non-blocking: Warn but don't terminate
- Prototypes already available
### Recovery Strategies
- **Partial screenshot failure**: Continue with available screenshots, list missing in warning
- **Generate failure**: Report specific target failures, user can re-generate individually
- **Integration failure**: Prototypes still usable, can integrate manually
## Integration Points
- **Input**: `--url-map` (multiple target:url pairs) + optional `--session`, `--refine-tokens`, `--prompt`
- **Output**: Complete design system in `{base_path}/` (screenshots, style-extraction, style-consolidation, prototypes)
- **Sub-commands Called**:
1. `/workflow:ui-design:capture` (Phase 1)
2. `/workflow:ui-design:extract` (Phase 2)
3. `/workflow:ui-design:consolidate` (Phase 3, conditional)
4. `/workflow:ui-design:generate-v2` (Phase 4)
5. `/workflow:ui-design:update` (Phase 5, if --session)
- **Deprecates**: `imitate-auto.md` (v1, single URL only)

View File

@@ -1,6 +1,8 @@
---
name: imitate-auto
description: Imitation-focused UI design workflow - Rapidly replicate a single design style from URL or images (skip exploration, direct to implementation)
deprecated: true
redirect_to: imitate-auto-v3
description: "[DEPRECATED] Use /workflow:ui-design:imitate-auto-v3 for batch multi-page support. This command redirects to v3 with parameter conversion."
usage: /workflow:ui-design:imitate-auto [--url "<url>"] [--images "<glob>"] [--prompt "<desc>"] [--targets "<list>"] [--target-type "page|component"] [--session <id>]
examples:
- /workflow:ui-design:imitate-auto --url "https://linear.app" --targets "home,features,pricing"
@@ -90,11 +92,144 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
- Feedback: modal, alert, toast, badge
- Other: footer, dropdown, avatar, pagination
## 5-Phase Execution
## ⚠️ DEPRECATION NOTICE
### Phase 0: Simplified Initialization
**This command is deprecated in favor of `/workflow:ui-design:imitate-auto-v3`.**
**Reasons for upgrade:**
- ✅ Batch multi-page support (v1 = single URL only)
- ✅ MCP-driven screenshot capture (more reliable)
- ✅ Optional token refinement control (--refine-tokens)
- ✅ Better error handling and progress tracking
**This command now acts as a compatibility wrapper:**
- Automatically redirects to imitate-auto-v3
- Converts legacy parameters to v3 format
- Maintains backward compatibility during transition
## Parameter Conversion & Redirect
### Phase 0: Deprecation Warning and Parameter Conversion
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "⚠️ DEPRECATION WARNING"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: ""
REPORT: "/workflow:ui-design:imitate-auto is DEPRECATED"
REPORT: ""
REPORT: "This command redirects to /workflow:ui-design:imitate-auto-v3"
REPORT: "with automatic parameter conversion for backward compatibility."
REPORT: ""
REPORT: "📋 Key Improvements in V3:"
REPORT: " • Batch multi-page support (v1 limited to single URL)"
REPORT: " • MCP-driven screenshot capture (more reliable)"
REPORT: " • Optional --refine-tokens flag for quality control"
REPORT: " • Better error handling and progress visibility"
REPORT: ""
REPORT: "💡 Migration Guide:"
REPORT: " OLD: /workflow:ui-design:imitate-auto --url 'https://example.com' --targets 'home,pricing'"
REPORT: " NEW: /workflow:ui-design:imitate-auto-v3 --url-map 'home:https://example.com, pricing:https://example.com/pricing'"
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: ""
REPORT: "Converting parameters..."
# Parameter conversion logic
url_value = --url OR null
images_value = --images OR null
targets_value = --targets OR null
prompt_value = --prompt OR null
session_value = --session OR null
# Validate: v1 requires either --url or --images
IF NOT url_value AND NOT images_value:
ERROR: "Either --url or --images must be provided"
ERROR: "For v3 usage, see: /help imitate-auto-v3"
EXIT 1
# Parameter conversion strategy
converted_params = []
# Handle url-map conversion
IF url_value:
# Build url-map from --url and --targets
IF targets_value:
# Multi-target case: url + targets
target_list = split(targets_value, ",")
url_map_pairs = [f"{target.strip()}:{url_value}" for target in target_list]
url_map_string = ", ".join(url_map_pairs)
ELSE:
# Single target case: default to "home"
url_map_string = f"home:{url_value}"
converted_params.append(f'--url-map "{url_map_string}"')
REPORT: " ✓ Converted --url + --targets to --url-map: \"{url_map_string}\""
ELSE IF images_value:
# Images mode: v3 doesn't have direct --images support in imitate-auto-v3
# Need to use extract manually, then call imitate-auto-v3 without capture
WARN: "⚠️ --images parameter not directly supported in v3"
WARN: " v3 focuses on URL-based batch capture"
WARN: ""
WARN: " For image-based workflows, use this sequence:"
WARN: " 1. /workflow:ui-design:extract --images '{images_value}' --mode imitate"
WARN: " 2. /workflow:ui-design:generate-v2 (will auto-detect proposed tokens)"
WARN: ""
ERROR: "Cannot auto-convert --images parameter"
ERROR: "Please use manual workflow sequence above"
EXIT 1
# Pass through other parameters
IF prompt_value:
converted_params.append(f'--prompt "{prompt_value}"')
REPORT: " ✓ Passed through --prompt"
IF session_value:
converted_params.append(f'--session {session_value}')
REPORT: " ✓ Passed through --session"
# Note: v1's --target-type is not needed in v3 (always "page" for url-based workflows)
# Build redirect command
redirect_command = f"/workflow:ui-design:imitate-auto-v3 {' '.join(converted_params)}"
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🔀 Redirecting to v3..."
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: ""
REPORT: "Executing: {redirect_command}"
REPORT: ""
# Execute redirect
SlashCommand(redirect_command)
# If redirect succeeds, the v3 command will handle everything
REPORT: ""
REPORT: "✅ Workflow delegated to imitate-auto-v3"
REPORT: ""
REPORT: "Note: Future usage should call imitate-auto-v3 directly for full feature access."
EXIT 0 # Redirect complete, v3 handles the rest
```
---
## Legacy Documentation (For Reference Only)
**The following sections document the original v1 implementation.**
**This logic is NO LONGER EXECUTED - all calls redirect to v3.**
---
## 5-Phase Execution (LEGACY - NOT EXECUTED)
### Phase 0: Simplified Initialization (LEGACY)
```bash
# THIS CODE IS NOT EXECUTED - KEPT FOR REFERENCE ONLY
run_id = "run-$(date +%Y%m%d-%H%M%S)"
base_path = --session ? ".workflow/WFS-{session}/design-${run_id}" : ".workflow/.design/${run_id}"