Add UI Design Commands: List and Reference Page Generator

- Implemented the '/workflow:ui-design:list' command to list all available design runs with metadata including session, created time, and prototype count.
- Developed the '/workflow:ui-design:reference-page-generator' command to generate multi-component reference pages and documentation from design run extraction, including setup, validation, and preview generation phases.
- Added detailed error handling and usage examples for both commands to enhance user experience and clarity.
This commit is contained in:
catlog22
2025-11-11 20:53:42 +08:00
parent ab09aa4621
commit 836bf4cd1c
39 changed files with 6646 additions and 3062 deletions

View File

@@ -36,7 +36,7 @@ elif [ -n "$SESSION_ID" ]; then
else
# Create new standalone design run
design_id="design-run-$(date +%Y%m%d)-$RANDOM"
relative_path=".workflow/.design/${design_id}"
relative_path=".workflow/${design_id}"
fi
# Create directory and convert to absolute path
@@ -206,7 +206,7 @@ bash($chrome --headless --screenshot="$output_file" --window-size=1920,1080 "$ur
Failed URLs:
home: https://linear.app
Save to: .workflow/.design/design-run-20250110/screenshots/home.png
Save to: .workflow/design-run-20250110/screenshots/home.png
Steps:
1. Visit URL in browser

View File

@@ -266,7 +266,7 @@ STORE: device_type, device_source
### Phase 4: Run Initialization & Directory Setup
```bash
design_id = "design-run-$(date +%Y%m%d)-$RANDOM"
relative_base_path = --session ? ".workflow/WFS-{session}/${design_id}" : ".workflow/.design/${design_id}"
relative_base_path = --session ? ".workflow/WFS-{session}/${design_id}" : ".workflow/${design_id}"
# Create directory and convert to absolute path
Bash(mkdir -p "${relative_base_path}/style-extraction")

View File

@@ -57,7 +57,7 @@ elif [ -n "$SESSION_ID" ]; then
else
# Create new standalone design run
design_id="design-run-$(date +%Y%m%d)-$RANDOM"
relative_path=".workflow/.design/${design_id}"
relative_path=".workflow/${design_id}"
fi
# Create directory structure and convert to absolute path

View File

@@ -69,7 +69,7 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*)
- `--session <id>`: Workflow session ID
- Integrate into existing session (`.workflow/WFS-{session}/`)
- Enable automatic design system integration (Phase 4)
- If not provided: standalone mode (`.workflow/.design/`)
- If not provided: standalone mode (`.workflow/`)
**Input Rules**:
- Must provide: `--input` OR (legacy: `--images`/`--prompt`)
@@ -98,7 +98,7 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*)
**Session Integration**:
- `--session` flag determines session integration or standalone execution
- Integrated: Design system automatically added to session artifacts
- Standalone: Output in `.workflow/.design/{run_id}/`
- Standalone: Output in `.workflow/{run_id}/`
## 5-Phase Execution
@@ -188,7 +188,7 @@ IF --session:
session_mode = "integrated"
ELSE:
session_id = null
relative_base_path = ".workflow/.design/{design_id}"
relative_base_path = ".workflow/{design_id}"
session_mode = "standalone"
# Create base directory and convert to absolute path

View File

@@ -126,13 +126,13 @@ Options:
Examples:
# Simple usage (auto-detect everything)
ui-instantiate-prototypes.sh .design/prototypes
ui-instantiate-prototypes.sh .workflow/design-run-*/prototypes
# With options
ui-instantiate-prototypes.sh .design/prototypes --session-id WFS-auth
ui-instantiate-prototypes.sh .workflow/design-run-*/prototypes --session-id WFS-auth
# Full manual mode
ui-instantiate-prototypes.sh .design/prototypes "login,dashboard" 3 3 --session-id WFS-auth
ui-instantiate-prototypes.sh .workflow/design-run-*/prototypes "login,dashboard" 3 3 --session-id WFS-auth
EOF
}

View File

@@ -3,7 +3,7 @@
"name": "analyze",
"command": "/cli:analyze",
"description": "Read-only codebase analysis using Gemini (default), Qwen, or Codex with auto-pattern detection and template selection",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] analysis target",
"arguments": "[--tool codex|gemini|qwen] [--enhance] analysis target",
"category": "cli",
"subcategory": null,
"usage_scenario": "analysis",
@@ -14,7 +14,7 @@
"name": "chat",
"command": "/cli:chat",
"description": "Read-only Q&A interaction with Gemini/Qwen/Codex for codebase questions with automatic context inference",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] inquiry",
"arguments": "[--tool codex|gemini|qwen] [--enhance] inquiry",
"category": "cli",
"subcategory": null,
"usage_scenario": "general",
@@ -58,7 +58,7 @@
"name": "execute",
"command": "/cli:execute",
"description": "Autonomous code implementation with YOLO auto-approval using Gemini/Qwen/Codex, supports task ID or description input with automatic file pattern detection",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] description or task-id",
"arguments": "[--tool codex|gemini|qwen] [--enhance] description or task-id",
"category": "cli",
"subcategory": null,
"usage_scenario": "implementation",
@@ -69,7 +69,7 @@
"name": "bug-diagnosis",
"command": "/cli:mode:bug-diagnosis",
"description": "Read-only bug root cause analysis using Gemini/Qwen/Codex with systematic diagnosis template for fix suggestions",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] bug description",
"arguments": "[--tool codex|gemini|qwen] [--enhance] [--cd path] bug description",
"category": "cli",
"subcategory": "mode",
"usage_scenario": "analysis",
@@ -80,7 +80,7 @@
"name": "code-analysis",
"command": "/cli:mode:code-analysis",
"description": "Read-only execution path tracing using Gemini/Qwen/Codex with specialized analysis template for call flow and optimization",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] analysis target",
"arguments": "[--tool codex|gemini|qwen] [--enhance] [--cd path] analysis target",
"category": "cli",
"subcategory": "mode",
"usage_scenario": "general",
@@ -91,7 +91,7 @@
"name": "plan",
"command": "/cli:mode:plan",
"description": "Read-only architecture planning using Gemini/Qwen/Codex with strategic planning template for modification plans and impact analysis",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] topic",
"arguments": "[--tool codex|gemini|qwen] [--enhance] [--cd path] topic",
"category": "cli",
"subcategory": "mode",
"usage_scenario": "planning",
@@ -153,6 +153,17 @@
"difficulty": "Intermediate",
"file_path": "memory/skill-memory.md"
},
{
"name": "memory:style-skill-memory",
"command": "/memory:style-skill-memory",
"description": "Generate SKILL memory package from style reference for easy loading and consistent design system usage",
"arguments": "[package-name] [--regenerate]",
"category": "memory",
"subcategory": null,
"usage_scenario": "documentation",
"difficulty": "Intermediate",
"file_path": "memory/style-skill-memory.md"
},
{
"name": "tech-research",
"command": "/memory:tech-research",
@@ -519,7 +530,7 @@
{
"name": "test-cycle-execute",
"command": "/workflow:test-cycle-execute",
"description": "Execute test-fix workflow with dynamic task generation and iterative fix cycles until all tests pass or max iterations reached",
"description": "Execute test-fix workflow with dynamic task generation and iterative fix cycles until test pass rate >= 95% or max iterations reached. Uses @cli-planning-agent for failure analysis and task generation.",
"arguments": "[--resume-session=\\\"session-id\\\"] [--max-iterations=N]",
"category": "workflow",
"subcategory": null,
@@ -651,8 +662,8 @@
{
"name": "animation-extract",
"command": "/workflow:ui-design:animation-extract",
"description": "Extract animation and transition patterns from URLs, CSS, or interactive questioning for design system documentation",
"arguments": "[--base-path <path>] [--session <id>] [--urls \"<list>\"] [--mode <auto|interactive>] [--focus \"<types>\"]",
"description": "Extract animation and transition patterns from prompt inference and image references for design system documentation",
"arguments": "[--design-id <id>] [--session <id>] [--images \"<glob>\"] [--focus \"<types>\"] [--interactive] [--refine]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -663,18 +674,29 @@
"name": "capture",
"command": "/workflow:ui-design:capture",
"description": "Batch screenshot capture for UI design workflows using MCP puppeteer or local fallback with URL mapping",
"arguments": "--url-map \"target:url,...\" [--base-path path] [--session id]",
"arguments": "--url-map \"target:url,...\" [--design-id <id>] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
"difficulty": "Intermediate",
"file_path": "workflow/ui-design/capture.md"
},
{
"name": "workflow:ui-design:codify-style",
"command": "/workflow:ui-design:codify-style",
"description": "Orchestrator to extract styles from code and generate shareable reference package with preview (automatic file discovery)",
"arguments": "<path> [--package-name <name>] [--output-dir <path>] [--overwrite]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "planning",
"difficulty": "Intermediate",
"file_path": "workflow/ui-design/codify-style.md"
},
{
"name": "explore-auto",
"command": "/workflow:ui-design:explore-auto",
"description": "Exploratory UI design workflow with style-centric batch generation, creates design variants from prompts/images with parallel execution",
"arguments": "[--prompt \"<desc>\"] [--images \"<glob>\"] [--targets \"<list>\"] [--target-type \"page|component\"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--interactive] [--batch-plan]",
"description": "Interactive exploratory UI design workflow with style-centric batch generation, creates design variants from prompts/images with parallel execution and user selection",
"arguments": "[--input \"<value>\"] [--targets \"<list>\"] [--target-type \"page|component\"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--batch-plan]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -685,7 +707,7 @@
"name": "explore-layers",
"command": "/workflow:ui-design:explore-layers",
"description": "Interactive deep UI capture with depth-controlled layer exploration using MCP puppeteer",
"arguments": "--url <url> --depth <1-5> [--session id] [--base-path path]",
"arguments": "--url <url> --depth <1-5> [--design-id <id>] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -695,8 +717,8 @@
{
"name": "generate",
"command": "/workflow:ui-design:generate",
"description": "Assemble UI prototypes by combining layout templates with design tokens, pure assembler without new content generation",
"arguments": "[--base-path <path>] [--session <id>]",
"description": "Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation",
"arguments": "[--design-id <id>] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "implementation",
@@ -706,8 +728,8 @@
{
"name": "imitate-auto",
"command": "/workflow:ui-design:imitate-auto",
"description": "High-speed multi-page UI replication with batch screenshot capture and design token extraction",
"arguments": "--url-map \"<map>\" [--capture-mode <batch|deep>] [--depth <1-5>] [--session <id>] [--prompt \"<desc>\"]",
"description": "UI design workflow with direct code/image input for design token extraction and prototype generation",
"arguments": "[--input \"<value>\"] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -717,8 +739,8 @@
{
"name": "workflow:ui-design:import-from-code",
"command": "/workflow:ui-design:import-from-code",
"description": "Import design system from code files (CSS/JS/HTML/SCSS) using parallel agent analysis with final synthesis",
"arguments": "[--base-path <path>] [--source <path>] [--css \\\"<glob>\\\"] [--js \\\"<glob>\\\"] [--scss \\\"<glob>\\\"] [--html \\\"<glob>\\\"] [--style-files \\\"<glob>\\\"] [--session <id>]",
"description": "Import design system from code files (CSS/JS/HTML/SCSS) with automatic file discovery and parallel agent analysis",
"arguments": "[--design-id <id>] [--session <id>] [--source <path>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "planning",
@@ -728,19 +750,41 @@
{
"name": "layout-extract",
"command": "/workflow:ui-design:layout-extract",
"description": "Extract structural layout information from reference images, URLs, or text prompts using Claude analysis",
"arguments": "[--base-path <path>] [--session <id>] [--images \"<glob>\"] [--urls \"<list>\"] [--prompt \"<desc>\"] [--targets \"<list>\"] [--variants <count>] [--device-type <desktop|mobile|tablet|responsive>] [--interactive]",
"description": "Extract structural layout information from reference images, URLs, or text prompts using Claude analysis with variant generation or refinement mode",
"arguments": "[--design-id <id>] [--session <id>] [--images \"<glob>\"] [--urls \"<list>\"] [--prompt \"<desc>\"] [--targets \"<list>\"] [--variants <count>] [--device-type <desktop|mobile|tablet|responsive>] [--interactive] [--refine]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
"difficulty": "Intermediate",
"file_path": "workflow/ui-design/layout-extract.md"
},
{
"name": "list",
"command": "/workflow:ui-design:list",
"description": "List all available design runs with metadata (session, created time, prototype count)",
"arguments": "[--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
"difficulty": "Beginner",
"file_path": "workflow/ui-design/list.md"
},
{
"name": "workflow:ui-design:reference-page-generator",
"command": "/workflow:ui-design:reference-page-generator",
"description": "Generate multi-component reference pages and documentation from design run extraction",
"arguments": "[--design-run <path>] [--package-name <name>] [--output-dir <path>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "planning",
"difficulty": "Intermediate",
"file_path": "workflow/ui-design/reference-page-generator.md"
},
{
"name": "style-extract",
"command": "/workflow:ui-design:style-extract",
"description": "Extract design style from reference images or text prompts using Claude analysis with variant generation",
"arguments": "[--base-path <path>] [--session <id>] [--images \"<glob>\"] [--urls \"<list>\"] [--prompt \"<desc>\"] [--variants <count>] [--interactive]",
"description": "Extract design style from reference images or text prompts using Claude analysis with variant generation or refinement mode",
"arguments": "[--design-id <id>] [--session <id>] [--images \"<glob>\"] [--urls \"<list>\"] [--prompt \"<desc>\"] [--variants <count>] [--interactive] [--refine]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",

View File

@@ -5,7 +5,7 @@
"name": "analyze",
"command": "/cli:analyze",
"description": "Read-only codebase analysis using Gemini (default), Qwen, or Codex with auto-pattern detection and template selection",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] analysis target",
"arguments": "[--tool codex|gemini|qwen] [--enhance] analysis target",
"category": "cli",
"subcategory": null,
"usage_scenario": "analysis",
@@ -16,7 +16,7 @@
"name": "chat",
"command": "/cli:chat",
"description": "Read-only Q&A interaction with Gemini/Qwen/Codex for codebase questions with automatic context inference",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] inquiry",
"arguments": "[--tool codex|gemini|qwen] [--enhance] inquiry",
"category": "cli",
"subcategory": null,
"usage_scenario": "general",
@@ -60,7 +60,7 @@
"name": "execute",
"command": "/cli:execute",
"description": "Autonomous code implementation with YOLO auto-approval using Gemini/Qwen/Codex, supports task ID or description input with automatic file pattern detection",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] description or task-id",
"arguments": "[--tool codex|gemini|qwen] [--enhance] description or task-id",
"category": "cli",
"subcategory": null,
"usage_scenario": "implementation",
@@ -73,7 +73,7 @@
"name": "bug-diagnosis",
"command": "/cli:mode:bug-diagnosis",
"description": "Read-only bug root cause analysis using Gemini/Qwen/Codex with systematic diagnosis template for fix suggestions",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] bug description",
"arguments": "[--tool codex|gemini|qwen] [--enhance] [--cd path] bug description",
"category": "cli",
"subcategory": "mode",
"usage_scenario": "analysis",
@@ -84,7 +84,7 @@
"name": "code-analysis",
"command": "/cli:mode:code-analysis",
"description": "Read-only execution path tracing using Gemini/Qwen/Codex with specialized analysis template for call flow and optimization",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] analysis target",
"arguments": "[--tool codex|gemini|qwen] [--enhance] [--cd path] analysis target",
"category": "cli",
"subcategory": "mode",
"usage_scenario": "general",
@@ -95,7 +95,7 @@
"name": "plan",
"command": "/cli:mode:plan",
"description": "Read-only architecture planning using Gemini/Qwen/Codex with strategic planning template for modification plans and impact analysis",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] topic",
"arguments": "[--tool codex|gemini|qwen] [--enhance] [--cd path] topic",
"category": "cli",
"subcategory": "mode",
"usage_scenario": "planning",
@@ -176,6 +176,17 @@
"difficulty": "Intermediate",
"file_path": "memory/skill-memory.md"
},
{
"name": "memory:style-skill-memory",
"command": "/memory:style-skill-memory",
"description": "Generate SKILL memory package from style reference for easy loading and consistent design system usage",
"arguments": "[package-name] [--regenerate]",
"category": "memory",
"subcategory": null,
"usage_scenario": "documentation",
"difficulty": "Intermediate",
"file_path": "memory/style-skill-memory.md"
},
{
"name": "tech-research",
"command": "/memory:tech-research",
@@ -363,7 +374,7 @@
{
"name": "test-cycle-execute",
"command": "/workflow:test-cycle-execute",
"description": "Execute test-fix workflow with dynamic task generation and iterative fix cycles until all tests pass or max iterations reached",
"description": "Execute test-fix workflow with dynamic task generation and iterative fix cycles until test pass rate >= 95% or max iterations reached. Uses @cli-planning-agent for failure analysis and task generation.",
"arguments": "[--resume-session=\\\"session-id\\\"] [--max-iterations=N]",
"category": "workflow",
"subcategory": null,
@@ -679,8 +690,8 @@
{
"name": "animation-extract",
"command": "/workflow:ui-design:animation-extract",
"description": "Extract animation and transition patterns from URLs, CSS, or interactive questioning for design system documentation",
"arguments": "[--base-path <path>] [--session <id>] [--urls \"<list>\"] [--mode <auto|interactive>] [--focus \"<types>\"]",
"description": "Extract animation and transition patterns from prompt inference and image references for design system documentation",
"arguments": "[--design-id <id>] [--session <id>] [--images \"<glob>\"] [--focus \"<types>\"] [--interactive] [--refine]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -691,18 +702,29 @@
"name": "capture",
"command": "/workflow:ui-design:capture",
"description": "Batch screenshot capture for UI design workflows using MCP puppeteer or local fallback with URL mapping",
"arguments": "--url-map \"target:url,...\" [--base-path path] [--session id]",
"arguments": "--url-map \"target:url,...\" [--design-id <id>] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
"difficulty": "Intermediate",
"file_path": "workflow/ui-design/capture.md"
},
{
"name": "workflow:ui-design:codify-style",
"command": "/workflow:ui-design:codify-style",
"description": "Orchestrator to extract styles from code and generate shareable reference package with preview (automatic file discovery)",
"arguments": "<path> [--package-name <name>] [--output-dir <path>] [--overwrite]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "planning",
"difficulty": "Intermediate",
"file_path": "workflow/ui-design/codify-style.md"
},
{
"name": "explore-auto",
"command": "/workflow:ui-design:explore-auto",
"description": "Exploratory UI design workflow with style-centric batch generation, creates design variants from prompts/images with parallel execution",
"arguments": "[--prompt \"<desc>\"] [--images \"<glob>\"] [--targets \"<list>\"] [--target-type \"page|component\"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--interactive] [--batch-plan]",
"description": "Interactive exploratory UI design workflow with style-centric batch generation, creates design variants from prompts/images with parallel execution and user selection",
"arguments": "[--input \"<value>\"] [--targets \"<list>\"] [--target-type \"page|component\"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--batch-plan]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -713,7 +735,7 @@
"name": "explore-layers",
"command": "/workflow:ui-design:explore-layers",
"description": "Interactive deep UI capture with depth-controlled layer exploration using MCP puppeteer",
"arguments": "--url <url> --depth <1-5> [--session id] [--base-path path]",
"arguments": "--url <url> --depth <1-5> [--design-id <id>] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -723,8 +745,8 @@
{
"name": "generate",
"command": "/workflow:ui-design:generate",
"description": "Assemble UI prototypes by combining layout templates with design tokens, pure assembler without new content generation",
"arguments": "[--base-path <path>] [--session <id>]",
"description": "Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation",
"arguments": "[--design-id <id>] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "implementation",
@@ -734,8 +756,8 @@
{
"name": "imitate-auto",
"command": "/workflow:ui-design:imitate-auto",
"description": "High-speed multi-page UI replication with batch screenshot capture and design token extraction",
"arguments": "--url-map \"<map>\" [--capture-mode <batch|deep>] [--depth <1-5>] [--session <id>] [--prompt \"<desc>\"]",
"description": "UI design workflow with direct code/image input for design token extraction and prototype generation",
"arguments": "[--input \"<value>\"] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -745,8 +767,8 @@
{
"name": "workflow:ui-design:import-from-code",
"command": "/workflow:ui-design:import-from-code",
"description": "Import design system from code files (CSS/JS/HTML/SCSS) using parallel agent analysis with final synthesis",
"arguments": "[--base-path <path>] [--source <path>] [--css \\\"<glob>\\\"] [--js \\\"<glob>\\\"] [--scss \\\"<glob>\\\"] [--html \\\"<glob>\\\"] [--style-files \\\"<glob>\\\"] [--session <id>]",
"description": "Import design system from code files (CSS/JS/HTML/SCSS) with automatic file discovery and parallel agent analysis",
"arguments": "[--design-id <id>] [--session <id>] [--source <path>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "planning",
@@ -756,19 +778,41 @@
{
"name": "layout-extract",
"command": "/workflow:ui-design:layout-extract",
"description": "Extract structural layout information from reference images, URLs, or text prompts using Claude analysis",
"arguments": "[--base-path <path>] [--session <id>] [--images \"<glob>\"] [--urls \"<list>\"] [--prompt \"<desc>\"] [--targets \"<list>\"] [--variants <count>] [--device-type <desktop|mobile|tablet|responsive>] [--interactive]",
"description": "Extract structural layout information from reference images, URLs, or text prompts using Claude analysis with variant generation or refinement mode",
"arguments": "[--design-id <id>] [--session <id>] [--images \"<glob>\"] [--urls \"<list>\"] [--prompt \"<desc>\"] [--targets \"<list>\"] [--variants <count>] [--device-type <desktop|mobile|tablet|responsive>] [--interactive] [--refine]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
"difficulty": "Intermediate",
"file_path": "workflow/ui-design/layout-extract.md"
},
{
"name": "list",
"command": "/workflow:ui-design:list",
"description": "List all available design runs with metadata (session, created time, prototype count)",
"arguments": "[--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
"difficulty": "Beginner",
"file_path": "workflow/ui-design/list.md"
},
{
"name": "workflow:ui-design:reference-page-generator",
"command": "/workflow:ui-design:reference-page-generator",
"description": "Generate multi-component reference pages and documentation from design run extraction",
"arguments": "[--design-run <path>] [--package-name <name>] [--output-dir <path>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "planning",
"difficulty": "Intermediate",
"file_path": "workflow/ui-design/reference-page-generator.md"
},
{
"name": "style-extract",
"command": "/workflow:ui-design:style-extract",
"description": "Extract design style from reference images or text prompts using Claude analysis with variant generation",
"arguments": "[--base-path <path>] [--session <id>] [--images \"<glob>\"] [--urls \"<list>\"] [--prompt \"<desc>\"] [--variants <count>] [--interactive]",
"description": "Extract design style from reference images or text prompts using Claude analysis with variant generation or refinement mode",
"arguments": "[--design-id <id>] [--session <id>] [--images \"<glob>\"] [--urls \"<list>\"] [--prompt \"<desc>\"] [--variants <count>] [--interactive] [--refine]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",

View File

@@ -4,7 +4,7 @@
"name": "analyze",
"command": "/cli:analyze",
"description": "Read-only codebase analysis using Gemini (default), Qwen, or Codex with auto-pattern detection and template selection",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] analysis target",
"arguments": "[--tool codex|gemini|qwen] [--enhance] analysis target",
"category": "cli",
"subcategory": null,
"usage_scenario": "analysis",
@@ -15,7 +15,7 @@
"name": "bug-diagnosis",
"command": "/cli:mode:bug-diagnosis",
"description": "Read-only bug root cause analysis using Gemini/Qwen/Codex with systematic diagnosis template for fix suggestions",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] bug description",
"arguments": "[--tool codex|gemini|qwen] [--enhance] [--cd path] bug description",
"category": "cli",
"subcategory": "mode",
"usage_scenario": "analysis",
@@ -39,7 +39,7 @@
"name": "chat",
"command": "/cli:chat",
"description": "Read-only Q&A interaction with Gemini/Qwen/Codex for codebase questions with automatic context inference",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] inquiry",
"arguments": "[--tool codex|gemini|qwen] [--enhance] inquiry",
"category": "cli",
"subcategory": null,
"usage_scenario": "general",
@@ -61,7 +61,7 @@
"name": "code-analysis",
"command": "/cli:mode:code-analysis",
"description": "Read-only execution path tracing using Gemini/Qwen/Codex with specialized analysis template for call flow and optimization",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] analysis target",
"arguments": "[--tool codex|gemini|qwen] [--enhance] [--cd path] analysis target",
"category": "cli",
"subcategory": "mode",
"usage_scenario": "general",
@@ -291,8 +291,8 @@
{
"name": "animation-extract",
"command": "/workflow:ui-design:animation-extract",
"description": "Extract animation and transition patterns from URLs, CSS, or interactive questioning for design system documentation",
"arguments": "[--base-path <path>] [--session <id>] [--urls \"<list>\"] [--mode <auto|interactive>] [--focus \"<types>\"]",
"description": "Extract animation and transition patterns from prompt inference and image references for design system documentation",
"arguments": "[--design-id <id>] [--session <id>] [--images \"<glob>\"] [--focus \"<types>\"] [--interactive] [--refine]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -303,7 +303,7 @@
"name": "capture",
"command": "/workflow:ui-design:capture",
"description": "Batch screenshot capture for UI design workflows using MCP puppeteer or local fallback with URL mapping",
"arguments": "--url-map \"target:url,...\" [--base-path path] [--session id]",
"arguments": "--url-map \"target:url,...\" [--design-id <id>] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -313,8 +313,8 @@
{
"name": "explore-auto",
"command": "/workflow:ui-design:explore-auto",
"description": "Exploratory UI design workflow with style-centric batch generation, creates design variants from prompts/images with parallel execution",
"arguments": "[--prompt \"<desc>\"] [--images \"<glob>\"] [--targets \"<list>\"] [--target-type \"page|component\"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--interactive] [--batch-plan]",
"description": "Interactive exploratory UI design workflow with style-centric batch generation, creates design variants from prompts/images with parallel execution and user selection",
"arguments": "[--input \"<value>\"] [--targets \"<list>\"] [--target-type \"page|component\"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--batch-plan]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -325,7 +325,7 @@
"name": "explore-layers",
"command": "/workflow:ui-design:explore-layers",
"description": "Interactive deep UI capture with depth-controlled layer exploration using MCP puppeteer",
"arguments": "--url <url> --depth <1-5> [--session id] [--base-path path]",
"arguments": "--url <url> --depth <1-5> [--design-id <id>] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -335,8 +335,8 @@
{
"name": "imitate-auto",
"command": "/workflow:ui-design:imitate-auto",
"description": "High-speed multi-page UI replication with batch screenshot capture and design token extraction",
"arguments": "--url-map \"<map>\" [--capture-mode <batch|deep>] [--depth <1-5>] [--session <id>] [--prompt \"<desc>\"]",
"description": "UI design workflow with direct code/image input for design token extraction and prototype generation",
"arguments": "[--input \"<value>\"] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -346,19 +346,30 @@
{
"name": "layout-extract",
"command": "/workflow:ui-design:layout-extract",
"description": "Extract structural layout information from reference images, URLs, or text prompts using Claude analysis",
"arguments": "[--base-path <path>] [--session <id>] [--images \"<glob>\"] [--urls \"<list>\"] [--prompt \"<desc>\"] [--targets \"<list>\"] [--variants <count>] [--device-type <desktop|mobile|tablet|responsive>] [--interactive]",
"description": "Extract structural layout information from reference images, URLs, or text prompts using Claude analysis with variant generation or refinement mode",
"arguments": "[--design-id <id>] [--session <id>] [--images \"<glob>\"] [--urls \"<list>\"] [--prompt \"<desc>\"] [--targets \"<list>\"] [--variants <count>] [--device-type <desktop|mobile|tablet|responsive>] [--interactive] [--refine]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
"difficulty": "Intermediate",
"file_path": "workflow/ui-design/layout-extract.md"
},
{
"name": "list",
"command": "/workflow:ui-design:list",
"description": "List all available design runs with metadata (session, created time, prototype count)",
"arguments": "[--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
"difficulty": "Beginner",
"file_path": "workflow/ui-design/list.md"
},
{
"name": "style-extract",
"command": "/workflow:ui-design:style-extract",
"description": "Extract design style from reference images or text prompts using Claude analysis with variant generation",
"arguments": "[--base-path <path>] [--session <id>] [--images \"<glob>\"] [--urls \"<list>\"] [--prompt \"<desc>\"] [--variants <count>] [--interactive]",
"description": "Extract design style from reference images or text prompts using Claude analysis with variant generation or refinement mode",
"arguments": "[--design-id <id>] [--session <id>] [--images \"<glob>\"] [--urls \"<list>\"] [--prompt \"<desc>\"] [--variants <count>] [--interactive] [--refine]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "general",
@@ -393,7 +404,7 @@
"name": "execute",
"command": "/cli:execute",
"description": "Autonomous code implementation with YOLO auto-approval using Gemini/Qwen/Codex, supports task ID or description input with automatic file pattern detection",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] description or task-id",
"arguments": "[--tool codex|gemini|qwen] [--enhance] description or task-id",
"category": "cli",
"subcategory": null,
"usage_scenario": "implementation",
@@ -436,7 +447,7 @@
{
"name": "test-cycle-execute",
"command": "/workflow:test-cycle-execute",
"description": "Execute test-fix workflow with dynamic task generation and iterative fix cycles until all tests pass or max iterations reached",
"description": "Execute test-fix workflow with dynamic task generation and iterative fix cycles until test pass rate >= 95% or max iterations reached. Uses @cli-planning-agent for failure analysis and task generation.",
"arguments": "[--resume-session=\\\"session-id\\\"] [--max-iterations=N]",
"category": "workflow",
"subcategory": null,
@@ -491,8 +502,8 @@
{
"name": "generate",
"command": "/workflow:ui-design:generate",
"description": "Assemble UI prototypes by combining layout templates with design tokens, pure assembler without new content generation",
"arguments": "[--base-path <path>] [--session <id>]",
"description": "Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation",
"arguments": "[--design-id <id>] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "implementation",
@@ -516,7 +527,7 @@
"name": "plan",
"command": "/cli:mode:plan",
"description": "Read-only architecture planning using Gemini/Qwen/Codex with strategic planning template for modification plans and impact analysis",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] topic",
"arguments": "[--tool codex|gemini|qwen] [--enhance] [--cd path] topic",
"category": "cli",
"subcategory": "mode",
"usage_scenario": "planning",
@@ -600,16 +611,38 @@
"difficulty": "Advanced",
"file_path": "workflow/tdd-plan.md"
},
{
"name": "workflow:ui-design:codify-style",
"command": "/workflow:ui-design:codify-style",
"description": "Orchestrator to extract styles from code and generate shareable reference package with preview (automatic file discovery)",
"arguments": "<path> [--package-name <name>] [--output-dir <path>] [--overwrite]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "planning",
"difficulty": "Intermediate",
"file_path": "workflow/ui-design/codify-style.md"
},
{
"name": "workflow:ui-design:import-from-code",
"command": "/workflow:ui-design:import-from-code",
"description": "Import design system from code files (CSS/JS/HTML/SCSS) using parallel agent analysis with final synthesis",
"arguments": "[--base-path <path>] [--source <path>] [--css \\\"<glob>\\\"] [--js \\\"<glob>\\\"] [--scss \\\"<glob>\\\"] [--html \\\"<glob>\\\"] [--style-files \\\"<glob>\\\"] [--session <id>]",
"description": "Import design system from code files (CSS/JS/HTML/SCSS) with automatic file discovery and parallel agent analysis",
"arguments": "[--design-id <id>] [--session <id>] [--source <path>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "planning",
"difficulty": "Intermediate",
"file_path": "workflow/ui-design/import-from-code.md"
},
{
"name": "workflow:ui-design:reference-page-generator",
"command": "/workflow:ui-design:reference-page-generator",
"description": "Generate multi-component reference pages and documentation from design run extraction",
"arguments": "[--design-run <path>] [--package-name <name>] [--output-dir <path>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "planning",
"difficulty": "Intermediate",
"file_path": "workflow/ui-design/reference-page-generator.md"
}
],
"documentation": [
@@ -646,6 +679,17 @@
"difficulty": "Intermediate",
"file_path": "memory/skill-memory.md"
},
{
"name": "memory:style-skill-memory",
"command": "/memory:style-skill-memory",
"description": "Generate SKILL memory package from style reference for easy loading and consistent design system usage",
"arguments": "[package-name] [--regenerate]",
"category": "memory",
"subcategory": null,
"usage_scenario": "documentation",
"difficulty": "Intermediate",
"file_path": "memory/style-skill-memory.md"
},
{
"name": "workflow-skill-memory",
"command": "/memory:workflow-skill-memory",

View File

@@ -58,7 +58,7 @@
"name": "analyze",
"command": "/cli:analyze",
"description": "Read-only codebase analysis using Gemini (default), Qwen, or Codex with auto-pattern detection and template selection",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] analysis target",
"arguments": "[--tool codex|gemini|qwen] [--enhance] analysis target",
"category": "cli",
"subcategory": null,
"usage_scenario": "analysis",
@@ -69,7 +69,7 @@
"name": "chat",
"command": "/cli:chat",
"description": "Read-only Q&A interaction with Gemini/Qwen/Codex for codebase questions with automatic context inference",
"arguments": "[--agent] [--tool codex|gemini|qwen] [--enhance] inquiry",
"arguments": "[--tool codex|gemini|qwen] [--enhance] inquiry",
"category": "cli",
"subcategory": null,
"usage_scenario": "general",

View File

@@ -0,0 +1,553 @@
---
name: cli-planning-agent
description: |
Specialized agent for executing CLI analysis tools (Gemini/Qwen) and dynamically generating task JSON files based on analysis results. Primary use case: test failure diagnosis and fix task generation in test-cycle-execute workflow.
Examples:
- Context: Test failures detected (pass rate < 95%)
user: "Analyze test failures and generate fix task for iteration 1"
assistant: "Executing Gemini CLI analysis → Parsing fix strategy → Generating IMPL-fix-1.json"
commentary: Agent encapsulates CLI execution + result parsing + task generation
- Context: Coverage gap analysis
user: "Analyze coverage gaps and generate补充test task"
assistant: "Executing CLI analysis for uncovered code paths → Generating test supplement task"
commentary: Agent handles both analysis and task JSON generation autonomously
color: purple
---
You are a specialized execution agent that bridges CLI analysis tools with task generation. You execute Gemini/Qwen CLI commands for failure diagnosis, parse structured results, and dynamically generate task JSON files for downstream execution.
## Core Responsibilities
1. **Execute CLI Analysis**: Run Gemini/Qwen with appropriate templates and context
2. **Parse CLI Results**: Extract structured information (fix strategies, root causes, modification points)
3. **Generate Task JSONs**: Create IMPL-fix-N.json or IMPL-supplement-N.json dynamically
4. **Save Analysis Reports**: Store detailed CLI output as iteration-N-analysis.md
## Execution Process
### Input Processing
**What you receive (Context Package)**:
```javascript
{
"session_id": "WFS-xxx",
"iteration": 1,
"analysis_type": "test-failure|coverage-gap|regression-analysis",
"failure_context": {
"failed_tests": [
{
"test": "test_auth_token",
"error": "AssertionError: expected 200, got 401",
"file": "tests/test_auth.py",
"line": 45,
"criticality": "high",
"test_type": "integration" // ← NEW: L0: static, L1: unit, L2: integration, L3: e2e
}
],
"error_messages": ["error1", "error2"],
"test_output": "full raw test output...",
"pass_rate": 85.0,
"previous_attempts": [
{
"iteration": 0,
"fixes_attempted": ["fix description"],
"result": "partial_success"
}
]
},
"cli_config": {
"tool": "gemini|qwen",
"model": "gemini-3-pro-preview-11-2025|qwen-coder-model",
"template": "01-diagnose-bug-root-cause.txt",
"timeout": 2400000,
"fallback": "qwen"
},
"task_config": {
"agent": "@test-fix-agent",
"type": "test-fix-iteration",
"max_iterations": 5,
"use_codex": false
}
}
```
### Execution Flow (Three-Phase)
```
Phase 1: CLI Analysis Execution
1. Validate context package and extract failure context
2. Construct CLI command with appropriate template
3. Execute Gemini/Qwen CLI tool
4. Handle errors and fallback to alternative tool if needed
5. Save raw CLI output to .process/iteration-N-cli-output.txt
Phase 2: Results Parsing & Strategy Extraction
1. Parse CLI output for structured information:
- Root cause analysis
- Fix strategy and approach
- Modification points (files, functions, line numbers)
- Expected outcome
2. Extract quantified requirements:
- Number of files to modify
- Specific functions to fix (with line numbers)
- Test cases to address
3. Generate structured analysis report (iteration-N-analysis.md)
Phase 3: Task JSON Generation
1. Load task JSON template (defined below)
2. Populate template with parsed CLI results
3. Add iteration context and previous attempts
4. Write task JSON to .workflow/{session}/.task/IMPL-fix-N.json
5. Return success status and task ID to orchestrator
```
## Core Functions
### 1. CLI Command Construction
**Template-Based Approach with Test Layer Awareness**:
```bash
cd {project_root} && {cli_tool} -p "
PURPOSE: Analyze {test_type} test failures and generate fix strategy for iteration {iteration}
TASK:
• Review {failed_tests.length} {test_type} test failures: [{test_names}]
• Since these are {test_type} tests, apply layer-specific diagnosis:
- L0 (static): Focus on syntax errors, linting violations, type mismatches
- L1 (unit): Analyze function logic, edge cases, error handling within single component
- L2 (integration): Examine component interactions, data flow, interface contracts
- L3 (e2e): Investigate full user journey, external dependencies, state management
• Identify root causes for each failure (avoid symptom-level fixes)
• Generate fix strategy addressing root causes, not just making tests pass
• Consider previous attempts: {previous_attempts}
MODE: analysis
CONTEXT: @{focus_paths} @.process/test-results.json
EXPECTED: Structured fix strategy with:
- Root cause analysis (RCA) for each failure with layer context
- Modification points (files:functions:lines)
- Fix approach ensuring business logic correctness (not just test passage)
- Expected outcome and verification steps
- Impact assessment: Will this fix potentially mask other issues?
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/{template}) |
- For {test_type} tests: {layer_specific_guidance}
- Avoid 'surgical fixes' that mask underlying issues
- Provide specific line numbers for modifications
- Consider previous iteration failures
- Validate fix doesn't introduce new vulnerabilities
- analysis=READ-ONLY
" -m {model} {timeout_flag}
```
**Layer-Specific Guidance Injection**:
```javascript
const layerGuidance = {
"static": "Fix the actual code issue (syntax, type), don't disable linting rules",
"unit": "Ensure function logic is correct; avoid changing assertions to match wrong behavior",
"integration": "Analyze full call stack and data flow across components; fix interaction issues, not symptoms",
"e2e": "Investigate complete user journey and state transitions; ensure fix doesn't break user experience"
};
const guidance = layerGuidance[test_type] || "Analyze holistically, avoid quick patches";
```
**Error Handling & Fallback**:
```javascript
try {
result = executeCLI("gemini", config);
} catch (error) {
if (error.code === 429 || error.code === 404) {
console.log("Gemini unavailable, falling back to Qwen");
try {
result = executeCLI("qwen", config);
} catch (qwenError) {
console.error("Both Gemini and Qwen failed");
// Return minimal analysis with basic fix strategy
return {
status: "degraded",
message: "CLI analysis failed, using fallback strategy",
fix_strategy: generateBasicFixStrategy(failure_context)
};
}
} else {
throw error;
}
}
```
**Fallback Strategy (When All CLI Tools Fail)**:
- Generate basic fix task based on error patterns matching
- Use previous successful fix patterns from fix-history.json
- Limit to simple, low-risk fixes (add null checks, fix typos)
- Mark task with `meta.analysis_quality: "degraded"` flag
- Orchestrator will treat degraded analysis with caution (may skip iteration)
### 2. CLI Output Parsing
**Expected CLI Output Structure** (from bug diagnosis template):
```markdown
## 故障现象描述
- 观察行为: [actual behavior]
- 预期行为: [expected behavior]
## 根本原因分析 (RCA)
- 问题定位: [specific issue location]
- 触发条件: [conditions that trigger the issue]
- 影响范围: [affected scope]
## 涉及文件概览
- src/auth/auth.service.ts (lines 45-60): validateToken function
- src/middleware/auth.middleware.ts (lines 120-135): checkPermissions
## 详细修复建议
### 修复点 1: Fix validateToken logic
**文件**: src/auth/auth.service.ts
**函数**: validateToken (lines 45-60)
**修改内容**:
```diff
- if (token.expired) return false;
+ if (token.exp < Date.now()) return null;
```
**理由**: [explanation]
## 验证建议
- Run: npm test -- tests/test_auth.py::test_auth_token
- Expected: Test passes with status code 200
```
**Parsing Logic**:
```javascript
const parsedResults = {
root_causes: extractSection("根本原因分析"),
modification_points: extractModificationPoints(),
fix_strategy: {
approach: extractSection("详细修复建议"),
files: extractFilesList(),
expected_outcome: extractSection("验证建议")
}
};
```
### 3. Task JSON Generation (Template Definition)
**Task JSON Template for IMPL-fix-N** (Simplified):
```json
{
"id": "IMPL-fix-{iteration}",
"title": "Fix {test_type} test failures - Iteration {iteration}: {fix_summary}",
"status": "pending",
"meta": {
"type": "test-fix-iteration",
"agent": "@test-fix-agent",
"iteration": "{iteration}",
"test_layer": "{dominant_test_type}",
"analysis_report": ".process/iteration-{iteration}-analysis.md",
"cli_output": ".process/iteration-{iteration}-cli-output.txt",
"max_iterations": "{task_config.max_iterations}",
"use_codex": "{task_config.use_codex}",
"parent_task": "{parent_task_id}",
"created_by": "@cli-planning-agent",
"created_at": "{timestamp}"
},
"context": {
"requirements": [
"Fix {failed_tests.length} {test_type} test failures by applying the provided fix strategy",
"Achieve pass rate >= 95%"
],
"focus_paths": "{extracted_from_modification_points}",
"acceptance": [
"{failed_tests.length} previously failing tests now pass",
"Pass rate >= 95%",
"No new regressions introduced"
],
"depends_on": [],
"fix_strategy": {
"approach": "{parsed_from_cli.fix_strategy.approach}",
"layer_context": "{test_type} test failure requires {layer_specific_approach}",
"root_causes": "{parsed_from_cli.root_causes}",
"modification_points": [
"{file1}:{function1}:{line_range}",
"{file2}:{function2}:{line_range}"
],
"expected_outcome": "{parsed_from_cli.fix_strategy.expected_outcome}",
"verification_steps": "{parsed_from_cli.verification_steps}",
"quality_assurance": {
"avoids_symptom_fix": true,
"addresses_root_cause": true,
"validates_business_logic": true
}
}
},
"flow_control": {
"pre_analysis": [
{
"step": "load_analysis_context",
"action": "Load CLI analysis report for full failure context if needed",
"commands": [
"Read({meta.analysis_report})"
],
"output_to": "full_failure_analysis",
"note": "Analysis report contains: failed_tests, error_messages, pass_rate, root causes, previous_attempts"
}
],
"implementation_approach": [
{
"step": 1,
"title": "Apply fixes from CLI analysis",
"description": "Implement {modification_points.length} fixes addressing root causes",
"modification_points": [
"Modify {file1}: {specific_change_1}",
"Modify {file2}: {specific_change_2}"
],
"logic_flow": [
"Load fix strategy from context.fix_strategy",
"Apply fixes to {modification_points.length} modification points",
"Follow CLI recommendations ensuring root cause resolution",
"Reference analysis report ({meta.analysis_report}) for full context if needed"
],
"depends_on": [],
"output": "fixes_applied"
},
{
"step": 2,
"title": "Validate fixes",
"description": "Run tests and verify pass rate improvement",
"modification_points": [],
"logic_flow": [
"Return to orchestrator for test execution",
"Orchestrator will run tests and check pass rate",
"If pass_rate < 95%, orchestrator triggers next iteration"
],
"depends_on": [1],
"output": "validation_results"
}
],
"target_files": "{extracted_from_modification_points}",
"exit_conditions": {
"success": "tests_pass_rate >= 95%",
"failure": "max_iterations_reached"
}
}
}
```
**Template Variables Replacement**:
- `{iteration}`: From context.iteration
- `{test_type}`: Dominant test type from failed_tests (e.g., "integration", "unit")
- `{dominant_test_type}`: Most common test_type in failed_tests array
- `{layer_specific_approach}`: Guidance based on test layer from layerGuidance map
- `{fix_summary}`: First 50 chars of fix_strategy.approach
- `{failed_tests.length}`: Count of failures
- `{modification_points.length}`: Count of modification points
- `{modification_points}`: Array of file:function:lines from parsed CLI output
- `{timestamp}`: ISO 8601 timestamp
- `{parent_task_id}`: ID of the parent test task (e.g., "IMPL-002")
- `{file1}`, `{file2}`, etc.: Specific file paths from modification_points
- `{specific_change_1}`, etc.: Change descriptions for each modification point
### 4. Analysis Report Generation
**Structure of iteration-N-analysis.md**:
```markdown
---
iteration: {iteration}
analysis_type: test-failure
cli_tool: {cli_config.tool}
model: {cli_config.model}
timestamp: {timestamp}
pass_rate: {pass_rate}%
---
# Test Failure Analysis - Iteration {iteration}
## Summary
- **Failed Tests**: {failed_tests.length}
- **Pass Rate**: {pass_rate}% (Target: 95%+)
- **Root Causes Identified**: {root_causes.length}
- **Modification Points**: {modification_points.length}
## Failed Tests Details
{foreach failed_test}
### {test.test}
- **Error**: {test.error}
- **File**: {test.file}:{test.line}
- **Criticality**: {test.criticality}
{endforeach}
## Root Cause Analysis
{CLI output: 根本原因分析 section}
## Fix Strategy
{CLI output: 详细修复建议 section}
## Modification Points
{foreach modification_point}
- `{file}:{function}:{line_range}` - {change_description}
{endforeach}
## Expected Outcome
{CLI output: 验证建议 section}
## Previous Attempts
{foreach previous_attempt}
- **Iteration {attempt.iteration}**: {attempt.result}
- Fixes: {attempt.fixes_attempted}
{endforeach}
## CLI Raw Output
See: `.process/iteration-{iteration}-cli-output.txt`
```
## Quality Standards
### CLI Execution Standards
- **Timeout Management**: Use dynamic timeout (2400000ms = 40min for analysis)
- **Fallback Chain**: Gemini → Qwen (if Gemini fails with 429/404)
- **Error Context**: Include full error details in failure reports
- **Output Preservation**: Save raw CLI output for debugging
### Task JSON Standards
- **Quantification**: All requirements must include counts and explicit lists
- **Specificity**: Modification points must have file:function:line format
- **Measurability**: Acceptance criteria must include verification commands
- **Traceability**: Link to analysis reports and CLI output files
### Analysis Report Standards
- **Structured Format**: Use consistent markdown sections
- **Metadata**: Include YAML frontmatter with key metrics
- **Completeness**: Capture all CLI output sections
- **Cross-References**: Link to test-results.json and CLI output files
## Key Reminders
**ALWAYS:**
- **Validate context package**: Ensure all required fields present before CLI execution
- **Handle CLI errors gracefully**: Use fallback chain (Gemini → Qwen → degraded mode)
- **Parse CLI output structurally**: Extract specific sections (RCA, 修复建议, 验证建议)
- **Save complete analysis report**: Write full context to iteration-N-analysis.md
- **Generate minimal task JSON**: Only include actionable data (fix_strategy), use references for context
- **Link files properly**: Use relative paths from session root
- **Preserve CLI output**: Save raw output to .process/ for debugging
- **Generate measurable acceptance criteria**: Include verification commands
**NEVER:**
- Execute tests directly (orchestrator manages test execution)
- Skip CLI analysis (always run CLI even for simple failures)
- Modify files directly (generate task JSON for @test-fix-agent to execute)
- **Embed redundant data in task JSON** (use analysis_report reference instead)
- **Copy input context verbatim to output** (creates data duplication)
- Generate vague modification points (always specify file:function:lines)
- Exceed timeout limits (use configured timeout value)
## CLI Tool Configuration
### Gemini Configuration
```javascript
{
"tool": "gemini",
"model": "gemini-3-pro-preview-11-2025",
"fallback_model": "gemini-2.5-pro",
"templates": {
"test-failure": "01-diagnose-bug-root-cause.txt",
"coverage-gap": "02-analyze-code-patterns.txt",
"regression": "01-trace-code-execution.txt"
}
}
```
### Qwen Configuration (Fallback)
```javascript
{
"tool": "qwen",
"model": "coder-model",
"templates": {
"test-failure": "01-diagnose-bug-root-cause.txt",
"coverage-gap": "02-analyze-code-patterns.txt"
}
}
```
## Integration with test-cycle-execute
**Orchestrator Call Pattern**:
```javascript
// When pass_rate < 95%
Task(
subagent_type="cli-planning-agent",
description=`Analyze test failures and generate fix task (iteration ${iteration})`,
prompt=`
## Context Package
${JSON.stringify(contextPackage, null, 2)}
## Your Task
1. Execute CLI analysis using ${cli_config.tool}
2. Parse CLI output and extract fix strategy
3. Generate IMPL-fix-${iteration}.json with structured task definition
4. Save analysis report to .process/iteration-${iteration}-analysis.md
5. Report success and task ID back to orchestrator
`
)
```
**Agent Response**:
```javascript
{
"status": "success",
"task_id": "IMPL-fix-{iteration}",
"task_path": ".workflow/{session}/.task/IMPL-fix-{iteration}.json",
"analysis_report": ".process/iteration-{iteration}-analysis.md",
"cli_output": ".process/iteration-{iteration}-cli-output.txt",
"summary": "{fix_strategy.approach first 100 chars}",
"modification_points_count": {count},
"estimated_complexity": "low|medium|high"
}
```
## Example Execution
**Input Context**:
```json
{
"session_id": "WFS-test-session-001",
"iteration": 1,
"analysis_type": "test-failure",
"failure_context": {
"failed_tests": [
{
"test": "test_auth_token_expired",
"error": "AssertionError: expected 401, got 200",
"file": "tests/integration/test_auth.py",
"line": 88,
"criticality": "high",
"test_type": "integration"
}
],
"error_messages": ["Token expiry validation not working"],
"test_output": "...",
"pass_rate": 90.0
},
"cli_config": {
"tool": "gemini",
"template": "01-diagnose-bug-root-cause.txt"
}
}
```
**Execution Steps**:
1. Detect test_type: "integration" → Apply integration-specific diagnosis
2. Execute: `gemini -p "PURPOSE: Analyze integration test failure... [layer-specific context]"`
- CLI prompt includes: "Examine component interactions, data flow, interface contracts"
- Guidance: "Analyze full call stack and data flow across components"
3. Parse: Extract RCA, 修复建议, 验证建议 sections
4. Generate: IMPL-fix-1.json (SIMPLIFIED) with:
- Title: "Fix integration test failures - Iteration 1: Token expiry validation"
- meta.analysis_report: ".process/iteration-1-analysis.md" (Reference, not embedded data)
- meta.test_layer: "integration"
- Requirements: "Fix 1 integration test failures by applying the provided fix strategy"
- fix_strategy.modification_points: ["src/auth/auth.service.ts:validateToken:45-60", "src/middleware/auth.middleware.ts:checkExpiry:120-135"]
- fix_strategy.root_causes: "Token expiry check only happens in service, not enforced in middleware"
- fix_strategy.quality_assurance: {avoids_symptom_fix: true, addresses_root_cause: true}
- **NO failure_context object** - full context available via analysis_report reference
5. Save: iteration-1-analysis.md with full CLI output, layer context, failed_tests details, previous_attempts
6. Return: task_id="IMPL-fix-1", test_layer="integration", status="success"

View File

@@ -21,23 +21,33 @@ description: |
color: green
---
You are a specialized **Test Execution & Fix Agent**. Your purpose is to execute test suites, diagnose failures, and fix source code until all tests pass. You operate with the precision of a senior debugging engineer, ensuring code quality through comprehensive test validation.
You are a specialized **Test Execution & Fix Agent**. Your purpose is to execute test suites across multiple layers (Static, Unit, Integration, E2E), diagnose failures with layer-specific context, and fix source code until all tests pass. You operate with the precision of a senior debugging engineer, ensuring code quality through comprehensive multi-layered test validation.
## Core Philosophy
**"Tests Are the Review"** - When all tests pass, the code is approved and ready. No separate review process is needed.
**"Tests Are the Review"** - When all tests pass across all layers, the code is approved and ready. No separate review process is needed.
**"Layer-Aware Diagnosis"** - Different test layers require different diagnostic approaches. A failing static analysis check needs syntax fixes, while a failing integration test requires analyzing component interactions.
## Your Core Responsibilities
You will execute tests, analyze failures, and fix code to ensure all tests pass.
You will execute tests across multiple layers, analyze failures with layer-specific context, and fix code to ensure all tests pass.
### Test Execution & Fixing Responsibilities:
1. **Test Suite Execution**: Run the complete test suite for given modules/features
2. **Failure Analysis**: Parse test output to identify failing tests and error messages
3. **Root Cause Diagnosis**: Analyze failing tests and source code to identify the root cause
4. **Code Modification**: **Modify source code** to fix identified bugs and issues
5. **Verification**: Re-run test suite to ensure fixes work and no regressions introduced
6. **Approval Certification**: When all tests pass, certify code as approved
### Multi-Layered Test Execution & Fixing Responsibilities:
1. **Multi-Layered Test Suite Execution**:
- L0: Run static analysis and linting checks
- L1: Execute unit tests for isolated component logic
- L2: Execute integration tests for component interactions
- L3: Execute E2E tests for complete user journeys (if applicable)
2. **Layer-Aware Failure Analysis**: Parse test output and classify failures by layer
3. **Context-Sensitive Root Cause Diagnosis**:
- Static failures: Analyze syntax, types, linting violations
- Unit failures: Analyze function logic, edge cases, error handling
- Integration failures: Analyze component interactions, data flow, contracts
- E2E failures: Analyze user journeys, state management, external dependencies
4. **Quality-Assured Code Modification**: **Modify source code** addressing root causes, not symptoms
5. **Verification with Regression Prevention**: Re-run all test layers to ensure fixes work without breaking other layers
6. **Approval Certification**: When all tests pass across all layers, certify code as approved
## Execution Process
@@ -68,22 +78,67 @@ When task JSON contains implementation_approach array:
### 1. Context Assessment & Test Discovery
- Analyze task context to identify test files and source code paths
- Load test framework configuration (Jest, Pytest, Mocha, etc.)
- **Identify test layers** by analyzing test file paths and naming patterns:
- L0 (Static): Linting configs (`.eslintrc`, `tsconfig.json`), static analysis tools
- L1 (Unit): `*.test.*`, `*.spec.*` in `__tests__/`, `tests/unit/`
- L2 (Integration): `tests/integration/`, `*.integration.test.*`
- L3 (E2E): `tests/e2e/`, `*.e2e.test.*`, `cypress/`, `playwright/`
- **context-package.json** (CCW Workflow): Extract artifact paths using `jq -r '.brainstorm_artifacts.role_analyses[].files[].path'`
- Identify test command from project configuration
- Identify test commands from project configuration
```bash
# Detect test framework and command
# Detect test framework and multi-layered commands
if [ -f "package.json" ]; then
TEST_CMD=$(cat package.json | jq -r '.scripts.test')
# Extract layer-specific test commands
LINT_CMD=$(cat package.json | jq -r '.scripts.lint // "eslint ."')
UNIT_CMD=$(cat package.json | jq -r '.scripts["test:unit"] // .scripts.test')
INTEGRATION_CMD=$(cat package.json | jq -r '.scripts["test:integration"] // ""')
E2E_CMD=$(cat package.json | jq -r '.scripts["test:e2e"] // ""')
elif [ -f "pytest.ini" ] || [ -f "setup.py" ]; then
TEST_CMD="pytest"
LINT_CMD="ruff check . || flake8 ."
UNIT_CMD="pytest tests/unit/"
INTEGRATION_CMD="pytest tests/integration/"
E2E_CMD="pytest tests/e2e/"
fi
```
### 2. Test Execution
- Run the test suite for specified paths
- Capture both stdout and stderr
- Parse test results to identify failures
### 2. Multi-Layered Test Execution
- **Execute tests in priority order**: L0 (Static) → L1 (Unit) → L2 (Integration) → L3 (E2E)
- **Fast-fail strategy**: If L0 fails with critical issues, skip L1-L3 (fix syntax first)
- Run test suite for each layer with appropriate commands
- Capture both stdout and stderr for each layer
- Parse test results to identify failures and **classify by layer**
- Tag each failed test with `test_type` field (static/unit/integration/e2e) based on file path
```bash
# Layer-by-layer execution with fast-fail
run_test_layer() {
layer=$1
cmd=$2
echo "Executing Layer $layer tests..."
$cmd 2>&1 | tee ".process/test-layer-$layer-output.txt"
# Parse results and tag with test_type
parse_test_results ".process/test-layer-$layer-output.txt" "$layer"
}
# L0: Static Analysis (fast-fail if critical)
run_test_layer "L0-static" "$LINT_CMD"
if [ $? -ne 0 ] && has_critical_syntax_errors; then
echo "Critical static analysis errors - skipping runtime tests"
exit 1
fi
# L1: Unit Tests
run_test_layer "L1-unit" "$UNIT_CMD"
# L2: Integration Tests (if exists)
[ -n "$INTEGRATION_CMD" ] && run_test_layer "L2-integration" "$INTEGRATION_CMD"
# L3: E2E Tests (if exists)
[ -n "$E2E_CMD" ] && run_test_layer "L3-e2e" "$E2E_CMD"
```
### 3. Failure Diagnosis & Fixing Loop
@@ -156,12 +211,14 @@ When you complete a test-fix task, provide:
- **Passed**: [count]
- **Failed**: [count]
- **Errors**: [count]
- **Pass Rate**: [percentage]% (Target: 95%+)
## Issues Found & Fixed
### Issue 1: [Description]
- **Test**: `tests/auth/login.test.ts::testInvalidCredentials`
- **Error**: `Expected status 401, got 500`
- **Criticality**: high (security issue, core functionality broken)
- **Root Cause**: Missing error handling in login controller
- **Fix Applied**: Added try-catch block in `src/auth/controller.ts:45`
- **Files Modified**: `src/auth/controller.ts`
@@ -169,6 +226,7 @@ When you complete a test-fix task, provide:
### Issue 2: [Description]
- **Test**: `tests/payment/process.test.ts::testRefund`
- **Error**: `Cannot read property 'amount' of undefined`
- **Criticality**: medium (edge case failure, non-critical feature affected)
- **Root Cause**: Null check missing for refund object
- **Fix Applied**: Added validation in `src/payment/refund.ts:78`
- **Files Modified**: `src/payment/refund.ts`
@@ -178,6 +236,7 @@ When you complete a test-fix task, provide:
**All tests passing**
- **Total Tests**: [count]
- **Passed**: [count]
- **Pass Rate**: 100%
- **Duration**: [time]
## Code Approval
@@ -190,6 +249,71 @@ All tests pass - code is ready for deployment.
- `src/payment/refund.ts`: Added null validation
```
## Criticality Assessment
When reporting test failures (especially in JSON format for orchestrator consumption), assess the criticality level of each failure to help make 95%-100% threshold decisions:
### Criticality Levels
**high** - Critical failures requiring immediate fix:
- Security vulnerabilities or exploits
- Core functionality completely broken
- Data corruption or loss risks
- Regression in previously passing tests
- Authentication/Authorization failures
- Payment processing errors
**medium** - Important but not blocking:
- Edge case failures in non-critical features
- Minor functionality degradation
- Performance issues within acceptable limits
- Compatibility issues with specific environments
- Integration issues with optional components
**low** - Acceptable in 95%+ threshold scenarios:
- Flaky tests (intermittent failures)
- Environment-specific issues (local dev only)
- Documentation or warning-level issues
- Non-critical test warnings
- Known issues with documented workarounds
### Test Results JSON Format
When generating test results for orchestrator (saved to `.process/test-results.json`):
```json
{
"total": 10,
"passed": 9,
"failed": 1,
"pass_rate": 90.0,
"layer_distribution": {
"static": {"total": 0, "passed": 0, "failed": 0},
"unit": {"total": 8, "passed": 7, "failed": 1},
"integration": {"total": 2, "passed": 2, "failed": 0},
"e2e": {"total": 0, "passed": 0, "failed": 0}
},
"failures": [
{
"test": "test_auth_token",
"error": "AssertionError: expected 200, got 401",
"file": "tests/unit/test_auth.py",
"line": 45,
"criticality": "high",
"test_type": "unit"
}
]
}
```
### Decision Support
**For orchestrator decision-making**:
- Pass rate 100% + all tests pass → ✅ SUCCESS (proceed to completion)
- Pass rate >= 95% + all failures are "low" criticality → ✅ PARTIAL SUCCESS (review and approve)
- Pass rate >= 95% + any "high" or "medium" criticality failures → ⚠️ NEEDS FIX (continue iteration)
- Pass rate < 95% → ❌ FAILED (continue iteration or abort)
## Important Reminders
**ALWAYS:**

View File

@@ -1,7 +1,7 @@
---
name: analyze
description: Read-only codebase analysis using Gemini (default), Qwen, or Codex with auto-pattern detection and template selection
argument-hint: "[--agent] [--tool codex|gemini|qwen] [--enhance] analysis target"
argument-hint: "[--tool codex|gemini|qwen] [--enhance] analysis target"
allowed-tools: SlashCommand(*), Bash(*), TodoWrite(*), Read(*), Glob(*), Task(*)
---
@@ -19,7 +19,6 @@ Quick codebase analysis using CLI tools. **Read-only - does NOT modify code**.
## Parameters
- `--tool <gemini|qwen|codex>` - Tool selection (default: gemini)
- `--agent` - Use cli-execution-agent for automated context discovery
- `--enhance` - Use `/enhance-prompt` for context-aware enhancement
- `<analysis-target>` - Description of what to analyze
@@ -42,43 +41,41 @@ Quick codebase analysis using CLI tools. **Read-only - does NOT modify code**.
## Execution Flow
### Standard Mode
1. Parse tool selection (default: gemini)
2. Optional: enhance with `/enhance-prompt`
3. Auto-detect file patterns from keywords
4. Build command with analysis template
5. Execute analysis (read-only)
6. Save results
### Agent Mode (`--agent`)
Delegates to agent for intelligent analysis:
Uses **cli-execution-agent** (default) for automated analysis:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Codebase analysis",
description="Codebase analysis with pattern detection",
prompt=`
Task: ${analysis_target}
Mode: analyze
Tool: ${tool_flag || 'auto-select'} // gemini|qwen|codex
Enhance: ${enhance_flag || false}
Tool: ${tool_flag || 'gemini'}
Enhance: ${enhance_flag}
Execute codebase analysis with auto-pattern detection:
Agent responsibilities:
1. Context Discovery:
- Discover relevant files/patterns
- Identify analysis scope
- Build file context
- Extract keywords from analysis target
- Auto-detect file patterns (auth→auth files, component→components, etc.)
- Discover additional relevant files using MCP
- Build comprehensive file context
2. CLI Command Generation:
- Build Gemini/Qwen/Codex command
- Apply analysis template
- Include discovered files
2. Template Selection:
- Auto-select analysis template based on keywords
- Apply appropriate analysis methodology
- Include @CLAUDE.md for project context
3. Execution & Output:
- Execute analysis
- Generate insights report
- Save to .workflow/.chat/ or .scratchpad/
3. CLI Command Construction:
- Tool: ${tool_flag || 'gemini'} (qwen fallback, codex for deep analysis)
- Context: @CLAUDE.md + auto-detected patterns + discovered files
- Mode: analysis (read-only)
- Expected: Insights, recommendations, pattern analysis
4. Execution & Output:
- Execute CLI tool with assembled context
- Generate comprehensive analysis report
- Save to .workflow/WFS-[id]/.chat/analyze-[timestamp].md (or .scratchpad/)
`
)
```
@@ -86,51 +83,5 @@ Task(
## Core Rules
- **Read-only**: Analyzes code, does NOT modify files
- **Auto-pattern**: Detects file patterns from keywords
- **Template-based**: Auto-selects analysis template
- **Output**: Saves to `.workflow/WFS-[id]/.chat/` or `.scratchpad/`
## File Pattern Auto-Detection
Keywords → file patterns:
- "auth" → `@**/*auth* @**/*user*`
- "component" → `@src/components/**/*`
- "API" → `@**/api/**/* @**/routes/**/*`
- "test" → `@**/*.test.* @**/*.spec.*`
- Generic → `@src/**/*`
## CLI Command Templates
**Gemini/Qwen**:
```bash
cd . && gemini -p "
PURPOSE: [goal]
TASK: [analysis type]
MODE: analysis
CONTEXT: @CLAUDE.md [auto-detected patterns]
EXPECTED: Insights, recommendations
RULES: [auto-selected template]
"
# Qwen: Replace 'gemini' with 'qwen'
```
**Codex**:
```bash
codex -C . --full-auto exec "
PURPOSE: [goal]
TASK: [analysis type]
MODE: analysis
CONTEXT: @CLAUDE.md [patterns]
EXPECTED: Deep insights
RULES: [template]
" -m gpt-5 --skip-git-repo-check -s danger-full-access
```
## Output
- **With session**: `.workflow/WFS-[id]/.chat/analyze-[timestamp].md`
- **No session**: `.workflow/.scratchpad/analyze-[desc]-[timestamp].md`
## Notes
- See `intelligent-tools-strategy.md` for detailed tool usage and templates
- **Auto-pattern**: Detects file patterns from keywords (auth→auth files, component→components, API→api/routes, test→test files)
- **Output**: `.workflow/WFS-[id]/.chat/analyze-[timestamp].md` (or `.scratchpad/` if no session)

View File

@@ -1,7 +1,7 @@
---
name: chat
description: Read-only Q&A interaction with Gemini/Qwen/Codex for codebase questions with automatic context inference
argument-hint: "[--agent] [--tool codex|gemini|qwen] [--enhance] inquiry"
argument-hint: "[--tool codex|gemini|qwen] [--enhance] inquiry"
allowed-tools: SlashCommand(*), Bash(*), Task(*)
---
@@ -19,7 +19,6 @@ Direct Q&A interaction with CLI tools for codebase analysis. **Read-only - does
## Parameters
- `--tool <gemini|qwen|codex>` - Tool selection (default: gemini)
- `--agent` - Use cli-execution-agent for automated context discovery
- `--enhance` - Enhance inquiry with `/enhance-prompt`
- `<inquiry>` (Required) - Question or analysis request
@@ -42,42 +41,36 @@ Direct Q&A interaction with CLI tools for codebase analysis. **Read-only - does
## Execution Flow
### Standard Mode
1. Parse tool selection (default: gemini)
2. Optional: enhance with `/enhance-prompt`
3. Assemble context: `@CLAUDE.md` + inferred files
4. Execute Q&A (read-only)
5. Return answer
### Agent Mode (`--agent`)
Delegates to agent for intelligent Q&A:
Uses **cli-execution-agent** (default) for automated Q&A:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Codebase Q&A",
description="Codebase Q&A with intelligent context discovery",
prompt=`
Task: ${inquiry}
Mode: chat (Q&A)
Tool: ${tool_flag || 'auto-select'} // gemini|qwen|codex
Enhance: ${enhance_flag || false}
Mode: chat
Tool: ${tool_flag || 'gemini'}
Enhance: ${enhance_flag}
Execute codebase Q&A with intelligent context discovery:
Agent responsibilities:
1. Context Discovery:
- Discover files relevant to question
- Identify key code sections
- Build precise context
- Parse inquiry to identify relevant topics/keywords
- Discover related files using MCP/ripgrep (prioritize precision)
- Include @CLAUDE.md + discovered files
- Validate context relevance to question
2. CLI Command Generation:
- Build Gemini/Qwen/Codex command
- Include discovered context
- Apply Q&A template
2. CLI Command Construction:
- Tool: ${tool_flag || 'gemini'} (qwen fallback, codex for deep dives)
- Context: @CLAUDE.md + discovered file patterns
- Mode: analysis (read-only)
- Expected: Clear, accurate answer with code references
3. Execution & Output:
- Execute Q&A analysis
- Generate detailed answer
- Save to .workflow/.chat/ or .scratchpad/
- Execute CLI tool with assembled context
- Validate answer completeness
- Save to .workflow/WFS-[id]/.chat/chat-[timestamp].md (or .scratchpad/)
`
)
```
@@ -86,40 +79,4 @@ Task(
- **Read-only**: Provides answers, does NOT modify code
- **Context**: `@CLAUDE.md` + inferred or all files (`@**/*`)
- **Output**: Saves to `.workflow/WFS-[id]/.chat/` or `.scratchpad/`
## CLI Command Templates
**Gemini/Qwen**:
```bash
cd . && gemini -p "
PURPOSE: Answer question
TASK: [inquiry]
MODE: analysis
CONTEXT: @CLAUDE.md [inferred or @**/*]
EXPECTED: Clear answer
RULES: Focus on accuracy
"
# Qwen: Replace 'gemini' with 'qwen'
```
**Codex**:
```bash
codex -C . --full-auto exec "
PURPOSE: Answer question
TASK: [inquiry]
MODE: analysis
CONTEXT: @CLAUDE.md [inferred or @**/*]
EXPECTED: Detailed answer
RULES: Technical depth
" -m gpt-5 --skip-git-repo-check -s danger-full-access
```
## Output
- **With session**: `.workflow/WFS-[id]/.chat/chat-[timestamp].md`
- **No session**: `.workflow/.scratchpad/chat-[desc]-[timestamp].md`
## Notes
- See `intelligent-tools-strategy.md` for detailed tool usage and templates
- **Output**: `.workflow/WFS-[id]/.chat/chat-[timestamp].md` (or `.scratchpad/` if no session)

View File

@@ -1,7 +1,7 @@
---
name: execute
description: Autonomous code implementation with YOLO auto-approval using Gemini/Qwen/Codex, supports task ID or description input with automatic file pattern detection
argument-hint: "[--agent] [--tool codex|gemini|qwen] [--enhance] description or task-id"
argument-hint: "[--tool codex|gemini|qwen] [--enhance] description or task-id"
allowed-tools: SlashCommand(*), Bash(*), Task(*)
---
@@ -39,7 +39,7 @@ Auto-approves: file pattern inference, execution, **file modifications**, summar
- Input: Workflow task identifier (e.g., `IMPL-001`)
- Process: Task JSON parsing → Scope analysis → Execute
**3. Agent Mode** (`--agent` flag):
**3. Agent Mode** (default):
- Input: Description or task-id
- Process: 5-Phase Workflow → Context Discovery → Optimal Tool Selection → Execute
@@ -68,8 +68,7 @@ Use `resume --last` when current task extends/relates to previous execution. See
## Parameters
- `--agent` - Use cli-execution-agent for automated context discovery (5-phase intelligent mode)
- `--tool <codex|gemini|qwen>` - Select CLI tool (default: gemini, ignored in agent mode unless specified)
- `--tool <codex|gemini|qwen>` - Select CLI tool (default: auto-select by agent based on complexity)
- `--enhance` - Enhance input with `/enhance-prompt` first (Description Mode only)
- `<description|task-id>` - Natural language description or task identifier
- `--debug` - Verbose logging
@@ -83,96 +82,83 @@ Use `resume --last` when current task extends/relates to previous execution. See
**Task Integration**: Load from `.task/[TASK-ID].json`, update status, generate summary
## Output Routing
## Execution Flow
**Execution Log Destination**:
- **IF** active workflow session exists:
- Save to `.workflow/WFS-[id]/.chat/execute-[timestamp].md`
- Update task status in `.task/[TASK-ID].json` (if task ID provided)
- Generate summary in `.workflow/WFS-[id]/.summaries/[TASK-ID]-summary.md`
- **ELSE** (no active session):
- **Option 1**: Create new workflow session for task
- **Option 2**: Save to `.workflow/.scratchpad/execute-[description]-[timestamp].md`
Uses **cli-execution-agent** (default) for automated implementation:
**Output Files** (when active session exists):
- Execution log: `.workflow/WFS-[id]/.chat/execute-[timestamp].md`
- Task summary: `.workflow/WFS-[id]/.summaries/[TASK-ID]-summary.md` (if task ID)
- Modified code: Project files per implementation
**Examples**:
- During session `WFS-auth-system`, executing `IMPL-001`:
- Log: `.workflow/WFS-auth-system/.chat/execute-20250105-143022.md`
- Summary: `.workflow/WFS-auth-system/.summaries/IMPL-001-summary.md`
- No session, ad-hoc implementation:
- Log: `.workflow/.scratchpad/execute-jwt-auth-20250105-143045.md`
## Execution Modes
### Standard Mode (Default)
```bash
# Gemini/Qwen: MODE=write with --approval-mode yolo
cd . && gemini --approval-mode yolo "
PURPOSE: [implementation goal]
TASK: [specific implementation]
MODE: write
CONTEXT: @CLAUDE.md [auto-detected files]
EXPECTED: Working implementation with code changes
RULES: [constraints] | Auto-approve all changes
"
# Codex: MODE=auto with danger-full-access
codex -C . --full-auto exec "
PURPOSE: [implementation goal]
TASK: [specific implementation]
MODE: auto
CONTEXT: [auto-detected files]
EXPECTED: Complete implementation with tests
" --skip-git-repo-check -s danger-full-access
```
### Agent Mode (`--agent` flag)
Delegate implementation to `cli-execution-agent` for intelligent execution with automated context discovery.
**Agent invocation**:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Implement with automated context discovery and optimal tool selection",
description="Autonomous code implementation with YOLO auto-approval",
prompt=`
Task: ${description_or_task_id}
Mode: execute
Tool Preference: ${tool_flag || 'auto-select'}
${enhance_flag ? 'Enhance: true' : ''}
Tool: ${tool_flag || 'auto-select'}
Enhance: ${enhance_flag}
Task-ID: ${task_id}
Agent will autonomously:
- Discover implementation files and dependencies
- Assess complexity and select optimal tool
- Execute with YOLO permissions (auto-approve)
- Generate task summary if task-id provided
Execute autonomous code implementation with full modification permissions:
1. Task Analysis:
${task_id ? '- Load task spec from .task/' + task_id + '.json' : ''}
- Parse requirements and implementation scope
- Classify complexity (simple/medium/complex)
- Extract keywords for context discovery
2. Context Discovery:
- Discover implementation files using MCP/ripgrep
- Identify existing patterns and conventions (CLAUDE.md)
- Map dependencies and integration points
- Gather related tests and documentation
- Auto-detect file patterns from keywords
3. Tool Selection & Execution:
- Complexity assessment:
* Simple/Medium → Gemini/Qwen (MODE=write, --approval-mode yolo)
* Complex → Codex (MODE=auto, --skip-git-repo-check -s danger-full-access)
- Tool preference: ${tool_flag || 'auto-select based on complexity'}
- Apply appropriate implementation template
- Execute with YOLO auto-approval (bypasses all confirmations)
4. Implementation:
- Modify/create/delete code files per requirements
- Follow existing code patterns and conventions
- Include comprehensive context in CLI command
- Ensure working implementation with proper error handling
5. Output & Documentation:
- Save execution log: .workflow/WFS-[id]/.chat/execute-[timestamp].md
${task_id ? '- Generate task summary: .workflow/WFS-[id]/.summaries/' + task_id + '-summary.md' : ''}
${task_id ? '- Update task status in .task/' + task_id + '.json' : ''}
- Document all code changes made
⚠️ YOLO Mode: All file operations auto-approved without confirmation
`
)
```
The agent handles all phases internally, including complexity-based tool selection.
**Output**: `.workflow/WFS-[id]/.chat/execute-[timestamp].md` + `.summaries/[TASK-ID]-summary.md` (or `.scratchpad/` if no session)
## Examples
**Basic Implementation (Standard Mode)** (modifies code):
**Basic Implementation** (modifies code):
```bash
/cli:execute "implement JWT authentication with middleware"
# Executes: Creates auth middleware, updates routes, modifies config
# Agent Phase 1: Classifies intent=execute, complexity=medium, keywords=['jwt', 'auth', 'middleware']
# Agent Phase 2: Discovers auth patterns, existing middleware structure
# Agent Phase 3: Selects Gemini (medium complexity)
# Agent Phase 4: Executes with auto-approval
# Result: NEW/MODIFIED code files with JWT implementation
```
**Intelligent Implementation (Agent Mode)** (modifies code):
**Complex Implementation** (modifies code):
```bash
/cli:execute --agent "implement OAuth2 authentication with token refresh"
# Phase 1: Classifies intent=execute, complexity=complex, keywords=['oauth2', 'auth', 'token', 'refresh']
# Phase 2: MCP discovers auth patterns, existing middleware, JWT dependencies
# Phase 3: Enhances prompt with discovered patterns and best practices
# Phase 4: Selects Codex (complex task), executes with comprehensive context
# Phase 5: Saves execution log + generates implementation summary
/cli:execute "implement OAuth2 authentication with token refresh"
# Agent Phase 1: Classifies intent=execute, complexity=complex, keywords=['oauth2', 'auth', 'token', 'refresh']
# Agent Phase 2: MCP discovers auth patterns, existing middleware, JWT dependencies
# Agent Phase 3: Enhances prompt with discovered patterns and best practices
# Agent Phase 4: Selects Codex (complex task), executes with comprehensive context
# Agent Phase 5: Saves execution log + generates implementation summary
# Result: Complete OAuth2 implementation + detailed execution log
```
@@ -214,8 +200,3 @@ The agent handles all phases internally, including complexity-based tool selecti
| `/cli:analyze` | Understand code | NO | N/A |
| `/cli:chat` | Ask questions | NO | N/A |
| `/cli:execute` | **Implement** | **YES** | **YES** |
## Notes
- Command templates, YOLO mode details, and session management: see intelligent-tools-strategy.md (loaded in memory)
- **Code Modification**: This command modifies code - execution logs document changes made

View File

@@ -1,7 +1,7 @@
---
name: bug-diagnosis
description: Read-only bug root cause analysis using Gemini/Qwen/Codex with systematic diagnosis template for fix suggestions
argument-hint: "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] bug description"
argument-hint: "[--tool codex|gemini|qwen] [--enhance] [--cd path] bug description"
allowed-tools: SlashCommand(*), Bash(*), Task(*)
---
@@ -19,7 +19,6 @@ Systematic bug diagnosis with root cause analysis template (`~/.claude/workflows
## Parameters
- `--tool <gemini|qwen|codex>` - Tool selection (default: gemini)
- `--agent` - Use cli-execution-agent for automated context discovery
- `--enhance` - Enhance bug description with `/enhance-prompt`
- `--cd "path"` - Target directory for focused diagnosis
- `<bug-description>` (Required) - Bug description or error details
@@ -44,44 +43,48 @@ Systematic bug diagnosis with root cause analysis template (`~/.claude/workflows
## Execution Flow
### Standard Mode
1. Parse tool selection (default: gemini)
2. Optional: enhance with `/enhance-prompt`
3. Detect directory from `--cd` or auto-infer
4. Build command with template
5. Execute diagnosis (read-only)
6. Save to `.workflow/WFS-[id]/.chat/`
### Agent Mode (`--agent`)
Delegates to agent for intelligent diagnosis:
Uses **cli-execution-agent** (default) for automated bug diagnosis:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Bug root cause diagnosis",
description="Bug root cause diagnosis with fix suggestions",
prompt=`
Task: ${bug_description}
Mode: bug-diagnosis
Tool: ${tool_flag || 'auto-select'} // gemini|qwen|codex
Directory: ${cd_path || 'auto-detect'}
Tool: ${tool_flag || 'gemini'}
Directory: ${cd_path || '.'}
Enhance: ${enhance_flag}
Template: ~/.claude/workflows/cli-templates/prompts/analysis/01-diagnose-bug-root-cause.txt
Agent responsibilities:
Execute systematic bug diagnosis and root cause analysis:
1. Context Discovery:
- Locate error traces and logs
- Find related code sections
- Identify data flow paths
- Locate error traces, stack traces, and log messages
- Find related code sections and affected modules
- Identify data flow paths leading to the bug
- Discover test cases related to bug area
- Use MCP/ripgrep for comprehensive context gathering
2. CLI Command Generation:
- Build Gemini/Qwen/Codex command
- Include diagnostic context
- Apply ~/.claude/workflows/cli-templates/prompts/analysis/01-diagnose-bug-root-cause.txt template
2. Root Cause Analysis:
- Apply diagnostic template methodology
- Trace execution to identify failure point
- Analyze state, data, and logic causing issue
- Document potential root causes with evidence
- Assess bug severity and impact scope
3. Execution & Output:
- Execute root cause analysis
- Generate fix suggestions
- Save to .workflow/.chat/
3. CLI Command Construction:
- Tool: ${tool_flag || 'gemini'} (qwen fallback, codex for complex bugs)
- Directory: cd ${cd_path || '.'} &&
- Context: @**/* + error traces + affected code
- Mode: analysis (read-only)
- Template: analysis/01-diagnose-bug-root-cause.txt
4. Output Generation:
- Root cause diagnosis with evidence
- Fix suggestions and recommendations
- Prevention strategies
- Save to .workflow/WFS-[id]/.chat/bug-diagnosis-[timestamp].md (or .scratchpad/)
`
)
```
@@ -89,42 +92,5 @@ Task(
## Core Rules
- **Read-only**: Diagnoses bugs, does NOT modify code
- **Template**: Uses `~/.claude/workflows/cli-templates/prompts/analysis/01-diagnose-bug-root-cause.txt` for root cause analysis
- **Output**: Saves to `.workflow/WFS-[id]/.chat/`
## CLI Command Templates
**Gemini/Qwen** (default, diagnosis only):
```bash
cd [dir] && gemini -p "
PURPOSE: [goal]
TASK: Root cause analysis
MODE: analysis
CONTEXT: @**/*
EXPECTED: Diagnosis, fix plan
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/01-diagnose-bug-root-cause.txt)
"
# Qwen: Replace 'gemini' with 'qwen'
```
**Codex** (diagnosis + potential fixes):
```bash
codex -C [dir] --full-auto exec "
PURPOSE: [goal]
TASK: Bug diagnosis
MODE: analysis
CONTEXT: @**/*
EXPECTED: Diagnosis, fix suggestions
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/01-diagnose-bug-root-cause.txt)
" -m gpt-5 --skip-git-repo-check -s danger-full-access
```
## Output
- **With session**: `.workflow/WFS-[id]/.chat/bug-diagnosis-[timestamp].md`
- **No session**: `.workflow/.scratchpad/bug-diagnosis-[desc]-[timestamp].md`
## Notes
- Template: `~/.claude/workflows/cli-templates/prompts/analysis/01-diagnose-bug-root-cause.txt`
- See `intelligent-tools-strategy.md` for detailed tool usage
- **Template**: `~/.claude/workflows/cli-templates/prompts/analysis/01-diagnose-bug-root-cause.txt`
- **Output**: `.workflow/WFS-[id]/.chat/bug-diagnosis-[timestamp].md` (or `.scratchpad/` if no session)

View File

@@ -1,7 +1,7 @@
---
name: code-analysis
description: Read-only execution path tracing using Gemini/Qwen/Codex with specialized analysis template for call flow and optimization
argument-hint: "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] analysis target"
argument-hint: "[--tool codex|gemini|qwen] [--enhance] [--cd path] analysis target"
allowed-tools: SlashCommand(*), Bash(*), Task(*)
---
@@ -21,7 +21,6 @@ Systematic code analysis with execution path tracing template (`~/.claude/workfl
## Parameters
- `--tool <gemini|qwen|codex>` - Tool selection (default: gemini)
- `--agent` - Use cli-execution-agent for automated context discovery
- `--enhance` - Enhance analysis target with `/enhance-prompt` first
- `--cd "path"` - Target directory for focused analysis
- `<analysis-target>` (Required) - Code analysis target or question
@@ -47,91 +46,53 @@ Systematic code analysis with execution path tracing template (`~/.claude/workfl
## Execution Flow
### Standard Mode (Default)
1. Parse tool selection (default: gemini)
2. Optional: enhance analysis target with `/enhance-prompt`
3. Detect target directory from `--cd` or auto-infer
4. Build command with template
5. Execute analysis (read-only)
6. Save to `.workflow/WFS-[id]/.chat/code-analysis-[timestamp].md`
### Agent Mode (`--agent` flag)
Delegates to `cli-execution-agent` for intelligent context discovery and analysis.
## Core Rules
- **Read-only**: Analyzes code, does NOT modify files
- **Template**: Uses `~/.claude/workflows/cli-templates/prompts/analysis/01-trace-code-execution.txt` for systematic analysis
- **Output**: Saves to `.workflow/WFS-[id]/.chat/`
## CLI Command Templates
**Gemini/Qwen** (default, read-only analysis):
```bash
cd [dir] && gemini -p "
PURPOSE: [goal]
TASK: Execution path tracing
MODE: analysis
CONTEXT: @**/*
EXPECTED: Trace, call diagram
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/01-trace-code-execution.txt)
"
# Qwen: Replace 'gemini' with 'qwen'
```
**Codex** (analysis + optimization suggestions):
```bash
codex -C [dir] --full-auto exec "
PURPOSE: [goal]
TASK: Path analysis
MODE: analysis
CONTEXT: @**/*
EXPECTED: Trace, optimization
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/01-trace-code-execution.txt)
" -m gpt-5 --skip-git-repo-check -s danger-full-access
```
## Agent Execution Context
When `--agent` flag is used, delegate to agent:
Uses **cli-execution-agent** (default) for automated code analysis:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Code execution path analysis",
description="Execution path tracing and call flow analysis",
prompt=`
Task: ${analysis_target}
Mode: code-analysis
Tool: ${tool_flag || 'auto-select'} // gemini|qwen|codex
Directory: ${cd_path || 'auto-detect'}
Tool: ${tool_flag || 'gemini'}
Directory: ${cd_path || '.'}
Enhance: ${enhance_flag}
Template: ~/.claude/workflows/cli-templates/prompts/analysis/01-trace-code-execution.txt
Agent responsibilities:
Execute systematic code analysis with execution path tracing:
1. Context Discovery:
- Identify entry points and call chains
- Discover related files (MCP/ripgrep)
- Map execution flow paths
- Identify entry points and function signatures
- Trace call chains and execution flows
- Discover related files (implementations, dependencies, tests)
- Map data flow and state transformations
- Use MCP/ripgrep for comprehensive file discovery
2. CLI Command Generation:
- Build Gemini/Qwen/Codex command
- Include discovered context
- Apply ~/.claude/workflows/cli-templates/prompts/analysis/01-trace-code-execution.txt template
2. Analysis Execution:
- Apply execution tracing template
- Generate call flow diagrams (textual)
- Document execution paths and branching logic
- Identify optimization opportunities
3. Execution & Output:
- Execute analysis with selected tool
- Save to .workflow/WFS-[id]/.chat/
3. CLI Command Construction:
- Tool: ${tool_flag || 'gemini'} (qwen fallback, codex for complex analysis)
- Directory: cd ${cd_path || '.'} &&
- Context: @**/* + discovered execution context
- Mode: analysis (read-only)
- Template: analysis/01-trace-code-execution.txt
4. Output Generation:
- Execution trace documentation
- Call flow analysis with diagrams
- Performance and optimization insights
- Save to .workflow/WFS-[id]/.chat/code-analysis-[timestamp].md (or .scratchpad/)
`
)
```
## Output
## Core Rules
- **With session**: `.workflow/WFS-[id]/.chat/code-analysis-[timestamp].md`
- **No session**: `.workflow/.scratchpad/code-analysis-[desc]-[timestamp].md`
## Notes
- Template: `~/.claude/workflows/cli-templates/prompts/analysis/01-trace-code-execution.txt`
- See `intelligent-tools-strategy.md` for detailed tool usage
- **Read-only**: Analyzes code, does NOT modify files
- **Template**: `~/.claude/workflows/cli-templates/prompts/analysis/01-trace-code-execution.txt`
- **Output**: `.workflow/WFS-[id]/.chat/code-analysis-[timestamp].md` (or `.scratchpad/` if no session)

View File

@@ -1,7 +1,7 @@
---
name: plan
description: Read-only architecture planning using Gemini/Qwen/Codex with strategic planning template for modification plans and impact analysis
argument-hint: "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] topic"
argument-hint: "[--tool codex|gemini|qwen] [--enhance] [--cd path] topic"
allowed-tools: SlashCommand(*), Bash(*), Task(*)
---
@@ -19,7 +19,6 @@ Strategic software architecture planning template (`~/.claude/workflows/cli-temp
## Parameters
- `--tool <gemini|qwen|codex>` - Tool selection (default: gemini)
- `--agent` - Use cli-execution-agent for automated context discovery
- `--enhance` - Enhance task with `/enhance-prompt`
- `--cd "path"` - Target directory for focused planning
- `<planning-task>` (Required) - Architecture planning task or modification requirements
@@ -43,87 +42,52 @@ Strategic software architecture planning template (`~/.claude/workflows/cli-temp
## Execution Flow
### Standard Mode
1. Parse tool selection (default: gemini)
2. Optional: enhance with `/enhance-prompt`
3. Detect directory from `--cd` or auto-infer
4. Build command with template
5. Execute planning (read-only, no code generation)
6. Save to `.workflow/WFS-[id]/.chat/`
### Agent Mode (`--agent`)
Delegates to agent for intelligent planning:
Uses **cli-execution-agent** (default) for automated planning:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Architecture modification planning",
description="Architecture planning with impact analysis",
prompt=`
Task: ${planning_task}
Mode: architecture-planning
Tool: ${tool_flag || 'auto-select'} // gemini|qwen|codex
Directory: ${cd_path || 'auto-detect'}
Mode: plan
Tool: ${tool_flag || 'gemini'}
Directory: ${cd_path || '.'}
Enhance: ${enhance_flag}
Template: ~/.claude/workflows/cli-templates/prompts/planning/01-plan-architecture-design.txt
Agent responsibilities:
Execute strategic architecture planning:
1. Context Discovery:
- Analyze current architecture
- Identify affected components
- Map dependencies and impacts
- Analyze current architecture structure
- Identify affected components and modules
- Map dependencies and integration points
- Assess modification impacts (scope, complexity, risks)
2. CLI Command Generation:
- Build Gemini/Qwen/Codex command
- Include architecture context
- Apply ~/.claude/workflows/cli-templates/prompts/planning/01-plan-architecture-design.txt template
2. Planning Analysis:
- Apply strategic planning template
- Generate modification plan with phases
- Document architectural decisions and rationale
- Identify potential conflicts and mitigation strategies
3. Execution & Output:
- Execute strategic planning
- Generate modification plan
- Save to .workflow/.chat/
3. CLI Command Construction:
- Tool: ${tool_flag || 'gemini'} (qwen fallback, codex for implementation guidance)
- Directory: cd ${cd_path || '.'} &&
- Context: @**/* (full architecture context)
- Mode: analysis (read-only, no code generation)
- Template: planning/01-plan-architecture-design.txt
4. Output Generation:
- Strategic modification plan
- Impact analysis and risk assessment
- Implementation roadmap
- Save to .workflow/WFS-[id]/.chat/plan-[timestamp].md (or .scratchpad/)
`
)
```
## Core Rules
- **Planning only**: Creates modification plans, does NOT generate code
- **Template**: Uses `~/.claude/workflows/cli-templates/prompts/planning/01-plan-architecture-design.txt` for strategic planning
- **Output**: Saves to `.workflow/WFS-[id]/.chat/`
## CLI Command Templates
**Gemini/Qwen** (default, planning only):
```bash
cd [dir] && gemini -p "
PURPOSE: [goal]
TASK: Architecture planning
MODE: analysis
CONTEXT: @**/*
EXPECTED: Modification plan, impact analysis
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/planning/01-plan-architecture-design.txt)
"
# Qwen: Replace 'gemini' with 'qwen'
```
**Codex** (planning + implementation guidance):
```bash
codex -C [dir] --full-auto exec "
PURPOSE: [goal]
TASK: Architecture planning
MODE: analysis
CONTEXT: @**/*
EXPECTED: Plan, implementation roadmap
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/planning/01-plan-architecture-design.txt)
" -m gpt-5 --skip-git-repo-check -s danger-full-access
```
## Output
- **With session**: `.workflow/WFS-[id]/.chat/plan-[timestamp].md`
- **No session**: `.workflow/.scratchpad/plan-[desc]-[timestamp].md`
## Notes
- Template: `~/.claude/workflows/cli-templates/prompts/planning/01-plan-architecture-design.txt`
- See `intelligent-tools-strategy.md` for detailed tool usage
- **Read-only**: Creates modification plans, does NOT generate code
- **Template**: `~/.claude/workflows/cli-templates/prompts/planning/01-plan-architecture-design.txt`
- **Output**: `.workflow/WFS-[id]/.chat/plan-[timestamp].md` (or `.scratchpad/` if no session)

View File

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

View File

@@ -9,22 +9,32 @@ allowed-tools: SlashCommand(*), Task(*), TodoWrite(*), Read(*), Write(*), Bash(*
## Coordinator Role
**This command is a pure orchestrator**: Execute 3 phases in sequence (interactive framework → parallel role analysis → synthesis), delegate to specialized commands/agents, and ensure complete execution through **automatic continuation**.
**This command is a pure orchestrator**: Execute 3 phases in sequence (interactive framework → parallel role analysis → synthesis), coordinating specialized commands/agents through task attachment model.
**Task Attachment Model**:
- SlashCommand invocation **expands workflow** by attaching sub-tasks to current TodoWrite
- Task agent execution **attaches analysis tasks** to orchestrator's TodoWrite
- Phase 1: artifacts command attaches its internal tasks (Phase 1-5)
- Phase 2: N conceptual-planning-agent tasks attached in parallel
- Phase 3: synthesis command attaches its internal tasks
- Orchestrator **executes these attached tasks** sequentially (Phase 1, 3) or in parallel (Phase 2)
- After completion, attached tasks are **collapsed** back to high-level phase summary
- This is **task expansion**, not external delegation
**Execution Model - Auto-Continue Workflow**:
This workflow runs **fully autonomously** once triggered. Phase 1 (artifacts) handles user interaction, Phase 2 (role agents) runs in parallel.
1. **User triggers**: `/workflow:brainstorm:auto-parallel "topic" [--count N]`
2. **Phase 1 executes** → artifacts command (interactive framework) → Auto-continues
3. **Phase 2 executes** → Parallel role agents (N agents run concurrently) → Auto-continues
4. **Phase 3 executes** → Synthesis command → Reports final summary
2. **Phase 1 executes** → artifacts command (tasks ATTACHED) → Auto-continues
3. **Phase 2 executes** → Parallel role agents (N tasks ATTACHED concurrently) → Auto-continues
4. **Phase 3 executes** → Synthesis command (tasks ATTACHED) → Reports final summary
**Auto-Continue Mechanism**:
- TodoList tracks current phase status
- After Phase 1 (artifacts) completion, automatically load roles and launch Phase 2 agents
- After Phase 2 (all agents) completion, automatically execute Phase 3 synthesis
- Progress updates shown at each phase for visibility
- TodoList tracks current phase status and dynamically manages task attachment/collapse
- When Phase 1 (artifacts) finishes executing, automatically load roles and launch Phase 2 agents
- When Phase 2 (all agents) finishes executing, automatically execute Phase 3 synthesis
- **⚠️ CONTINUOUS EXECUTION** - Do not stop until all phases complete
## Core Rules
@@ -32,8 +42,10 @@ This workflow runs **fully autonomously** once triggered. Phase 1 (artifacts) ha
2. **No Preliminary Analysis**: Do not analyze topic before Phase 1 - artifacts handles all analysis
3. **Parse Every Output**: Extract selected_roles from workflow-session.json after Phase 1
4. **Auto-Continue via TodoList**: Check TodoList status to execute next pending phase automatically
5. **Track Progress**: Update TodoWrite after every phase completion
6. **TodoWrite Extension**: artifacts command EXTENDS parent TodoList (NOT replaces)
5. **Track Progress**: Update TodoWrite dynamically with task attachment/collapse pattern
6. **Task Attachment Model**: SlashCommand and Task invocations **attach** sub-tasks to current workflow. Orchestrator **executes** these attached tasks itself, then **collapses** them after completion
7. **⚠️ CRITICAL: DO NOT STOP**: Continuous multi-phase workflow. After executing all attached tasks, immediately collapse them and execute next phase
8. **Parallel Execution**: Phase 2 attaches multiple agent tasks simultaneously for concurrent execution
## Usage
@@ -74,15 +86,37 @@ This workflow runs **fully autonomously** once triggered. Phase 1 (artifacts) ha
- workflow-session.json contains selected_roles[] (metadata only, no content duplication)
- Session directory `.workflow/WFS-{topic}/.brainstorming/` exists
**TodoWrite**: Mark phase 1 completed, phase 2 in_progress
**TodoWrite Update (Phase 1 SlashCommand invoked - tasks attached)**:
```json
[
{"content": "Parse --count parameter from user input", "status": "completed", "activeForm": "Parsing count parameter"},
{"content": "Phase 1.1: Topic analysis and question generation (artifacts)", "status": "in_progress", "activeForm": "Analyzing topic"},
{"content": "Phase 1.2: Role selection and user confirmation (artifacts)", "status": "pending", "activeForm": "Selecting roles"},
{"content": "Phase 1.3: Role questions and user decisions (artifacts)", "status": "pending", "activeForm": "Collecting role questions"},
{"content": "Phase 1.4: Conflict detection and resolution (artifacts)", "status": "pending", "activeForm": "Resolving conflicts"},
{"content": "Phase 1.5: Guidance specification generation (artifacts)", "status": "pending", "activeForm": "Generating guidance"},
{"content": "Execute parallel role analysis", "status": "pending", "activeForm": "Executing parallel role analysis"},
{"content": "Execute synthesis integration", "status": "pending", "activeForm": "Executing synthesis integration"}
]
```
**After Phase 1**: Auto-continue to Phase 2 (role agent assignment)
**Note**: SlashCommand invocation **attaches** artifacts' 5 internal tasks. Orchestrator **executes** these tasks sequentially.
**⚠️ TodoWrite Coordination**: artifacts EXTENDS parent TodoList by:
- Marking parent task "Execute artifacts..." as in_progress
- APPENDING artifacts sub-tasks (Phase 1-5) after parent task
- PRESERVING all other auto-parallel tasks (role agents, synthesis)
- When artifacts Phase 5 completes, marking parent task as completed
**Next Action**: Tasks attached → **Execute Phase 1.1-1.5** sequentially
**TodoWrite Update (Phase 1 completed - tasks collapsed)**:
```json
[
{"content": "Parse --count parameter from user input", "status": "completed", "activeForm": "Parsing count parameter"},
{"content": "Execute artifacts interactive framework generation", "status": "completed", "activeForm": "Executing artifacts interactive framework"},
{"content": "Execute parallel role analysis", "status": "pending", "activeForm": "Executing parallel role analysis"},
{"content": "Execute synthesis integration", "status": "pending", "activeForm": "Executing synthesis integration"}
]
```
**Note**: Phase 1 tasks completed and collapsed to summary.
**After Phase 1**: Auto-continue to Phase 2 (parallel role agent execution)
---
@@ -143,8 +177,9 @@ TOPIC: {user-provided-topic}
**Parallel Execution**:
- Launch N agents simultaneously (one message with multiple Task calls)
- Each agent task **attached** to orchestrator's TodoWrite
- All agents execute concurrently, each attaching their own analysis sub-tasks
- Each agent operates independently reading same guidance-specification.md
- All agents update progress concurrently
**Input**:
- `selected_roles[]` from Phase 1
@@ -158,7 +193,33 @@ TOPIC: {user-provided-topic}
- **FORBIDDEN naming**: No `recommendations.md`, `recommendations-*.md`, or any non-`analysis` prefixed files
- All N role analyses completed
**TodoWrite**: Mark all N role agent tasks completed, phase 3 in_progress
**TodoWrite Update (Phase 2 agents invoked - tasks attached in parallel)**:
```json
[
{"content": "Parse --count parameter from user input", "status": "completed", "activeForm": "Parsing count parameter"},
{"content": "Execute artifacts interactive framework generation", "status": "completed", "activeForm": "Executing artifacts interactive framework"},
{"content": "Phase 2.1: Execute system-architect analysis [conceptual-planning-agent]", "status": "in_progress", "activeForm": "Executing system-architect analysis"},
{"content": "Phase 2.2: Execute ui-designer analysis [conceptual-planning-agent]", "status": "in_progress", "activeForm": "Executing ui-designer analysis"},
{"content": "Phase 2.3: Execute product-manager analysis [conceptual-planning-agent]", "status": "in_progress", "activeForm": "Executing product-manager analysis"},
{"content": "Execute synthesis integration", "status": "pending", "activeForm": "Executing synthesis integration"}
]
```
**Note**: Multiple Task invocations **attach** N role analysis tasks simultaneously. Orchestrator **executes** these tasks in parallel.
**Next Action**: Tasks attached → **Execute Phase 2.1-2.N** concurrently
**TodoWrite Update (Phase 2 completed - tasks collapsed)**:
```json
[
{"content": "Parse --count parameter from user input", "status": "completed", "activeForm": "Parsing count parameter"},
{"content": "Execute artifacts interactive framework generation", "status": "completed", "activeForm": "Executing artifacts interactive framework"},
{"content": "Execute parallel role analysis", "status": "completed", "activeForm": "Executing parallel role analysis"},
{"content": "Execute synthesis integration", "status": "pending", "activeForm": "Executing synthesis integration"}
]
```
**Note**: Phase 2 parallel tasks completed and collapsed to summary.
**After Phase 2**: Auto-continue to Phase 3 (synthesis)
@@ -180,7 +241,33 @@ TOPIC: {user-provided-topic}
- `.workflow/WFS-{topic}/.brainstorming/synthesis-specification.md` exists
- Synthesis references all role analyses
**TodoWrite**: Mark phase 3 completed
**TodoWrite Update (Phase 3 SlashCommand invoked - tasks attached)**:
```json
[
{"content": "Parse --count parameter from user input", "status": "completed", "activeForm": "Parsing count parameter"},
{"content": "Execute artifacts interactive framework generation", "status": "completed", "activeForm": "Executing artifacts interactive framework"},
{"content": "Execute parallel role analysis", "status": "completed", "activeForm": "Executing parallel role analysis"},
{"content": "Phase 3.1: Load role analysis files (synthesis)", "status": "in_progress", "activeForm": "Loading role analyses"},
{"content": "Phase 3.2: Integrate insights across roles (synthesis)", "status": "pending", "activeForm": "Integrating insights"},
{"content": "Phase 3.3: Generate synthesis specification (synthesis)", "status": "pending", "activeForm": "Generating synthesis"}
]
```
**Note**: SlashCommand invocation **attaches** synthesis' internal tasks. Orchestrator **executes** these tasks sequentially.
**Next Action**: Tasks attached → **Execute Phase 3.1-3.3** sequentially
**TodoWrite Update (Phase 3 completed - tasks collapsed)**:
```json
[
{"content": "Parse --count parameter from user input", "status": "completed", "activeForm": "Parsing count parameter"},
{"content": "Execute artifacts interactive framework generation", "status": "completed", "activeForm": "Executing artifacts interactive framework"},
{"content": "Execute parallel role analysis", "status": "completed", "activeForm": "Executing parallel role analysis"},
{"content": "Execute synthesis integration", "status": "completed", "activeForm": "Executing synthesis integration"}
]
```
**Note**: Phase 3 tasks completed and collapsed to summary.
**Return to User**:
```
@@ -195,49 +282,49 @@ Synthesis: .workflow/WFS-{topic}/.brainstorming/synthesis-specification.md
## TodoWrite Pattern
```javascript
// Initialize (before Phase 1)
TodoWrite({todos: [
{"content": "Parse --count parameter from user input", "status": "in_progress", "activeForm": "Parsing count parameter"},
{"content": "Execute artifacts command for interactive framework generation", "status": "pending", "activeForm": "Executing artifacts interactive framework"},
{"content": "Load selected_roles from workflow-session.json", "status": "pending", "activeForm": "Loading selected roles"},
// Role agent tasks added dynamically after Phase 1 based on selected_roles count
{"content": "Execute synthesis command for final integration", "status": "pending", "activeForm": "Executing synthesis integration"}
]})
**Core Concept**: Dynamic task attachment and collapse for parallel brainstorming workflow with interactive framework generation and concurrent role analysis.
// After Phase 1 (artifacts completes, roles loaded)
// Note: artifacts EXTENDS this list by appending its Phase 1-5 sub-tasks
TodoWrite({todos: [
{"content": "Parse --count parameter from user input", "status": "completed", "activeForm": "Parsing count parameter"},
{"content": "Execute artifacts command for interactive framework generation", "status": "completed", "activeForm": "Executing artifacts interactive framework"},
{"content": "Load selected_roles from workflow-session.json", "status": "in_progress", "activeForm": "Loading selected roles"},
{"content": "Execute system-architect analysis [conceptual-planning-agent]", "status": "pending", "activeForm": "Executing system-architect analysis"},
{"content": "Execute ui-designer analysis [conceptual-planning-agent]", "status": "pending", "activeForm": "Executing ui-designer analysis"},
{"content": "Execute product-manager analysis [conceptual-planning-agent]", "status": "pending", "activeForm": "Executing product-manager analysis"},
// ... (N role tasks based on --count parameter)
{"content": "Execute synthesis command for final integration", "status": "pending", "activeForm": "Executing synthesis integration"}
]})
### Key Principles
// After Phase 2 (all agents launched in parallel)
TodoWrite({todos: [
// ... previous completed tasks
{"content": "Load selected_roles from workflow-session.json", "status": "completed", "activeForm": "Loading selected roles"},
{"content": "Execute system-architect analysis [conceptual-planning-agent]", "status": "in_progress", "activeForm": "Executing system-architect analysis"},
{"content": "Execute ui-designer analysis [conceptual-planning-agent]", "status": "in_progress", "activeForm": "Executing ui-designer analysis"},
{"content": "Execute product-manager analysis [conceptual-planning-agent]", "status": "in_progress", "activeForm": "Executing product-manager analysis"},
// ... (all N agents in_progress simultaneously)
{"content": "Execute synthesis command for final integration", "status": "pending", "activeForm": "Executing synthesis integration"}
]})
1. **Task Attachment** (when SlashCommand/Task invoked):
- Sub-command's or agent's internal tasks are **attached** to orchestrator's TodoWrite
- Phase 1: `/workflow:brainstorm:artifacts` attaches 5 internal tasks (Phase 1.1-1.5)
- Phase 2: Multiple `Task(conceptual-planning-agent)` calls attach N role analysis tasks simultaneously
- Phase 3: `/workflow:brainstorm:synthesis` attaches 3 internal tasks (Phase 3.1-3.3)
- First attached task marked as `in_progress`, others as `pending`
- Orchestrator **executes** these attached tasks (sequentially for Phase 1, 3; in parallel for Phase 2)
// After Phase 2 (all agents complete)
TodoWrite({todos: [
// ... previous completed tasks
{"content": "Execute system-architect analysis [conceptual-planning-agent]", "status": "completed", "activeForm": "Executing system-architect analysis"},
{"content": "Execute ui-designer analysis [conceptual-planning-agent]", "status": "completed", "activeForm": "Executing ui-designer analysis"},
{"content": "Execute product-manager analysis [conceptual-planning-agent]", "status": "completed", "activeForm": "Executing product-manager analysis"},
{"content": "Execute synthesis command for final integration", "status": "in_progress", "activeForm": "Executing synthesis integration"}
]})
```
2. **Task Collapse** (after sub-tasks complete):
- Remove detailed sub-tasks from TodoWrite
- **Collapse** to high-level phase summary
- Example: Phase 1.1-1.5 collapse to "Execute artifacts interactive framework generation: completed"
- Phase 2: Multiple role tasks collapse to "Execute parallel role analysis: completed"
- Phase 3: Synthesis tasks collapse to "Execute synthesis integration: completed"
- Maintains clean orchestrator-level view
3. **Continuous Execution**:
- After collapse, automatically proceed to next pending phase
- No user intervention required between phases
- TodoWrite dynamically reflects current execution state
**Lifecycle Summary**: Initial pending tasks → Phase 1 invoked (artifacts tasks ATTACHED) → Artifacts sub-tasks executed → Phase 1 completed (tasks COLLAPSED) → Phase 2 invoked (N role tasks ATTACHED in parallel) → Role analyses executed concurrently → Phase 2 completed (tasks COLLAPSED) → Phase 3 invoked (synthesis tasks ATTACHED) → Synthesis sub-tasks executed → Phase 3 completed (tasks COLLAPSED) → Workflow complete.
### Brainstorming Workflow Specific Features
- **Phase 1**: Interactive framework generation with user Q&A (SlashCommand attachment)
- **Phase 2**: Parallel role analysis execution with N concurrent agents (Task agent attachments)
- **Phase 3**: Cross-role synthesis integration (SlashCommand attachment)
- **Dynamic Role Count**: `--count N` parameter determines number of Phase 2 parallel tasks (default: 3, max: 9)
- **Mixed Execution**: Sequential (Phase 1, 3) and Parallel (Phase 2) task execution
**Benefits**:
- Real-time visibility into attached tasks during execution
- Clean orchestrator-level summary after tasks complete
- Clear mental model: SlashCommand/Task = attach tasks, not delegate work
- Parallel execution support for concurrent role analysis
- Dynamic attachment/collapse maintains clarity
**Note**: See individual Phase descriptions (Phase 1, 2, 3) for detailed TodoWrite Update examples with full JSON structures.
## Input Processing

View File

@@ -22,11 +22,19 @@ This workflow runs **fully autonomously** once triggered. Phase 3 (conflict reso
4. **Phase 3 executes** (optional, if conflict_risk ≥ medium) → Conflict resolution → Auto-continues
5. **Phase 4 executes** → Task generation (task-generate-agent) → Reports final summary
**Task Attachment Model**:
- SlashCommand invocation **expands workflow** by attaching sub-tasks to current TodoWrite
- When a sub-command is invoked (e.g., `/workflow:tools:context-gather`), its internal tasks are attached to the orchestrator's TodoWrite
- Orchestrator **executes these attached tasks** sequentially
- After completion, attached tasks are **collapsed** back to high-level phase summary
- This is **task expansion**, not external delegation
**Auto-Continue Mechanism**:
- TodoList tracks current phase status
- After each phase completion, automatically executes next pending phase
- TodoList tracks current phase status and dynamically manages task attachment/collapse
- When each phase finishes executing, automatically execute next pending phase
- All phases run autonomously without user interaction (clarification handled in brainstorm phase)
- Progress updates shown at each phase for visibility
- **⚠️ CONTINUOUS EXECUTION** - Do not stop until all phases complete
## Core Rules
@@ -34,8 +42,9 @@ This workflow runs **fully autonomously** once triggered. Phase 3 (conflict reso
2. **No Preliminary Analysis**: Do not read files, analyze structure, or gather context before Phase 1
3. **Parse Every Output**: Extract required data from each command/agent output for next phase
4. **Auto-Continue via TodoList**: Check TodoList status to execute next pending phase automatically
5. **Track Progress**: Update TodoWrite after every phase completion
6. **Agent Delegation**: Phase 3 uses cli-execution-agent for autonomous intelligent analysis
5. **Track Progress**: Update TodoWrite dynamically with task attachment/collapse pattern
6. **Task Attachment Model**: SlashCommand invocation **attaches** sub-tasks to current workflow. Orchestrator **executes** these attached tasks itself, then **collapses** them after completion
7. **⚠️ CRITICAL: DO NOT STOP**: Continuous multi-phase workflow. After executing all attached tasks, immediately collapse them and execute next phase
## 5-Phase Execution
@@ -84,9 +93,35 @@ CONTEXT: Existing user database schema, REST API endpoints
- Context package path extracted
- File exists and is valid JSON
**TodoWrite**: Mark phase 2 completed, phase 3 in_progress
<!-- TodoWrite: When context-gather invoked, INSERT 3 context-gather tasks, mark first as in_progress -->
**After Phase 2**: Return to user showing Phase 2 results, then auto-continue to Phase 3
**TodoWrite Update (Phase 2 SlashCommand invoked - tasks attached)**:
```json
[
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Phase 2.1: Analyze codebase structure (context-gather)", "status": "in_progress", "activeForm": "Analyzing codebase structure"},
{"content": "Phase 2.2: Identify integration points (context-gather)", "status": "pending", "activeForm": "Identifying integration points"},
{"content": "Phase 2.3: Generate context package (context-gather)", "status": "pending", "activeForm": "Generating context package"},
{"content": "Execute task generation", "status": "pending", "activeForm": "Executing task generation"}
]
```
**Note**: SlashCommand invocation **attaches** context-gather's 3 tasks. Orchestrator **executes** these tasks sequentially.
<!-- TodoWrite: After Phase 2 tasks complete, REMOVE Phase 2.1-2.3, restore to orchestrator view -->
**TodoWrite Update (Phase 2 completed - tasks collapsed)**:
```json
[
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Execute task generation", "status": "pending", "activeForm": "Executing task generation"}
]
```
**Note**: Phase 2 tasks completed and collapsed to summary.
**After Phase 2**: Return to user showing Phase 2 results, then auto-continue to Phase 3/4 (depending on conflict_risk)
---
@@ -112,7 +147,35 @@ CONTEXT: Existing user database schema, REST API endpoints
- If conflict_risk is "none" or "low", skip directly to Phase 3.5
- Display: "No significant conflicts detected, proceeding to clarification"
**TodoWrite**: Mark phase 3 completed (if executed) or skipped, phase 3.5 in_progress
<!-- TodoWrite: If conflict_risk ≥ medium, INSERT 3 conflict-resolution tasks -->
**TodoWrite Update (Phase 3 SlashCommand invoked - tasks attached, if conflict_risk ≥ medium)**:
```json
[
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Phase 3.1: Detect conflicts with CLI analysis (conflict-resolution)", "status": "in_progress", "activeForm": "Detecting conflicts"},
{"content": "Phase 3.2: Present conflicts to user (conflict-resolution)", "status": "pending", "activeForm": "Presenting conflicts"},
{"content": "Phase 3.3: Apply resolution strategies (conflict-resolution)", "status": "pending", "activeForm": "Applying resolution strategies"},
{"content": "Execute task generation", "status": "pending", "activeForm": "Executing task generation"}
]
```
**Note**: SlashCommand invocation **attaches** conflict-resolution's 3 tasks. Orchestrator **executes** these tasks sequentially.
<!-- TodoWrite: After Phase 3 tasks complete, REMOVE Phase 3.1-3.3, restore to orchestrator view -->
**TodoWrite Update (Phase 3 completed - tasks collapsed)**:
```json
[
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Resolve conflicts and apply fixes", "status": "completed", "activeForm": "Resolving conflicts"},
{"content": "Execute task generation", "status": "pending", "activeForm": "Executing task generation"}
]
```
**Note**: Phase 3 tasks completed and collapsed to summary.
**After Phase 3**: Return to user showing conflict resolution results (if executed) and selected strategies, then auto-continue to Phase 3.5
@@ -173,7 +236,35 @@ SlashCommand(command="/workflow:tools:task-generate-agent --session [sessionId]
- `.workflow/[sessionId]/.task/IMPL-*.json` exists (at least one)
- `.workflow/[sessionId]/TODO_LIST.md` exists
**TodoWrite**: Mark phase 4 completed
<!-- TodoWrite: When task-generate-agent invoked, INSERT 3 task-generate-agent tasks -->
**TodoWrite Update (Phase 4 SlashCommand invoked - tasks attached)**:
```json
[
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Phase 4.1: Discovery - analyze requirements (task-generate-agent)", "status": "in_progress", "activeForm": "Analyzing requirements"},
{"content": "Phase 4.2: Planning - design tasks (task-generate-agent)", "status": "pending", "activeForm": "Designing tasks"},
{"content": "Phase 4.3: Output - generate JSONs (task-generate-agent)", "status": "pending", "activeForm": "Generating task JSONs"}
]
```
**Note**: SlashCommand invocation **attaches** task-generate-agent's 3 tasks. Orchestrator **executes** these tasks.
**Next Action**: Tasks attached → **Execute Phase 4.1-4.3** sequentially
<!-- TodoWrite: After Phase 4 tasks complete, REMOVE Phase 4.1-4.3, restore to orchestrator view -->
**TodoWrite Update (Phase 4 completed - tasks collapsed)**:
```json
[
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Execute task generation", "status": "completed", "activeForm": "Executing task generation"}
]
```
**Note**: Phase 4 tasks completed and collapsed to summary.
**Return to User**:
```
@@ -191,39 +282,37 @@ Quality Gate: Consider running /workflow:action-plan-verify to catch issues earl
## TodoWrite Pattern
```javascript
// Initialize (before Phase 1)
// Note: Phase 3 todo only added dynamically after Phase 2 if conflict_risk ≥ medium
TodoWrite({todos: [
{"content": "Execute session discovery", "status": "in_progress", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "pending", "activeForm": "Executing context gathering"},
// Phase 3 todo added dynamically after Phase 2 if conflict_risk ≥ medium
{"content": "Execute task generation", "status": "pending", "activeForm": "Executing task generation"}
]})
**Core Concept**: Dynamic task attachment and collapse for real-time visibility into workflow execution.
// After Phase 2 (if conflict_risk ≥ medium, insert Phase 3 todo)
TodoWrite({todos: [
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Resolve conflicts and apply fixes", "status": "in_progress", "activeForm": "Resolving conflicts"},
{"content": "Execute task generation", "status": "pending", "activeForm": "Executing task generation"}
]})
### Key Principles
// After Phase 2 (if conflict_risk is none/low, skip Phase 3, go directly to Phase 4)
TodoWrite({todos: [
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Execute task generation", "status": "in_progress", "activeForm": "Executing task generation"}
]})
1. **Task Attachment** (when SlashCommand invoked):
- Sub-command's internal tasks are **attached** to orchestrator's TodoWrite
- Example: `/workflow:tools:context-gather` attaches 3 sub-tasks (Phase 2.1, 2.2, 2.3)
- First attached task marked as `in_progress`, others as `pending`
- Orchestrator **executes** these attached tasks sequentially
// After Phase 3 (if executed), continue to Phase 4
TodoWrite({todos: [
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Resolve conflicts and apply fixes", "status": "completed", "activeForm": "Resolving conflicts"},
{"content": "Execute task generation", "status": "in_progress", "activeForm": "Executing task generation"}
]})
```
2. **Task Collapse** (after sub-tasks complete):
- Remove detailed sub-tasks from TodoWrite
- **Collapse** to high-level phase summary
- Example: Phase 2.1-2.3 collapse to "Execute context gathering: completed"
- Maintains clean orchestrator-level view
3. **Continuous Execution**:
- After collapse, automatically proceed to next pending phase
- No user intervention required between phases
- TodoWrite dynamically reflects current execution state
**Lifecycle Summary**: Initial pending tasks → Phase invoked (tasks ATTACHED) → Sub-tasks executed sequentially → Phase completed (tasks COLLAPSED to summary) → Next phase begins → Repeat until all phases complete.
### Benefits
- ✓ Real-time visibility into sub-task execution
- ✓ Clear mental model: SlashCommand = attach → execute → collapse
- ✓ Clean summary after completion
- ✓ Easy to track workflow progress
**Note**: See individual Phase descriptions (Phase 2, 3, 4) for detailed TodoWrite Update examples with full JSON structures.
## Input Processing
@@ -304,6 +393,55 @@ Return summary to user
- **Traceability**: Easy to track what was requested
- **Precision**: Better context gathering and analysis
## Execution Flow Diagram
```
User triggers: /workflow:plan "Build authentication system"
[TodoWrite Init] 3 orchestrator-level tasks
Phase 1: Session Discovery
→ sessionId extracted
Phase 2: Context Gathering (SlashCommand invoked)
→ ATTACH 3 tasks: ← ATTACHED
- Phase 2.1: Analyze codebase structure
- Phase 2.2: Identify integration points
- Phase 2.3: Generate context package
→ Execute Phase 2.1-2.3
→ COLLAPSE tasks ← COLLAPSED
→ contextPath + conflict_risk extracted
Conditional Branch: Check conflict_risk
├─ IF conflict_risk ≥ medium:
│ Phase 3: Conflict Resolution (SlashCommand invoked)
│ → ATTACH 3 tasks: ← ATTACHED
│ - Phase 3.1: Detect conflicts with CLI analysis
│ - Phase 3.2: Present conflicts to user
│ - Phase 3.3: Apply resolution strategies
│ → Execute Phase 3.1-3.3
│ → COLLAPSE tasks ← COLLAPSED
└─ ELSE: Skip Phase 3, proceed to Phase 4
Phase 4: Task Generation (SlashCommand invoked)
→ ATTACH 3 tasks: ← ATTACHED
- Phase 4.1: Discovery - analyze requirements
- Phase 4.2: Planning - design tasks
- Phase 4.3: Output - generate JSONs
→ Execute Phase 4.1-4.3
→ COLLAPSE tasks ← COLLAPSED
→ Outputs: IMPL_PLAN.md, IMPL-*.json, TODO_LIST.md
Return summary to user
```
**Key Points**:
- **← ATTACHED**: Sub-tasks attached to TodoWrite when SlashCommand invoked
- **← COLLAPSED**: Sub-tasks collapsed to summary after completion
- **Conditional Branch**: Phase 3 only executes if conflict_risk ≥ medium
- **Continuous Flow**: No user intervention between phases
## Error Handling
- **Parsing Failure**: If output parsing fails, retry command once, then report error
@@ -320,7 +458,7 @@ Return summary to user
- Parse context path from Phase 2 output, store in memory
- **Extract conflict_risk from context-package.json**: Determine Phase 3 execution
- **If conflict_risk ≥ medium**: Launch Phase 3 conflict-resolution with sessionId and contextPath
- Wait for Phase 3 completion (if executed), verify CONFLICT_RESOLUTION.md created
- Wait for Phase 3 to finish executing (if executed), verify CONFLICT_RESOLUTION.md created
- **If conflict_risk is none/low**: Skip Phase 3, proceed directly to Phase 4
- **Build Phase 4 command**:
- Base command: `/workflow:tools:task-generate-agent --session [sessionId]`

View File

@@ -9,21 +9,35 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
## Coordinator Role
**This command is a pure orchestrator**: Execute 5 slash commands in sequence, parse outputs, pass context, and ensure complete TDD workflow creation.
**This command is a pure orchestrator**: Execute 6 slash commands in sequence, parse outputs, pass context, and ensure complete TDD workflow creation with Red-Green-Refactor task generation.
**Execution Modes**:
- **Agent Mode** (default): Use `/workflow:tools:task-generate-tdd` (autonomous agent-driven)
- **CLI Mode** (`--cli-execute`): Use `/workflow:tools:task-generate-tdd --cli-execute` (Gemini/Qwen)
**Task Attachment Model**:
- SlashCommand invocation **expands workflow** by attaching sub-tasks to current TodoWrite
- When a sub-command is invoked (e.g., `/workflow:tools:test-context-gather`), its internal tasks are attached to the orchestrator's TodoWrite
- Orchestrator **executes these attached tasks** sequentially
- After completion, attached tasks are **collapsed** back to high-level phase summary
- This is **task expansion**, not external delegation
**Auto-Continue Mechanism**:
- TodoList tracks current phase status and dynamically manages task attachment/collapse
- When each phase finishes executing, automatically execute next pending phase
- All phases run autonomously without user interaction
- **⚠️ CONTINUOUS EXECUTION** - Do not stop until all phases complete
## Core Rules
1. **Start Immediately**: First action is TodoWrite initialization, second action is Phase 1 execution
2. **No Preliminary Analysis**: Do not read files before Phase 1
3. **Parse Every Output**: Extract required data for next phase
4. **Auto-Continue via TodoList**: Check TodoList status to execute next pending phase automatically
5. **Track Progress**: Update TodoWrite after every phase completion
5. **Track Progress**: Update TodoWrite dynamically with task attachment/collapse pattern
6. **TDD Context**: All descriptions include "TDD:" prefix
7. **Quality Gate**: Phase 4 conflict resolution (optional, auto-triggered) validates compatibility before task generation
7. **Task Attachment Model**: SlashCommand invocation **attaches** sub-tasks to current workflow. Orchestrator **executes** these attached tasks itself, then **collapses** them after completion
8. **⚠️ CRITICAL: DO NOT STOP**: Continuous multi-phase workflow. After executing all attached tasks, immediately collapse them and execute next phase
## 6-Phase Execution (with Conflict Resolution)
@@ -85,9 +99,41 @@ TEST_FOCUS: [Test scenarios]
- Prevents duplicate test creation
- Enables integration with existing tests
**TodoWrite**: Mark phase 3 completed, phase 4 in_progress
<!-- TodoWrite: When test-context-gather invoked, INSERT 3 test-context-gather tasks -->
**After Phase 3**: Return to user showing test coverage results, then auto-continue to Phase 4
**TodoWrite Update (Phase 3 SlashCommand invoked - tasks attached)**:
```json
[
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Phase 3.1: Detect test framework and conventions (test-context-gather)", "status": "in_progress", "activeForm": "Detecting test framework"},
{"content": "Phase 3.2: Analyze existing test coverage (test-context-gather)", "status": "pending", "activeForm": "Analyzing test coverage"},
{"content": "Phase 3.3: Identify coverage gaps (test-context-gather)", "status": "pending", "activeForm": "Identifying coverage gaps"},
{"content": "Execute TDD task generation", "status": "pending", "activeForm": "Executing TDD task generation"},
{"content": "Validate TDD structure", "status": "pending", "activeForm": "Validating TDD structure"}
]
```
**Note**: SlashCommand invocation **attaches** test-context-gather's 3 tasks. Orchestrator **executes** these tasks.
**Next Action**: Tasks attached → **Execute Phase 3.1-3.3** sequentially
<!-- TodoWrite: After Phase 3 tasks complete, REMOVE Phase 3.1-3.3, restore to orchestrator view -->
**TodoWrite Update (Phase 3 completed - tasks collapsed)**:
```json
[
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Execute test coverage analysis", "status": "completed", "activeForm": "Executing test coverage analysis"},
{"content": "Execute TDD task generation", "status": "pending", "activeForm": "Executing TDD task generation"},
{"content": "Validate TDD structure", "status": "pending", "activeForm": "Validating TDD structure"}
]
```
**Note**: Phase 3 tasks completed and collapsed to summary.
**After Phase 3**: Return to user showing test coverage results, then auto-continue to Phase 4/5 (depending on conflict_risk)
---
@@ -113,7 +159,41 @@ TEST_FOCUS: [Test scenarios]
- If conflict_risk is "none" or "low", skip directly to Phase 5
- Display: "No significant conflicts detected, proceeding to TDD task generation"
**TodoWrite**: Mark phase 4 completed (if executed) or skipped, phase 5 in_progress
<!-- TodoWrite: If conflict_risk ≥ medium, INSERT 3 conflict-resolution tasks -->
**TodoWrite Update (Phase 4 SlashCommand invoked - tasks attached, if conflict_risk ≥ medium)**:
```json
[
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Execute test coverage analysis", "status": "completed", "activeForm": "Executing test coverage analysis"},
{"content": "Phase 4.1: Detect conflicts with CLI analysis (conflict-resolution)", "status": "in_progress", "activeForm": "Detecting conflicts"},
{"content": "Phase 4.2: Present conflicts to user (conflict-resolution)", "status": "pending", "activeForm": "Presenting conflicts"},
{"content": "Phase 4.3: Apply resolution strategies (conflict-resolution)", "status": "pending", "activeForm": "Applying resolution strategies"},
{"content": "Execute TDD task generation", "status": "pending", "activeForm": "Executing TDD task generation"},
{"content": "Validate TDD structure", "status": "pending", "activeForm": "Validating TDD structure"}
]
```
**Note**: SlashCommand invocation **attaches** conflict-resolution's 3 tasks. Orchestrator **executes** these tasks.
**Next Action**: Tasks attached → **Execute Phase 4.1-4.3** sequentially
<!-- TodoWrite: After Phase 4 tasks complete, REMOVE Phase 4.1-4.3, restore to orchestrator view -->
**TodoWrite Update (Phase 4 completed - tasks collapsed)**:
```json
[
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Execute test coverage analysis", "status": "completed", "activeForm": "Executing test coverage analysis"},
{"content": "Execute conflict resolution", "status": "completed", "activeForm": "Executing conflict resolution"},
{"content": "Execute TDD task generation", "status": "pending", "activeForm": "Executing TDD task generation"},
{"content": "Validate TDD structure", "status": "pending", "activeForm": "Validating TDD structure"}
]
```
**Note**: Phase 4 tasks completed and collapsed to summary.
**After Phase 4**: Return to user showing conflict resolution results (if executed) and selected strategies, then auto-continue to Phase 5
@@ -145,6 +225,40 @@ TEST_FOCUS: [Test scenarios]
- IMPL_PLAN.md contains workflow_type: "tdd" in frontmatter
- Task count ≤10 (compliance with task limit)
<!-- TodoWrite: When task-generate-tdd invoked, INSERT 3 task-generate-tdd tasks -->
**TodoWrite Update (Phase 5 SlashCommand invoked - tasks attached)**:
```json
[
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Execute test coverage analysis", "status": "completed", "activeForm": "Executing test coverage analysis"},
{"content": "Phase 5.1: Discovery - analyze TDD requirements (task-generate-tdd)", "status": "in_progress", "activeForm": "Analyzing TDD requirements"},
{"content": "Phase 5.2: Planning - design Red-Green-Refactor cycles (task-generate-tdd)", "status": "pending", "activeForm": "Designing TDD cycles"},
{"content": "Phase 5.3: Output - generate IMPL tasks with internal TDD phases (task-generate-tdd)", "status": "pending", "activeForm": "Generating TDD tasks"},
{"content": "Validate TDD structure", "status": "pending", "activeForm": "Validating TDD structure"}
]
```
**Note**: SlashCommand invocation **attaches** task-generate-tdd's 3 tasks. Orchestrator **executes** these tasks. Each generated IMPL task will contain internal Red-Green-Refactor cycle.
**Next Action**: Tasks attached → **Execute Phase 5.1-5.3** sequentially
<!-- TodoWrite: After Phase 5 tasks complete, REMOVE Phase 5.1-5.3, restore to orchestrator view -->
**TodoWrite Update (Phase 5 completed - tasks collapsed)**:
```json
[
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Execute test coverage analysis", "status": "completed", "activeForm": "Executing test coverage analysis"},
{"content": "Execute TDD task generation", "status": "completed", "activeForm": "Executing TDD task generation"},
{"content": "Validate TDD structure", "status": "in_progress", "activeForm": "Validating TDD structure"}
]
```
**Note**: Phase 5 tasks completed and collapsed to summary. Each generated IMPL task contains complete Red-Green-Refactor cycle internally.
### Phase 6: TDD Structure Validation & Action Plan Verification (RECOMMENDED)
**Internal validation first, then recommend external verification**
@@ -202,45 +316,90 @@ Quality Gate: Consider running /workflow:action-plan-verify to validate TDD task
## TodoWrite Pattern
```javascript
// Initialize (Phase 4 added dynamically after Phase 3 if conflict_risk ≥ medium)
TodoWrite({todos: [
{"content": "Execute session discovery", "status": "in_progress", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "pending", "activeForm": "Executing context gathering"},
{"content": "Execute test coverage analysis", "status": "pending", "activeForm": "Executing test coverage analysis"},
// Phase 4 todo added dynamically after Phase 3 if conflict_risk ≥ medium
{"content": "Execute TDD task generation", "status": "pending", "activeForm": "Executing TDD task generation"},
{"content": "Validate TDD structure", "status": "pending", "activeForm": "Validating TDD structure"}
]})
**Core Concept**: Dynamic task attachment and collapse for TDD workflow with test coverage analysis and Red-Green-Refactor cycle generation.
// After Phase 3 (if conflict_risk ≥ medium, insert Phase 4 todo)
TodoWrite({todos: [
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Execute test coverage analysis", "status": "completed", "activeForm": "Executing test coverage analysis"},
{"content": "Execute conflict resolution", "status": "in_progress", "activeForm": "Executing conflict resolution"},
{"content": "Execute TDD task generation", "status": "pending", "activeForm": "Executing TDD task generation"},
{"content": "Validate TDD structure", "status": "pending", "activeForm": "Validating TDD structure"}
]})
### Key Principles
// After Phase 3 (if conflict_risk is none/low, skip Phase 4, go directly to Phase 5)
TodoWrite({todos: [
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Execute test coverage analysis", "status": "completed", "activeForm": "Executing test coverage analysis"},
{"content": "Execute TDD task generation", "status": "in_progress", "activeForm": "Executing TDD task generation"},
{"content": "Validate TDD structure", "status": "pending", "activeForm": "Validating TDD structure"}
]})
1. **Task Attachment** (when SlashCommand invoked):
- Sub-command's internal tasks are **attached** to orchestrator's TodoWrite
- Example: `/workflow:tools:test-context-gather` attaches 3 sub-tasks (Phase 3.1, 3.2, 3.3)
- First attached task marked as `in_progress`, others as `pending`
- Orchestrator **executes** these attached tasks sequentially
// After Phase 4 (if executed), continue to Phase 5
TodoWrite({todos: [
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Execute test coverage analysis", "status": "completed", "activeForm": "Executing test coverage analysis"},
{"content": "Execute conflict resolution", "status": "completed", "activeForm": "Executing conflict resolution"},
{"content": "Execute TDD task generation", "status": "in_progress", "activeForm": "Executing TDD task generation"},
{"content": "Validate TDD structure", "status": "pending", "activeForm": "Validating TDD structure"}
]})
2. **Task Collapse** (after sub-tasks complete):
- Remove detailed sub-tasks from TodoWrite
- **Collapse** to high-level phase summary
- Example: Phase 3.1-3.3 collapse to "Execute test coverage analysis: completed"
- Maintains clean orchestrator-level view
3. **Continuous Execution**:
- After collapse, automatically proceed to next pending phase
- No user intervention required between phases
- TodoWrite dynamically reflects current execution state
**Lifecycle Summary**: Initial pending tasks → Phase invoked (tasks ATTACHED) → Sub-tasks executed sequentially → Phase completed (tasks COLLAPSED to summary) → Next phase begins (conditional Phase 4 if conflict_risk ≥ medium) → Repeat until all phases complete.
### TDD-Specific Features
- **Phase 3**: Test coverage analysis detects existing patterns and gaps
- **Phase 5**: Generated IMPL tasks contain internal Red-Green-Refactor cycles
- **Conditional Phase 4**: Conflict resolution only if conflict_risk ≥ medium
### Benefits
- ✓ Real-time visibility into TDD workflow execution
- ✓ Clear mental model: SlashCommand = attach → execute → collapse
- ✓ Test-aware planning with coverage analysis
- ✓ Self-contained TDD cycles within each IMPL task
**Note**: See individual Phase descriptions (Phase 3, 4, 5) for detailed TodoWrite Update examples with full JSON structures.
## Execution Flow Diagram
```
TDD Workflow Orchestrator
├─ Phase 1: Session Discovery
│ └─ /workflow:session:start --auto
│ └─ Returns: sessionId
├─ Phase 2: Context Gathering
│ └─ /workflow:tools:context-gather
│ └─ Returns: context-package.json path
├─ Phase 3: Test Coverage Analysis ← ATTACHED (3 tasks)
│ └─ /workflow:tools:test-context-gather
│ ├─ Phase 3.1: Detect test framework
│ ├─ Phase 3.2: Analyze existing test coverage
│ └─ Phase 3.3: Identify coverage gaps
│ └─ Returns: test-context-package.json ← COLLAPSED
├─ Phase 4: Conflict Resolution (conditional)
│ IF conflict_risk ≥ medium:
│ └─ /workflow:tools:conflict-resolution ← ATTACHED (3 tasks)
│ ├─ Phase 4.1: Detect conflicts with CLI
│ ├─ Phase 4.2: Present conflicts to user
│ └─ Phase 4.3: Apply resolution strategies
│ └─ Returns: CONFLICT_RESOLUTION.md ← COLLAPSED
│ ELSE:
│ └─ Skip to Phase 5
├─ Phase 5: TDD Task Generation ← ATTACHED (3 tasks)
│ └─ /workflow:tools:task-generate-tdd
│ ├─ Phase 5.1: Discovery - analyze TDD requirements
│ ├─ Phase 5.2: Planning - design Red-Green-Refactor cycles
│ └─ Phase 5.3: Output - generate IMPL tasks with internal TDD phases
│ └─ Returns: IMPL-*.json, IMPL_PLAN.md ← COLLAPSED
│ (Each IMPL task contains internal Red-Green-Refactor cycle)
└─ Phase 6: TDD Structure Validation
└─ Internal validation + summary returned
└─ Recommend: /workflow:action-plan-verify
Key Points:
• ← ATTACHED: SlashCommand attaches sub-tasks to orchestrator TodoWrite
• ← COLLAPSED: Sub-tasks executed and collapsed to phase summary
• TDD-specific: Each generated IMPL task contains complete Red-Green-Refactor cycle
```
## Input Processing

View File

@@ -1,6 +1,6 @@
---
name: test-cycle-execute
description: Execute test-fix workflow with dynamic task generation and iterative fix cycles until all tests pass or max iterations reached
description: Execute test-fix workflow with dynamic task generation and iterative fix cycles until test pass rate >= 95% or max iterations reached. Uses @cli-planning-agent for failure analysis and task generation.
argument-hint: "[--resume-session=\"session-id\"] [--max-iterations=N]"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Task(*)
---
@@ -10,10 +10,13 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Task(*)
## Overview
Orchestrates dynamic test-fix workflow execution through iterative cycles of testing, analysis, and fixing. **Unlike standard execute, this command dynamically generates intermediate tasks** during execution based on test results and CLI analysis, enabling adaptive problem-solving.
**Quality Gate**: Iterates until test pass rate >= 95% (with criticality assessment) or 100% for full approval.
**CRITICAL - Orchestrator Boundary**:
- This command is the **ONLY place** where test failures are handled
- All CLI analysis (Gemini/Qwen), fix task generation (IMPL-fix-N.json), and iteration management happen HERE
- Agents (@test-fix-agent) only execute single tasks and return results
- All failure analysis and fix task generation delegated to **@cli-planning-agent**
- Orchestrator calculates pass rate, assesses criticality, and manages iteration loop
- @test-fix-agent executes tests and applies fixes, reports results back
- **Do NOT handle test failures in main workflow or other commands** - always delegate to this orchestrator
**Resume Mode**: When called with `--resume-session` flag, skips discovery and continues from interruption point.
@@ -35,44 +38,53 @@ Orchestrates dynamic test-fix workflow execution through iterative cycles of tes
### Agent Coordination
- **@code-developer**: Understands requirements, generates implementations
- **@test-fix-agent**: Executes tests, applies fixes, validates results
- **CLI Tools (Gemini/Qwen)**: Analyzes failures, suggests fix strategies
- **@test-fix-agent**: Executes tests, applies fixes, validates results, assigns criticality
- **@cli-planning-agent**: Executes CLI analysis (Gemini/Qwen), parses results, generates fix task JSONs
## Core Rules
1. **Dynamic Task Generation**: Create intermediate fix tasks based on test failures
2. **Iterative Execution**: Repeat test-fix cycles until success or max iterations
3. **CLI-Driven Analysis**: Use Gemini/Qwen to analyze failures and plan fixes
4. **Agent Delegation**: All execution delegated to specialized agents
5. **Context Accumulation**: Each iteration builds on previous attempt context
6. **Autonomous Completion**: Continue until all tests pass without user interruption
1. **Dynamic Task Generation**: Create intermediate fix tasks via @cli-planning-agent based on test failures
2. **Iterative Execution**: Repeat test-fix cycles until pass rate >= 95% (with criticality assessment) or max iterations
3. **Pass Rate Threshold**: Target 95%+ pass rate; 100% for full approval; assess criticality for 95-100% range
4. **Agent-Based Analysis**: Delegate CLI execution and task generation to @cli-planning-agent
5. **Agent Delegation**: All execution delegated to specialized agents (@cli-planning-agent, @test-fix-agent)
6. **Context Accumulation**: Each iteration builds on previous attempt context
7. **Autonomous Completion**: Continue until pass rate >= 95% without user interruption
## Core Responsibilities
- **Session Discovery**: Identify test-fix workflow sessions
- **Task Queue Management**: Maintain dynamic task queue with runtime additions
- **Test Execution**: Run tests through @test-fix-agent
- **Failure Analysis**: Use CLI tools to diagnose test failures
- **Fix Task Generation**: Create intermediate fix tasks dynamically
- **Iteration Control**: Manage fix cycles with max iteration limits
- **Context Propagation**: Pass failure context and fix history between iterations
- **Pass Rate Calculation**: Calculate test pass rate from test-results.json (passed/total * 100)
- **Criticality Assessment**: Evaluate failure severity using test-results.json criticality field
- **Threshold Decision**: Determine if pass rate >= 95% with criticality consideration
- **Failure Analysis Delegation**: Invoke @cli-planning-agent for CLI analysis and task generation
- **Iteration Control**: Manage fix cycles with max iteration limits (5 default)
- **Context Propagation**: Pass failure context and fix history to @cli-planning-agent
- **Progress Tracking**: TodoWrite updates for entire iteration cycle
- **Session Auto-Complete**: Call `/workflow:session:complete` when all tests pass
- **Session Auto-Complete**: Call `/workflow:session:complete` when pass rate >= 95% (or 100%)
## Responsibility Matrix
**CRITICAL - Clear division of labor between orchestrator and agents:**
| Responsibility | test-cycle-execute (Orchestrator) | @test-fix-agent (Executor) |
|----------------|----------------------------|---------------------------|
| Manage iteration loop | Yes - Controls loop flow | No - Executes single task |
| Run CLI analysis (Gemini/Qwen) | Yes - Runs between agent tasks | No - Not involved |
| Generate IMPL-fix-N.json | Yes - Creates task files | No - Not involved |
| Run tests | No - Delegates to agent | Yes - Executes test command |
| Apply fixes | No - Delegates to agent | Yes - Modifies code |
| Detect test failures | Yes - Analyzes results and decides next action | Yes - Executes tests and reports outcomes |
| Add tasks to queue | Yes - Manages queue | No - Not involved |
| Update iteration state | Yes - Maintains overall iteration state | Yes - Updates individual task status only |
| Responsibility | test-cycle-execute (Orchestrator) | @cli-planning-agent | @test-fix-agent (Executor) |
|----------------|----------------------------|---------------------|---------------------------|
| Manage iteration loop | Yes - Controls loop flow | No - Not involved | No - Executes single task |
| Calculate pass rate | Yes - From test-results.json | No - Not involved | No - Reports test results |
| Assess criticality | Yes - From test-results.json | No - Not involved | Yes - Assigns criticality in test results |
| Run CLI analysis (Gemini/Qwen) | No - Delegates to cli-planning-agent | Yes - Executes CLI internally | No - Not involved |
| Parse CLI output | No - Delegated | Yes - Extracts fix strategy | No - Not involved |
| Generate IMPL-fix-N.json | No - Delegated | Yes - Creates task files | No - Not involved |
| Run tests | No - Delegates to agent | No - Not involved | Yes - Executes test command |
| Apply fixes | No - Delegates to agent | No - Not involved | Yes - Modifies code |
| Detect test failures | Yes - Analyzes pass rate and decides next action | No - Not involved | Yes - Executes tests and reports outcomes |
| Add tasks to queue | Yes - Manages queue | No - Returns task ID | No - Not involved |
| Update iteration state | Yes - Maintains overall iteration state | No - Not involved | Yes - Updates individual task status only |
**Key Principle**: Orchestrator manages the "what" and "when"; agents execute the "how".
**Key Principles**:
- Orchestrator manages the "what" (iteration flow, threshold decisions) and "when" (task scheduling)
- @cli-planning-agent executes the "analysis" (CLI execution, result parsing, task generation)
- @test-fix-agent executes the "how" (run tests, apply fixes)
**ENFORCEMENT**: If test failures occur outside this orchestrator, do NOT handle them inline - always call `/workflow:test-cycle-execute` instead.
@@ -97,17 +109,29 @@ For each task in queue:
1. [Orchestrator] Load task JSON and context
2. [Orchestrator] Determine task type (test-gen, test-fix, fix-iteration)
3. [Orchestrator] Execute task through appropriate agent
4. [Orchestrator] Collect agent results and check exit conditions
5. If test failures detected:
a. [Orchestrator] Run CLI analysis (Gemini/Qwen)
b. [Orchestrator] Generate fix task JSON (IMPL-fix-N.json)
4. [Orchestrator] Collect agent results from .process/test-results.json
5. [Orchestrator] Calculate test pass rate:
a. Parse test-results.json: passRate = (passed / total) * 100
b. Assess failure criticality (from test-results.json)
c. Evaluate fix effectiveness (NEW):
- Compare passRate with previous iteration
- If passRate decreased by >10%: REGRESSION detected
- If regression: Rollback last fix, skip to next strategy
6. [Orchestrator] Make threshold decision:
IF passRate === 100%:
→ SUCCESS: Mark task complete, update TodoWrite, continue
ELSE IF passRate >= 95%:
→ REVIEW: Check failure criticality
→ If all failures are "low" criticality: PARTIAL SUCCESS (approve with note)
→ If any "high" or "medium" criticality: Enter fix loop (step 7)
ELSE IF passRate < 95%:
→ FAILED: Enter fix loop (step 7)
7. If entering fix loop (pass rate < 95% OR critical failures exist):
a. [Orchestrator] Invoke @cli-planning-agent with failure context
b. [Agent] Executes CLI analysis + generates IMPL-fix-N.json
c. [Orchestrator] Insert fix task at front of queue
d. [Orchestrator] Continue loop
6. If test success:
a. [Orchestrator] Mark task complete
b. [Orchestrator] Update TodoWrite
c. [Orchestrator] Continue to next task
7. [Orchestrator] Check max iterations limit
8. [Orchestrator] Check max iterations limit (abort if exceeded)
```
**Note**: The orchestrator controls the loop. Agents execute individual tasks and return results.
@@ -119,33 +143,33 @@ For each task in queue:
#### Iteration Structure
```
Iteration N (managed by test-cycle-execute orchestrator):
├── 1. Test Execution
├── 1. Test Execution & Pass Rate Validation
│ ├── [Orchestrator] Launch @test-fix-agent with test task
│ ├── [Agent] Run test suite
│ ├── [Agent] Collect failures and report back
── [Orchestrator] Receive failure report
├── 2. Failure Analysis
│ ├── [Orchestrator] Run CLI tool (Gemini/Qwen)
│ ├── [CLI Tool] Analyze error messages and failure context
│ ├── [CLI Tool] Identify root causes
── [CLI Tool] Generate fix strategy → saved to iteration-N-analysis.md
├── 3. Fix Task Generation
│ ├── [Orchestrator] Parse CLI analysis results
│ ├── [Orchestrator] Create IMPL-fix-N.json with:
│ ├── meta.agent: "@test-fix-agent"
│ │ ├── Failure context (content, not just path)
│ └── Fix strategy from CLI analysis
── [Orchestrator] Insert into task queue (front position)
├── 4. Fix Execution
│ ├── [Orchestrator] Launch @test-fix-agent with fix task
│ ├── [Agent] Load fix strategy from task context
│ ├── [Agent] Apply fixes to code/tests
│ ├── [Agent] Run test suite and save results to test-results.json
│ ├── [Agent] Report completion back to orchestrator
── [Orchestrator] Calculate pass rate: (passed / total) * 100
│ └── [Orchestrator] Assess failure criticality from test-results.json
├── 2. Failure Analysis & Task Generation (via @cli-planning-agent)
│ ├── [Orchestrator] Assemble failure context package (tests, errors, pass_rate)
│ ├── [Orchestrator] Invoke @cli-planning-agent with context
── [@cli-planning-agent] Execute CLI tool (Gemini/Qwen) internally
│ ├── [@cli-planning-agent] Parse CLI output for root causes and fix strategy
│ ├── [@cli-planning-agent] Generate IMPL-fix-N.json with structured task
│ ├── [@cli-planning-agent] Save analysis to iteration-N-analysis.md
└── [Orchestrator] Receive task ID and insert into queue (front position)
├── 3. Fix Execution
├── [Orchestrator] Launch @test-fix-agent with IMPL-fix-N task
── [Agent] Load fix strategy from task.context.fix_strategy
│ ├── [Agent] Apply surgical fixes to identified files
│ └── [Agent] Report completion
└── 5. Re-test
└── 4. Re-test
└── [Orchestrator] Return to step 1 with updated code
```
**Key**: Orchestrator runs CLI analysis between agent tasks, then generates new fix tasks.
**Key Changes**:
- CLI analysis + task generation encapsulated in @cli-planning-agent
- Pass rate calculation added to test execution step
- Orchestrator only assembles context and invokes agent
#### Iteration Task JSON Template
```json
@@ -220,74 +244,139 @@ Iteration N (managed by test-cycle-execute orchestrator):
}
```
### Phase 4: CLI Analysis Integration
### Phase 4: Agent-Based Failure Analysis & Task Generation
**Orchestrator executes CLI analysis between agent tasks:**
**Orchestrator delegates CLI analysis and task generation to @cli-planning-agent:**
#### When Test Failures Occur
1. **[Orchestrator]** Detects failures from agent test execution output
2. **[Orchestrator]** Collects failure context from `.process/test-results.json` and logs
3. **[Orchestrator]** Executes Gemini/Qwen CLI tool with failure context
4. **[Orchestrator]** Interprets CLI tool output to extract fix strategy
5. **[Orchestrator]** Saves analysis to `.process/iteration-N-analysis.md`
6. **[Orchestrator]** Generates `IMPL-fix-N.json` with strategy content (not just path)
#### When Test Failures Occur (Pass Rate < 95% OR Critical Failures)
1. **[Orchestrator]** Detects failures from test-results.json
2. **[Orchestrator]** Check for repeated failures (NEW):
- Compare failed_tests with previous 2 iterations
- If same test failed 3 times consecutively: Mark as "stuck"
- If >50% of failures are "stuck": Switch analysis strategy or abort
3. **[Orchestrator]** Extracts failure context:
- Failed tests with criticality assessment
- Error messages and stack traces
- Current pass rate
- Previous iteration attempts (if any)
- Stuck test markers (NEW)
4. **[Orchestrator]** Assembles context package for @cli-planning-agent
5. **[Orchestrator]** Invokes @cli-planning-agent via Task tool
6. **[@cli-planning-agent]** Executes internally:
- Runs Gemini/Qwen CLI analysis with bug diagnosis template
- Parses CLI output to extract root causes and fix strategy
- Generates `IMPL-fix-N.json` with structured task definition
- Saves analysis report to `.process/iteration-N-analysis.md`
- Saves raw CLI output to `.process/iteration-N-cli-output.txt`
7. **[Orchestrator]** Receives task ID from agent and inserts into queue
**Note**: The orchestrator executes CLI analysis tools and processes their output. CLI tools provide analysis, orchestrator manages the workflow.
**Key Change**: CLI execution + result parsing + task generation are now encapsulated in @cli-planning-agent, simplifying orchestrator logic.
#### CLI Analysis Command (executed by orchestrator)
```bash
cd {project_root} && gemini -p "
PURPOSE: Analyze test failures and generate fix strategy
TASK: Review test failures and identify root causes
MODE: analysis
CONTEXT: @test files @ implementation files
#### Agent Invocation Pattern (executed by orchestrator)
```javascript
Task(
subagent_type="cli-planning-agent",
description=`Analyze test failures and generate fix task (iteration ${currentIteration})`,
prompt=`
## Context Package
{
"session_id": "${sessionId}",
"iteration": ${currentIteration},
"analysis_type": "test-failure",
"failure_context": {
"failed_tests": ${JSON.stringify(failedTests)},
"error_messages": ${JSON.stringify(errorMessages)},
"test_output": "${testOutputPath}",
"pass_rate": ${passRate},
"previous_attempts": ${JSON.stringify(previousAttempts)}
},
"cli_config": {
"tool": "gemini",
"model": "gemini-3-pro-preview-11-2025",
"template": "01-diagnose-bug-root-cause.txt",
"timeout": 2400000,
"fallback": "qwen"
},
"task_config": {
"agent": "@test-fix-agent",
"type": "test-fix-iteration",
"max_iterations": ${maxIterations},
"use_codex": false
}
}
[Test failure context and requirements...]
EXPECTED: Detailed fix strategy in markdown format
RULES: Focus on minimal changes, avoid over-engineering
"
## Your Task
1. Execute CLI analysis using Gemini (fallback to Qwen if needed)
2. Parse CLI output and extract fix strategy with specific modification points
3. Generate IMPL-fix-${currentIteration}.json using your internal task template
4. Save analysis report to .process/iteration-${currentIteration}-analysis.md
5. Report success and task ID back to orchestrator
`
)
```
#### Analysis Output Structure
#### Agent Response
```javascript
{
"status": "success",
"task_id": "IMPL-fix-${iteration}",
"task_path": ".workflow/${session}/.task/IMPL-fix-${iteration}.json",
"analysis_report": ".process/iteration-${iteration}-analysis.md",
"cli_output": ".process/iteration-${iteration}-cli-output.txt",
"summary": "Fix authentication token validation and null check issues",
"modification_points_count": 2,
"estimated_complexity": "low"
}
```
#### Generated Analysis Report Structure
The @cli-planning-agent generates `.process/iteration-N-analysis.md`:
```markdown
# Test Failure Analysis - Iteration {N}
---
iteration: N
analysis_type: test-failure
cli_tool: gemini
model: gemini-3-pro-preview-11-2025
timestamp: 2025-11-10T10:00:00Z
pass_rate: 85.0%
---
# Test Failure Analysis - Iteration N
## Summary
- **Failed Tests**: 2
- **Pass Rate**: 85.0% (Target: 95%+)
- **Root Causes Identified**: 2
- **Modification Points**: 2
## Failed Tests Details
### test_auth_flow
- **Error**: Expected 200, got 401
- **File**: tests/test_auth.test.ts:45
- **Criticality**: high
### test_data_validation
- **Error**: TypeError: Cannot read property 'name' of undefined
- **File**: tests/test_validators.test.ts:23
- **Criticality**: medium
## Root Cause Analysis
1. **Test: test_auth_flow**
- Error: `Expected 200, got 401`
- Root Cause: Missing authentication token in request headers
- Affected Code: `src/auth/client.ts:45`
2. **Test: test_data_validation**
- Error: `TypeError: Cannot read property 'name' of undefined`
- Root Cause: Null check missing before property access
- Affected Code: `src/validators/user.ts:23`
[CLI output: 根本原因分析 section]
## Fix Strategy
[CLI output: 详细修复建议 section]
### Priority 1: Authentication Issue
- **File**: src/auth/client.ts
- **Function**: sendRequest (line 45)
- **Change**: Add token header: `headers['Authorization'] = 'Bearer ' + token`
- **Verification**: Run test_auth_flow
## Modification Points
- `src/auth/client.ts:sendRequest:45-50` - Add authentication token header
- `src/validators/user.ts:validateUser:23-25` - Add null check before property access
### Priority 2: Null Check
- **File**: src/validators/user.ts
- **Function**: validateUser (line 23)
- **Change**: Add check: `if (!user?.name) return false`
- **Verification**: Run test_data_validation
## Expected Outcome
[CLI output: 验证建议 section]
## Verification Plan
1. Apply fixes in order
2. Run test suite after each fix
3. Check for regressions
4. Validate all tests pass
## Risk Assessment
- Low risk: Changes are surgical and isolated
- No breaking changes expected
- Existing tests should remain green
## CLI Raw Output
See: `.process/iteration-N-cli-output.txt`
```
### Phase 5: Task Queue Management
@@ -321,27 +410,56 @@ After IMPL-fix-2 execution (success):
#### Success Conditions
- All initial tasks completed
- All generated fix tasks completed
- All tests passing
- **Test pass rate === 100%** (all tests passing)
- No pending tasks in queue
#### Partial Success Conditions (NEW)
- All initial tasks completed
- Test pass rate >= 95% AND < 100%
- All failures are "low" criticality (flaky tests, env-specific issues)
- **Automatic Approval with Warning**: System auto-approves but marks session with review flag
- Note: Generate completion summary with detailed warnings about low-criticality failures
#### Completion Steps
1. **Final Validation**: Run full test suite one more time
2. **Update Session State**: Mark all tasks completed
3. **Generate Summary**: Create session completion summary
4. **Update TodoWrite**: Mark all items completed
5. **Auto-Complete**: Call `/workflow:session:complete`
2. **Calculate Final Pass Rate**: Parse test-results.json
3. **Assess Completion Status**:
- If pass_rate === 100% → Full Success
- If pass_rate >= 95% + all "low" criticality → Partial Success (add review note)
- If pass_rate >= 95% + any "high"/"medium" criticality → Continue iteration
- If pass_rate < 95% → Failure
4. **Update Session State**: Mark all tasks completed (or blocked if failure)
5. **Generate Summary**: Create session completion summary with pass rate metrics
6. **Update TodoWrite**: Mark all items completed
7. **Auto-Complete**: Call `/workflow:session:complete` (for Full or Partial Success)
#### Failure Conditions
- Max iterations reached without success
- Unrecoverable test failures
- Max iterations (5) reached without achieving 95% pass rate
- **Test pass rate < 95% after max iterations** (NEW)
- Pass rate >= 95% but critical failures exist and max iterations reached
- Unrecoverable test failures (infinite loop detection)
- Agent execution errors
#### Failure Handling
1. **Document State**: Save current iteration context
2. **Generate Report**: Create failure analysis report
3. **Preserve Context**: Keep all iteration logs
1. **Document State**: Save current iteration context with final pass rate
2. **Generate Failure Report**: Include:
- Final pass rate (e.g., "85% after 5 iterations")
- Remaining failures with criticality assessment
- Iteration history and attempted fixes
- CLI analysis quality (normal/degraded)
- Recommendations for manual intervention
3. **Preserve Context**: Keep all iteration logs and analysis reports
4. **Mark Blocked**: Update task status to blocked
5. **Return Control**: Return to user with detailed report
5. **Return Control**: Return to user with detailed failure report
#### Degraded Analysis Handling (NEW)
When @cli-planning-agent returns `status: "degraded"` (both Gemini and Qwen failed):
1. **Log Warning**: Record CLI analysis failure in iteration-state.json
2. **Assess Risk**: Check if degraded analysis is acceptable:
- If iteration < 3 AND pass_rate improved: Accept degraded analysis, continue
- If iteration >= 3 OR pass_rate stagnant: Skip iteration, mark as blocked
3. **User Notification**: Include CLI failure in completion summary
4. **Fallback Strategy**: Use basic pattern matching from fix-history.json
## TodoWrite Coordination

View File

@@ -58,6 +58,19 @@ This command is a **pure planning coordinator**:
- Creates independent test workflow session
- **All execution delegated to `/workflow:test-cycle-execute`**
**Task Attachment Model**:
- SlashCommand invocation **expands workflow** by attaching sub-tasks to current TodoWrite
- When a sub-command is invoked (e.g., `/workflow:tools:test-context-gather`), its internal tasks are attached to the orchestrator's TodoWrite
- Orchestrator **executes these attached tasks** sequentially
- After completion, attached tasks are **collapsed** back to high-level phase summary
- This is **task expansion**, not external delegation
**Auto-Continue Mechanism**:
- TodoList tracks current phase status and dynamically manages task attachment/collapse
- When each phase finishes executing, automatically execute next pending phase
- All phases run autonomously without user interaction
- **⚠️ CONTINUOUS EXECUTION** - Do not stop until all phases complete
---
## Usage
@@ -128,9 +141,11 @@ This command is a **pure planning coordinator**:
3. **Parse Every Output**: Extract required data from each phase for next phase
4. **Sequential Execution**: Each phase depends on previous phase's output
5. **Complete All Phases**: Do not return until Phase 5 completes
6. **Track Progress**: Update TodoWrite after every phase
6. **Track Progress**: Update TodoWrite dynamically with task attachment/collapse pattern
7. **Automatic Detection**: Mode auto-detected from input pattern
8. **Parse Flags**: Extract `--use-codex` and `--cli-execute` flags for Phase 4
9. **Task Attachment Model**: SlashCommand invocation **attaches** sub-tasks to current workflow. Orchestrator **executes** these attached tasks itself, then **collapses** them after completion
10. **⚠️ CRITICAL: DO NOT STOP**: Continuous multi-phase workflow. After executing all attached tasks, immediately collapse them and execute next phase
### 5-Phase Execution
@@ -202,9 +217,25 @@ This command is a **pure planning coordinator**:
**Expected Behavior**:
- Use Gemini to analyze coverage gaps and implementation
- Study existing test patterns and conventions
- Generate test requirements for missing test files
- Design test generation strategy
- Generate `TEST_ANALYSIS_RESULTS.md`
- Generate **multi-layered test requirements** (L0: Static Analysis, L1: Unit, L2: Integration, L3: E2E)
- Design test generation strategy with quality assurance criteria
- Generate `TEST_ANALYSIS_RESULTS.md` with structured test layers
**Enhanced Test Requirements**:
For each targeted file/function, Gemini MUST generate:
1. **L0: Static Analysis Requirements**:
- Linting rules to enforce (ESLint, Prettier)
- Type checking requirements (TypeScript)
- Anti-pattern detection rules
2. **L1: Unit Test Requirements**:
- Happy path scenarios (valid inputs → expected outputs)
- Negative path scenarios (invalid inputs → error handling)
- Edge cases (null, undefined, 0, empty strings/arrays)
3. **L2: Integration Test Requirements**:
- Successful component interactions
- Failure handling scenarios (service unavailable, timeout)
4. **L3: E2E Test Requirements** (if applicable):
- Key user journeys from start to finish
**Parse Output**:
- Verify `.workflow/[testSessionId]/.process/TEST_ANALYSIS_RESULTS.md` created
@@ -213,9 +244,18 @@ This command is a **pure planning coordinator**:
- TEST_ANALYSIS_RESULTS.md exists with complete sections:
- Coverage Assessment
- Test Framework & Conventions
- Test Requirements by File
- **Multi-Layered Test Plan** (NEW):
- L0: Static Analysis Plan
- L1: Unit Test Plan
- L2: Integration Test Plan
- L3: E2E Test Plan (if applicable)
- Test Requirements by File (with layer annotations)
- Test Generation Strategy
- Implementation Targets
- Quality Assurance Criteria (NEW):
- Minimum coverage thresholds
- Required test types per function
- Acceptance criteria for test quality
- Success Criteria
**TodoWrite**: Mark phase 3 completed, phase 4 in_progress
@@ -232,16 +272,18 @@ This command is a **pure planning coordinator**:
- `--cli-execute` flag (if present) - Controls IMPL-001 generation mode
**Expected Behavior**:
- Parse TEST_ANALYSIS_RESULTS.md from Phase 3
- Generate **minimum 2 task JSON files** (expandable based on complexity):
- Parse TEST_ANALYSIS_RESULTS.md from Phase 3 (multi-layered test plan)
- Generate **minimum 3 task JSON files** (expandable based on complexity):
- **IMPL-001.json**: Test Understanding & Generation (`@code-developer`)
- **IMPL-001.5-review.json**: Test Quality Gate (`@test-fix-agent`) ← **NEW**
- **IMPL-002.json**: Test Execution & Fix Cycle (`@test-fix-agent`)
- **IMPL-003+**: Additional tasks if needed for complex projects
- Generate `IMPL_PLAN.md` with test strategy
- Generate `IMPL_PLAN.md` with multi-layered test strategy
- Generate `TODO_LIST.md` with task checklist
**Parse Output**:
- Verify `.workflow/[testSessionId]/.task/IMPL-001.json` exists
- Verify `.workflow/[testSessionId]/.task/IMPL-001.5-review.json` exists ← **NEW**
- Verify `.workflow/[testSessionId]/.task/IMPL-002.json` exists
- Verify additional `.task/IMPL-*.json` if applicable
- Verify `IMPL_PLAN.md` and `TODO_LIST.md` created
@@ -262,11 +304,16 @@ Test Session: [testSessionId]
Tasks Created:
- IMPL-001: Test Understanding & Generation (@code-developer)
- IMPL-001.5: Test Quality Gate - Static Analysis & Coverage (@test-fix-agent) ← NEW
- IMPL-002: Test Execution & Fix Cycle (@test-fix-agent)
[- IMPL-003+: Additional tasks if applicable]
Test Strategy: Multi-Layered (L0: Static, L1: Unit, L2: Integration, L3: E2E)
Test Framework: [detected framework]
Test Files to Generate: [count]
Quality Thresholds:
- Minimum Coverage: 80%
- Static Analysis: Zero critical issues
Max Fix Iterations: 5
Fix Mode: [Manual|Codex Automated]
@@ -275,11 +322,12 @@ Review artifacts:
- Task list: .workflow/[testSessionId]/TODO_LIST.md
CRITICAL - Next Steps:
1. Review IMPL_PLAN.md
1. Review IMPL_PLAN.md (now includes multi-layered test strategy)
2. **MUST execute: /workflow:test-cycle-execute**
- This command only generated task JSON files
- Test execution and fix iterations happen in test-cycle-execute
- Do NOT attempt to run tests or fixes in main workflow
3. IMPL-001.5 will validate test quality before fix cycle begins
```
**TodoWrite**: Mark phase 5 completed
@@ -291,52 +339,133 @@ CRITICAL - Next Steps:
---
### TodoWrite Progress Tracking
### TodoWrite Pattern
Track all 5 phases:
**Core Concept**: Dynamic task attachment and collapse for test-fix-gen workflow with dual-mode support (Session Mode and Prompt Mode).
```javascript
TodoWrite({todos: [
{"content": "Create independent test session", "status": "in_progress|completed", "activeForm": "Creating test session"},
{"content": "Gather test coverage context", "status": "pending|in_progress|completed", "activeForm": "Gathering test coverage context"},
{"content": "Analyze test requirements with Gemini", "status": "pending|in_progress|completed", "activeForm": "Analyzing test requirements"},
{"content": "Generate test generation and execution tasks", "status": "pending|in_progress|completed", "activeForm": "Generating test tasks"},
{"content": "Return workflow summary", "status": "pending|in_progress|completed", "activeForm": "Returning workflow summary"}
]})
```
#### Key Principles
Update status to `in_progress` when starting each phase, `completed` when done.
1. **Task Attachment** (when SlashCommand invoked):
- Sub-command's internal tasks are **attached** to orchestrator's TodoWrite
- Example: `/workflow:tools:test-context-gather` (Session Mode) or `/workflow:tools:context-gather` (Prompt Mode) attaches 3 sub-tasks (Phase 2.1, 2.2, 2.3)
- First attached task marked as `in_progress`, others as `pending`
- Orchestrator **executes** these attached tasks sequentially
2. **Task Collapse** (after sub-tasks complete):
- Remove detailed sub-tasks from TodoWrite
- **Collapse** to high-level phase summary
- Example: Phase 2.1-2.3 collapse to "Gather test coverage context: completed"
- Maintains clean orchestrator-level view
3. **Continuous Execution**:
- After collapse, automatically proceed to next pending phase
- No user intervention required between phases
- TodoWrite dynamically reflects current execution state
**Lifecycle Summary**: Initial pending tasks → Phase invoked (tasks ATTACHED with mode-specific context gathering) → Sub-tasks executed sequentially → Phase completed (tasks COLLAPSED to summary) → Next phase begins → Repeat until all phases complete.
#### Test-Fix-Gen Specific Features
- **Dual-Mode Support**: Automatic mode detection based on input pattern
- **Session Mode**: Input pattern `WFS-*` → uses `test-context-gather` for cross-session context
- **Prompt Mode**: Text or file path → uses `context-gather` for direct codebase analysis
- **Phase 2**: Mode-specific context gathering (session summaries vs codebase analysis)
- **Phase 3**: Multi-layered test requirements analysis (L0: Static, L1: Unit, L2: Integration, L3: E2E)
- **Phase 4**: Multi-task generation with quality gate (IMPL-001, IMPL-001.5-review, IMPL-002)
- **Fix Mode Configuration**: `--use-codex` flag controls IMPL-002 fix mode (manual vs automated)
**Benefits**:
- Real-time visibility into attached tasks during execution
- Clean orchestrator-level summary after tasks complete
- Clear mental model: SlashCommand = attach tasks, not delegate work
- Dual-mode support: Both Session Mode and Prompt Mode use same attachment pattern
- Dynamic attachment/collapse maintains clarity
**Note**: Unlike other workflow orchestrators, this file consolidates TodoWrite examples in this section rather than distributing them across Phase descriptions for better dual-mode clarity.
---
## Task Specifications
Generates minimum 2 tasks (expandable for complex projects):
Generates minimum 3 tasks (expandable for complex projects):
### IMPL-001: Test Understanding & Generation
**Agent**: `@code-developer`
**Purpose**: Understand source implementation and generate test files
**Purpose**: Understand source implementation and generate test files following multi-layered test strategy
**Task Configuration**:
- Task ID: `IMPL-001`
- `meta.type: "test-gen"`
- `meta.agent: "@code-developer"`
- `context.requirements`: Understand source implementation and generate tests
- `context.requirements`: Understand source implementation and generate tests across all layers (L0-L3)
- `flow_control.target_files`: Test files to create from TEST_ANALYSIS_RESULTS.md section 5
**Execution Flow**:
1. **Understand Phase**:
- Load TEST_ANALYSIS_RESULTS.md and test context
- Understand source code implementation patterns
- Analyze test requirements and conventions
- Identify test scenarios and edge cases
- Analyze multi-layered test requirements (L0: Static, L1: Unit, L2: Integration, L3: E2E)
- Identify test scenarios, edge cases, and error paths
2. **Generation Phase**:
- Generate test files following existing patterns
- Ensure test coverage aligns with requirements
- Generate L1 unit test files following existing patterns
- Generate L2 integration test files (if applicable)
- Generate L3 E2E test files (if applicable)
- Ensure test coverage aligns with multi-layered requirements
- Include both positive and negative test cases
3. **Verification Phase**:
- Verify test completeness and correctness
- Ensure each test has meaningful assertions
- Check for test anti-patterns (tests without assertions, overly broad mocks)
### IMPL-001.5: Test Quality Gate ← **NEW**
**Agent**: `@test-fix-agent`
**Purpose**: Validate test quality before entering fix cycle - prevent "hollow tests" from becoming the source of truth
**Task Configuration**:
- Task ID: `IMPL-001.5-review`
- `meta.type: "test-quality-review"`
- `meta.agent: "@test-fix-agent"`
- `context.depends_on: ["IMPL-001"]`
- `context.requirements`: Validate generated tests meet quality standards
- `context.quality_config`: Load from `.claude/workflows/test-quality-config.json`
**Execution Flow**:
1. **L0: Static Analysis**:
- Run linting on test files (ESLint, Prettier)
- Check for test anti-patterns:
- Tests without assertions (`expect()` missing)
- Empty test bodies (`it('should...', () => {})`)
- Disabled tests without justification (`it.skip`, `xit`)
- Verify TypeScript type safety (if applicable)
2. **Coverage Analysis**:
- Run coverage analysis on generated tests
- Calculate coverage percentage for target source files
- Identify uncovered branches and edge cases
3. **Test Quality Metrics**:
- Verify minimum coverage threshold met (default: 80%)
- Verify all critical functions have negative test cases
- Verify integration tests cover key component interactions
4. **Quality Gate Decision**:
- **PASS**: Coverage ≥ 80%, zero critical anti-patterns → Proceed to IMPL-002
- **FAIL**: Coverage < 80% OR critical anti-patterns found → Loop back to IMPL-001 with feedback
**Acceptance Criteria**:
- Static analysis: Zero critical issues
- Test coverage: ≥ 80% for target files
- Test completeness: All targeted functions have unit tests
- Negative test coverage: Each public API has at least one error handling test
- Integration coverage: Key component interactions have integration tests (if applicable)
**Failure Handling**:
If quality gate fails:
1. Generate detailed feedback report (`.process/test-quality-report.md`)
2. Update IMPL-001 task with specific improvement requirements
3. Trigger IMPL-001 re-execution with enhanced context
4. Maximum 2 quality gate retries before escalating to user
### IMPL-002: Test Execution & Fix Cycle
@@ -412,18 +541,62 @@ WFS-test-[session]/
- `workflow_type: "test_session"`
- No `source_session_id` field
### Complete Data Flow
### Execution Flow Diagram
**Example Command**: `/workflow:test-fix-gen WFS-user-auth`
```
Test-Fix-Gen Workflow Orchestrator (Dual-Mode Support)
├─ Phase 1: Create Test Session
│ ├─ Session Mode: /workflow:session:start --new (with source_session_id)
│ └─ Prompt Mode: /workflow:session:start --new (without source_session_id)
│ └─ Returns: testSessionId (WFS-test-[slug])
├─ Phase 2: Gather Context ← ATTACHED (3 tasks)
│ ├─ Session Mode: /workflow:tools:test-context-gather
│ │ └─ Load source session summaries + analyze coverage
│ └─ Prompt Mode: /workflow:tools:context-gather
│ └─ Analyze codebase from description
│ ├─ Phase 2.1: Load context and analyze coverage
│ ├─ Phase 2.2: Detect test framework and conventions
│ └─ Phase 2.3: Generate context package
│ └─ Returns: [test-]context-package.json ← COLLAPSED
├─ Phase 3: Test Generation Analysis ← ATTACHED (3 tasks)
│ └─ /workflow:tools:test-concept-enhanced
│ ├─ Phase 3.1: Analyze coverage gaps with Gemini
│ ├─ Phase 3.2: Study existing test patterns
│ └─ Phase 3.3: Generate test generation strategy
│ └─ Returns: TEST_ANALYSIS_RESULTS.md ← COLLAPSED
├─ Phase 4: Generate Test Tasks ← ATTACHED (3 tasks)
│ └─ /workflow:tools:test-task-generate
│ ├─ Phase 4.1: Parse TEST_ANALYSIS_RESULTS.md
│ ├─ Phase 4.2: Generate task JSONs (IMPL-001, IMPL-002)
│ └─ Phase 4.3: Generate IMPL_PLAN.md and TODO_LIST.md
│ └─ Returns: Task JSONs and plans ← COLLAPSED
└─ Phase 5: Return Summary
└─ Command ends, control returns to user
**Phase Execution Chain**:
1. Phase 1: `session-start``WFS-test-user-auth`
2. Phase 2: `test-context-gather``test-context-package.json`
3. Phase 3: `test-concept-enhanced``TEST_ANALYSIS_RESULTS.md`
4. Phase 4: `test-task-generate``IMPL-001.json` + `IMPL-002.json` (+ additional if needed)
5. Phase 5: Return summary
Artifacts Created:
├── .workflow/WFS-test-[session]/
│ ├── workflow-session.json
│ ├── IMPL_PLAN.md
│ ├── TODO_LIST.md
│ ├── .task/
│ │ ├── IMPL-001.json (test understanding & generation)
│ │ ├── IMPL-002.json (test execution & fix cycle)
│ │ └── IMPL-003.json (optional: test review & certification)
│ └── .process/
│ ├── [test-]context-package.json
│ └── TEST_ANALYSIS_RESULTS.md
**Command completes after Phase 5**
Key Points:
• ← ATTACHED: SlashCommand attaches sub-tasks to orchestrator TodoWrite
• ← COLLAPSED: Sub-tasks executed and collapsed to phase summary
• Dual-Mode: Session Mode and Prompt Mode share same attachment pattern
• Command Boundary: Execution delegated to /workflow:test-cycle-execute
```
---

View File

@@ -18,6 +18,19 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
- **Parameter Simplification**: Tools auto-detect test session type via metadata, no manual cross-session parameters needed
- **Manual First**: Default to manual fixes, use `--use-codex` flag for automated Codex fix application
**Task Attachment Model**:
- SlashCommand invocation **expands workflow** by attaching sub-tasks to current TodoWrite
- When a sub-command is invoked (e.g., `/workflow:tools:test-context-gather`), its internal tasks are attached to the orchestrator's TodoWrite
- Orchestrator **executes these attached tasks** sequentially
- After completion, attached tasks are **collapsed** back to high-level phase summary
- This is **task expansion**, not external delegation
**Auto-Continue Mechanism**:
- TodoList tracks current phase status and dynamically manages task attachment/collapse
- When each phase finishes executing, automatically execute next pending phase
- All phases run autonomously without user interaction
- **⚠️ CONTINUOUS EXECUTION** - Do not stop until all phases complete
**Execution Flow**:
1. Initialize TodoWrite → Create test session → Parse session ID
2. Gather cross-session context (automatic) → Parse context path
@@ -33,10 +46,12 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
3. **Parse Every Output**: Extract required data from each phase for next phase
4. **Sequential Execution**: Each phase depends on previous phase's output
5. **Complete All Phases**: Do not return to user until Phase 5 completes (summary returned)
6. **Track Progress**: Update TodoWrite after every phase completion
6. **Track Progress**: Update TodoWrite dynamically with task attachment/collapse pattern
7. **Automatic Detection**: context-gather auto-detects test session and gathers source session context
8. **Parse --use-codex Flag**: Extract flag from arguments and pass to Phase 4 (test-task-generate)
9. **Command Boundary**: This command ends at Phase 5 summary. Test execution is NOT part of this command.
10. **Task Attachment Model**: SlashCommand invocation **attaches** sub-tasks to current workflow. Orchestrator **executes** these attached tasks itself, then **collapses** them after completion
11. **⚠️ CRITICAL: DO NOT STOP**: Continuous multi-phase workflow. After executing all attached tasks, immediately collapse them and execute next phase
## 5-Phase Execution
@@ -89,7 +104,39 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
- Test framework detected
- Test conventions documented
**TodoWrite**: Mark phase 2 completed, phase 3 in_progress
<!-- TodoWrite: When test-context-gather invoked, INSERT 3 test-context-gather tasks -->
**TodoWrite Update (Phase 2 SlashCommand invoked - tasks attached)**:
```json
[
{"content": "Create independent test session", "status": "completed", "activeForm": "Creating test session"},
{"content": "Phase 2.1: Load source session summaries (test-context-gather)", "status": "in_progress", "activeForm": "Loading source session summaries"},
{"content": "Phase 2.2: Analyze test coverage with MCP tools (test-context-gather)", "status": "pending", "activeForm": "Analyzing test coverage"},
{"content": "Phase 2.3: Identify coverage gaps and framework (test-context-gather)", "status": "pending", "activeForm": "Identifying coverage gaps"},
{"content": "Analyze test requirements with Gemini", "status": "pending", "activeForm": "Analyzing test requirements"},
{"content": "Generate test generation and execution tasks", "status": "pending", "activeForm": "Generating test tasks"},
{"content": "Return workflow summary", "status": "pending", "activeForm": "Returning workflow summary"}
]
```
**Note**: SlashCommand invocation **attaches** test-context-gather's 3 tasks. Orchestrator **executes** these tasks.
**Next Action**: Tasks attached → **Execute Phase 2.1-2.3** sequentially
<!-- TodoWrite: After Phase 2 tasks complete, REMOVE Phase 2.1-2.3, restore to orchestrator view -->
**TodoWrite Update (Phase 2 completed - tasks collapsed)**:
```json
[
{"content": "Create independent test session", "status": "completed", "activeForm": "Creating test session"},
{"content": "Gather test coverage context", "status": "completed", "activeForm": "Gathering test coverage context"},
{"content": "Analyze test requirements with Gemini", "status": "pending", "activeForm": "Analyzing test requirements"},
{"content": "Generate test generation and execution tasks", "status": "pending", "activeForm": "Generating test tasks"},
{"content": "Return workflow summary", "status": "pending", "activeForm": "Returning workflow summary"}
]
```
**Note**: Phase 2 tasks completed and collapsed to summary.
---
@@ -121,7 +168,39 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
- Implementation Targets (test files to create)
- Success Criteria
**TodoWrite**: Mark phase 3 completed, phase 4 in_progress
<!-- TodoWrite: When test-concept-enhanced invoked, INSERT 3 concept-enhanced tasks -->
**TodoWrite Update (Phase 3 SlashCommand invoked - tasks attached)**:
```json
[
{"content": "Create independent test session", "status": "completed", "activeForm": "Creating test session"},
{"content": "Gather test coverage context", "status": "completed", "activeForm": "Gathering test coverage context"},
{"content": "Phase 3.1: Analyze coverage gaps with Gemini (test-concept-enhanced)", "status": "in_progress", "activeForm": "Analyzing coverage gaps"},
{"content": "Phase 3.2: Study existing test patterns (test-concept-enhanced)", "status": "pending", "activeForm": "Studying test patterns"},
{"content": "Phase 3.3: Generate test generation strategy (test-concept-enhanced)", "status": "pending", "activeForm": "Generating test strategy"},
{"content": "Generate test generation and execution tasks", "status": "pending", "activeForm": "Generating test tasks"},
{"content": "Return workflow summary", "status": "pending", "activeForm": "Returning workflow summary"}
]
```
**Note**: SlashCommand invocation **attaches** test-concept-enhanced's 3 tasks. Orchestrator **executes** these tasks.
**Next Action**: Tasks attached → **Execute Phase 3.1-3.3** sequentially
<!-- TodoWrite: After Phase 3 tasks complete, REMOVE Phase 3.1-3.3, restore to orchestrator view -->
**TodoWrite Update (Phase 3 completed - tasks collapsed)**:
```json
[
{"content": "Create independent test session", "status": "completed", "activeForm": "Creating test session"},
{"content": "Gather test coverage context", "status": "completed", "activeForm": "Gathering test coverage context"},
{"content": "Analyze test requirements with Gemini", "status": "completed", "activeForm": "Analyzing test requirements"},
{"content": "Generate test generation and execution tasks", "status": "pending", "activeForm": "Generating test tasks"},
{"content": "Return workflow summary", "status": "pending", "activeForm": "Returning workflow summary"}
]
```
**Note**: Phase 3 tasks completed and collapsed to summary.
---
@@ -173,7 +252,39 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
- Phase 2: Iterative Gemini diagnosis + manual/Codex fixes (based on flag)
- Phase 3: Final validation and certification
**TodoWrite**: Mark phase 4 completed, phase 5 in_progress
<!-- TodoWrite: When test-task-generate invoked, INSERT 3 test-task-generate tasks -->
**TodoWrite Update (Phase 4 SlashCommand invoked - tasks attached)**:
```json
[
{"content": "Create independent test session", "status": "completed", "activeForm": "Creating test session"},
{"content": "Gather test coverage context", "status": "completed", "activeForm": "Gathering test coverage context"},
{"content": "Analyze test requirements with Gemini", "status": "completed", "activeForm": "Analyzing test requirements"},
{"content": "Phase 4.1: Parse TEST_ANALYSIS_RESULTS.md (test-task-generate)", "status": "in_progress", "activeForm": "Parsing test analysis"},
{"content": "Phase 4.2: Generate IMPL-001.json and IMPL-002.json (test-task-generate)", "status": "pending", "activeForm": "Generating task JSONs"},
{"content": "Phase 4.3: Generate IMPL_PLAN.md and TODO_LIST.md (test-task-generate)", "status": "pending", "activeForm": "Generating plan documents"},
{"content": "Return workflow summary", "status": "pending", "activeForm": "Returning workflow summary"}
]
```
**Note**: SlashCommand invocation **attaches** test-task-generate's 3 tasks. Orchestrator **executes** these tasks.
**Next Action**: Tasks attached → **Execute Phase 4.1-4.3** sequentially
<!-- TodoWrite: After Phase 4 tasks complete, REMOVE Phase 4.1-4.3, restore to orchestrator view -->
**TodoWrite Update (Phase 4 completed - tasks collapsed)**:
```json
[
{"content": "Create independent test session", "status": "completed", "activeForm": "Creating test session"},
{"content": "Gather test coverage context", "status": "completed", "activeForm": "Gathering test coverage context"},
{"content": "Analyze test requirements with Gemini", "status": "completed", "activeForm": "Analyzing test requirements"},
{"content": "Generate test generation and execution tasks", "status": "completed", "activeForm": "Generating test tasks"},
{"content": "Return workflow summary", "status": "in_progress", "activeForm": "Returning workflow summary"}
]
```
**Note**: Phase 4 tasks completed and collapsed to summary.
---
@@ -214,37 +325,76 @@ Ready for execution. Use appropriate workflow commands to proceed.
## TodoWrite Pattern
Track progress through 5 phases:
**Core Concept**: Dynamic task attachment and collapse for test-gen workflow with cross-session context gathering and test generation strategy.
```javascript
TodoWrite({todos: [
{"content": "Create independent test session", "status": "in_progress|completed", "activeForm": "Creating test session"},
{"content": "Gather test coverage context", "status": "pending|in_progress|completed", "activeForm": "Gathering test coverage context"},
{"content": "Analyze test requirements with Gemini", "status": "pending|in_progress|completed", "activeForm": "Analyzing test requirements"},
{"content": "Generate test generation and execution tasks", "status": "pending|in_progress|completed", "activeForm": "Generating test tasks"},
{"content": "Return workflow summary", "status": "pending|in_progress|completed", "activeForm": "Returning workflow summary"}
]})
```
### Key Principles
Update status to `in_progress` when starting each phase, mark `completed` when done.
1. **Task Attachment** (when SlashCommand invoked):
- Sub-command's internal tasks are **attached** to orchestrator's TodoWrite
- Example: `/workflow:tools:test-context-gather` attaches 3 sub-tasks (Phase 2.1, 2.2, 2.3)
- First attached task marked as `in_progress`, others as `pending`
- Orchestrator **executes** these attached tasks sequentially
## Data Flow
2. **Task Collapse** (after sub-tasks complete):
- Remove detailed sub-tasks from TodoWrite
- **Collapse** to high-level phase summary
- Example: Phase 2.1-2.3 collapse to "Gather test coverage context: completed"
- Maintains clean orchestrator-level view
3. **Continuous Execution**:
- After collapse, automatically proceed to next pending phase
- No user intervention required between phases
- TodoWrite dynamically reflects current execution state
**Lifecycle Summary**: Initial pending tasks → Phase invoked (tasks ATTACHED) → Sub-tasks executed sequentially → Phase completed (tasks COLLAPSED to summary) → Next phase begins → Repeat until all phases complete.
### Test-Gen Specific Features
- **Phase 2**: Cross-session context gathering from source implementation session
- **Phase 3**: Test requirements analysis with Gemini for generation strategy
- **Phase 4**: Dual-task generation (IMPL-001 for test generation, IMPL-002 for test execution)
- **Fix Mode Configuration**: `--use-codex` flag controls IMPL-002 fix mode (manual vs automated)
**Benefits**:
- Real-time visibility into attached tasks during execution
- Clean orchestrator-level summary after tasks complete
- Clear mental model: SlashCommand = attach tasks, not delegate work
- Dynamic attachment/collapse maintains clarity
**Note**: See individual Phase descriptions (Phase 2, 3, 4) for detailed TodoWrite Update examples with full JSON structures.
## Execution Flow Diagram
```
┌─────────────────────────────────────────────────────────┐
│ /workflow:test-gen WFS-user-auth
├─────────────────────────────────────────────────────────┤
Phase 1: session-start → WFS-test-user-auth │
↓ │
│ Phase 2: test-context-gather → test-context-package.json
│ ↓
Phase 3: test-concept-enhanced → TEST_ANALYSIS_RESULTS.md│
↓ │
Phase 4: test-task-generate → IMPL-001.json + IMPL-002.json│
Phase 5: Return summary
└─────────────────────────────────────────────────────────┘
COMMAND ENDS - Control returns to user
Test-Gen Workflow Orchestrator
├─ Phase 1: Create Test Session
└─ /workflow:session:start --new
└─ Returns: testSessionId (WFS-test-[source])
├─ Phase 2: Gather Test Context ← ATTACHED (3 tasks)
└─ /workflow:tools:test-context-gather
├─ Phase 2.1: Load source session summaries
├─ Phase 2.2: Analyze test coverage with MCP tools
└─ Phase 2.3: Identify coverage gaps and framework
└─ Returns: test-context-package.json ← COLLAPSED
├─ Phase 3: Test Generation Analysis ← ATTACHED (3 tasks)
│ └─ /workflow:tools:test-concept-enhanced
│ ├─ Phase 3.1: Analyze coverage gaps with Gemini
│ ├─ Phase 3.2: Study existing test patterns
│ └─ Phase 3.3: Generate test generation strategy
│ └─ Returns: TEST_ANALYSIS_RESULTS.md ← COLLAPSED
├─ Phase 4: Generate Test Tasks ← ATTACHED (3 tasks)
│ └─ /workflow:tools:test-task-generate
│ ├─ Phase 4.1: Parse TEST_ANALYSIS_RESULTS.md
│ ├─ Phase 4.2: Generate IMPL-001.json and IMPL-002.json
│ └─ Phase 4.3: Generate IMPL_PLAN.md and TODO_LIST.md
│ └─ Returns: Task JSONs and plans ← COLLAPSED
└─ Phase 5: Return Summary
└─ Command ends, control returns to user
Artifacts Created:
├── .workflow/WFS-test-[session]/
@@ -257,6 +407,10 @@ Artifacts Created:
│ └── .process/
│ ├── test-context-package.json
│ └── TEST_ANALYSIS_RESULTS.md
Key Points:
• ← ATTACHED: SlashCommand attaches sub-tasks to orchestrator TodoWrite
• ← COLLAPSED: Sub-tasks executed and collapsed to phase summary
```
## Session Metadata

View File

@@ -1,7 +1,7 @@
---
name: capture
description: Batch screenshot capture for UI design workflows using MCP puppeteer or local fallback with URL mapping
argument-hint: --url-map "target:url,..." [--base-path path] [--session id]
argument-hint: --url-map "target:url,..." [--design-id <id>] [--session <id>]
allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*), ListMcpResourcesTool(*), mcp__chrome-devtools__*, mcp__playwright__*
---
@@ -15,21 +15,38 @@ Batch screenshot tool with MCP-first strategy and multi-tier fallback. Processes
## Phase 1: Initialize & Parse
### Step 1: Determine Base Path
### Step 1: Determine Base Path & Generate Design ID
```bash
# Priority: --base-path > session > standalone
relative_path=$(if [ -n "$BASE_PATH" ]; then
echo "$BASE_PATH"
# Priority: --design-id > session (latest) > standalone (create new)
if [ -n "$DESIGN_ID" ]; then
# Use provided design ID
relative_path=$(find .workflow -name "${DESIGN_ID}" -type d -print -quit)
if [ -z "$relative_path" ]; then
echo "ERROR: Design run not found: $DESIGN_ID"
echo "HINT: Run '/workflow:ui-design:list' to see available design runs"
exit 1
fi
elif [ -n "$SESSION_ID" ]; then
find .workflow/WFS-$SESSION_ID/design-* -type d -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2 || \
echo ".workflow/WFS-$SESSION_ID/design-run-$(date +%Y%m%d)-$RANDOM"
# Find latest in session or create new
relative_path=$(find .workflow/WFS-$SESSION_ID -name "design-run-*" -type d -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2)
if [ -z "$relative_path" ]; then
design_id="design-run-$(date +%Y%m%d)-$RANDOM"
relative_path=".workflow/WFS-$SESSION_ID/${design_id}"
fi
else
echo ".workflow/.design/design-run-$(date +%Y%m%d)-$RANDOM"
fi)
# Create new standalone design run
design_id="design-run-$(date +%Y%m%d)-$RANDOM"
relative_path=".workflow/${design_id}"
fi
# Create directory and convert to absolute path
bash(mkdir -p "$relative_path"/screenshots)
base_path=$(cd "$relative_path" && pwd)
# Extract and display design_id
design_id=$(basename "$base_path")
echo "✓ Design ID: $design_id"
echo "✓ Base path: $base_path"
```
### Step 2: Parse URL Map
@@ -189,7 +206,7 @@ bash($chrome --headless --screenshot="$output_file" --window-size=1920,1080 "$ur
Failed URLs:
home: https://linear.app
Save to: .workflow/.design/design-run-20250110/screenshots/home.png
Save to: .workflow/design-run-20250110/screenshots/home.png
Steps:
1. Visit URL in browser

View File

@@ -0,0 +1,678 @@
---
name: workflow:ui-design:codify-style
description: Orchestrator to extract styles from code and generate shareable reference package with preview (automatic file discovery)
argument-hint: "<path> [--package-name <name>] [--output-dir <path>] [--overwrite]"
allowed-tools: SlashCommand,Bash,Read,TodoWrite
auto-continue: true
---
# UI Design: Codify Style (Orchestrator)
## Overview & Execution Model
**Fully autonomous orchestrator**: Coordinates style extraction from codebase and generates shareable reference packages.
**Pure Orchestrator Pattern**: Does NOT directly execute agent tasks. Delegates to specialized commands:
1. `/workflow:ui-design:import-from-code` - Extract styles from source code
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}/`
**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) → **Attach 4 tasks → Execute tasks → Collapse** → Auto-continues to Phase 2
4. Phase 2 (reference-page-generator) → **Attach 4 tasks → Execute tasks → Collapse** → Auto-continues to Phase 3
5. Phase 3 (cleanup & verification) → **Execute orchestrator task** → Reports completion
**Phase Transition Mechanism**:
- **Phase 0 (Validation)**: Validate parameters, prepare workspace → IMMEDIATELY triggers Phase 1
- **Phase 1-2 (Task Attachment)**: `SlashCommand` invocation **ATTACHES** tasks to current workflow. Orchestrator **EXECUTES** these tasks itself.
- **Task Execution**: Orchestrator runs attached tasks sequentially, updating TodoWrite as each completes
- **Task Collapse**: After all attached tasks complete, collapse them into phase summary
- **Phase Transition**: Automatically execute next phase after collapsing completed tasks
- No user interaction required after initial command
**Auto-Continue Mechanism**: TodoWrite tracks phase status with dynamic task attachment/collapse. After executing all attached tasks, you MUST immediately collapse them, restore phase summary, and execute the next phase. No user intervention required. The workflow is NOT complete until reaching Phase 3.
**Task Attachment Model**: SlashCommand invocation is NOT delegation - it's task expansion. The orchestrator executes these attached tasks itself, not waiting for external completion.
## Core Rules
1. **Start Immediately**: TodoWrite initialization → Phase 0 validation → Phase 1 execution
2. **No Task JSON**: This command does not create task JSON files - pure orchestrator pattern
3. **Parse & Pass**: Extract required data from each command output (design run path, metadata)
4. **Intelligent Validation**: Smart parameter validation with user-friendly error messages
5. **Safety First**: Package overwrite protection, existence checks, fallback error handling
6. **Track Progress**: Update TodoWrite dynamically with task attachment/collapse pattern
7. **⚠️ CRITICAL: Task Attachment Model** - SlashCommand invocation **ATTACHES** tasks to current workflow. Orchestrator **EXECUTES** these attached tasks itself, not waiting for external completion. This is NOT delegation - it's task expansion.
8. **⚠️ CRITICAL: DO NOT STOP** - This is a continuous multi-phase workflow. After executing all attached tasks, you MUST immediately collapse them and execute the next phase. Workflow is NOT complete until Phase 3.
---
## Usage
### Command Syntax
```bash
/workflow:ui-design:codify-style <path> [OPTIONS]
# Required
<path> Source code directory to analyze
# Optional
--package-name <name> Custom name for the style reference package
(default: auto-generated from directory name)
--output-dir <path> Output directory (default: .workflow/reference_style)
--overwrite Overwrite existing package without prompting
```
**Note**: File discovery is fully automatic. The command will scan the source directory and find all style-related files (CSS, SCSS, JS, HTML) automatically.
---
## 4-Phase Execution
### Phase 0: Intelligent Parameter Validation & Session Preparation
**Goal**: Validate parameters, check safety constraints, prepare session, and get user confirmation
**TodoWrite** (First Action):
```json
[
{"content": "Phase 0: Validate parameters and prepare session", "status": "in_progress", "activeForm": "Validating parameters"},
{"content": "Phase 1: Style extraction from source code (import-from-code)", "status": "pending", "activeForm": "Extracting styles"},
{"content": "Phase 2: Reference package generation (reference-page-generator)", "status": "pending", "activeForm": "Generating package"},
{"content": "Phase 3: Cleanup and verify package", "status": "pending", "activeForm": "Cleanup and verification"}
]
```
**Note**: Orchestrator tracks only high-level phases. Sub-command details shown when executed.
**Step 0a: Parse and Validate Required Parameters**
```bash
# 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"
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
```
**Step 0b: Intelligent Package Safety Check**
```bash
# 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..."
```
**Step 0c: Session Preparation**
```bash
# Create temporary workspace for processing
TRY:
# Step 1: Ensure .workflow directory exists and generate unique ID
Bash(mkdir -p .workflow)
temp_id = Bash(echo "codify-temp-$(date +%Y%m%d-%H%M%S)")
# Step 2: Create temporary directory
Bash(mkdir -p ".workflow/${temp_id}")
# Step 3: Get absolute path using bash
design_run_path = Bash(cd ".workflow/${temp_id}" && pwd)
CATCH error:
REPORT: "❌ ERROR: Failed to create temporary workspace: ${error}"
EXIT 1
STORE: temp_id, design_run_path
```
**Summary Variables**:
- `SOURCE`: Validated source directory path
- `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
- `OVERWRITE`: `true` if --overwrite flag present
- `CSS/SCSS/JS/HTML/STYLE_FILES`: Optional glob patterns
- `TEMP_ID`: `codify-temp-{timestamp}` (temporary workspace identifier)
- `DESIGN_RUN_PATH`: Absolute path to temporary workspace
<!-- TodoWrite: Update Phase 0 → completed, Phase 1 → in_progress, INSERT import-from-code tasks -->
**TodoWrite Update (Phase 1 SlashCommand invoked - tasks attached)**:
```json
[
{"content": "Phase 0: Validate parameters and prepare session", "status": "completed", "activeForm": "Validating parameters"},
{"content": "Phase 1.0: Discover and categorize code files (import-from-code)", "status": "in_progress", "activeForm": "Discovering code files"},
{"content": "Phase 1.1: Style Agent extraction (import-from-code)", "status": "pending", "activeForm": "Extracting style tokens"},
{"content": "Phase 1.2: Animation Agent extraction (import-from-code)", "status": "pending", "activeForm": "Extracting animation tokens"},
{"content": "Phase 1.3: Layout Agent extraction (import-from-code)", "status": "pending", "activeForm": "Extracting layout patterns"},
{"content": "Phase 2: Reference package generation (reference-page-generator)", "status": "pending", "activeForm": "Generating package"},
{"content": "Phase 3: Cleanup and verify package", "status": "pending", "activeForm": "Cleanup and verification"}
]
```
**Note**: SlashCommand invocation **attaches** import-from-code's 4 tasks to current workflow. Orchestrator **executes** these tasks itself.
**Next Action**: Tasks attached → **Execute Phase 1.0-1.3** sequentially
---
### Phase 1: Style Extraction from Source Code
**Goal**: Extract design tokens, style patterns, and component styles from codebase
**Command Construction**:
```bash
# Build command with required parameters only
# Use temp_id as design-id since it's the workspace directory name
command = "/workflow:ui-design:import-from-code" +
" --design-id \"${temp_id}\"" +
" --source \"${source}\""
```
**Execute Command (Task Attachment Pattern)**:
```bash
TRY:
# SlashCommand invocation ATTACHES import-from-code's 4 tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself:
# 1. Phase 1.0: Discover and categorize code files
# 2. Phase 1.1: Style Agent extraction
# 3. Phase 1.2: Animation Agent extraction
# 4. Phase 1.3: Layout Agent extraction
SlashCommand(command)
# After executing all attached tasks, 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: "Continuing with available outputs..."
CATCH error:
REPORT: "❌ ERROR: Style extraction failed"
REPORT: "Error: ${error}"
REPORT: "Possible cause: Source directory contains no style files"
Bash(rm -rf .workflow/${temp_id})
EXIT 1
```
**Example Command**:
```bash
# Automatic file discovery
/workflow:ui-design:import-from-code --design-id codify-temp-20250111-123456 --source ./src
```
**Completion Criteria**:
-`import-from-code` command executed successfully
- ✅ Design run created at `${design_run_path}`
- ✅ Required files exist:
- `design-tokens.json` - Complete design token system
- `style-guide.md` - Style documentation
- ⭕ Optional files:
- `animation-tokens.json` - Animation specifications
- `component-patterns.json` - Component catalog
<!-- TodoWrite: REMOVE Phase 1.0-1.3 tasks, INSERT reference-page-generator tasks -->
**TodoWrite Update (Phase 2 SlashCommand invoked - tasks attached)**:
```json
[
{"content": "Phase 0: Validate parameters and prepare session", "status": "completed", "activeForm": "Validating parameters"},
{"content": "Phase 1: Style extraction from source code (import-from-code)", "status": "completed", "activeForm": "Extracting styles"},
{"content": "Phase 2.1: Validation and preparation (reference-page-generator)", "status": "in_progress", "activeForm": "Validating parameters"},
{"content": "Phase 2.2: Component pattern extraction (reference-page-generator)", "status": "pending", "activeForm": "Extracting component patterns"},
{"content": "Phase 2.3: Generate preview pages (reference-page-generator)", "status": "pending", "activeForm": "Generating preview"},
{"content": "Phase 2.4: Generate metadata and documentation (reference-page-generator)", "status": "pending", "activeForm": "Generating documentation"},
{"content": "Phase 3: Cleanup and verify package", "status": "pending", "activeForm": "Cleanup and verification"}
]
```
**Note**: Phase 1 tasks completed and collapsed. SlashCommand invocation **attaches** reference-page-generator's 4 tasks. Orchestrator **executes** these tasks itself.
**Next Action**: Tasks attached → **Execute Phase 2.1-2.4** sequentially
---
### Phase 2: Reference Package Generation
**Goal**: Generate shareable reference package with interactive preview and documentation
**Command Construction**:
```bash
command = "/workflow:ui-design:reference-page-generator " +
"--design-run \"${design_run_path}\" " +
"--package-name \"${package_name}\" " +
"--output-dir \"${output_dir}\""
```
**Execute Command (Task Attachment Pattern)**:
```bash
TRY:
# SlashCommand invocation ATTACHES reference-page-generator's 4 tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself:
# 1. Phase 2.1: Validation and preparation
# 2. Phase 2.2: Component pattern extraction
# 3. Phase 2.3: Generate preview pages
# 4. Phase 2.4: Generate metadata and documentation
SlashCommand(command)
# After executing all attached tasks, 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"
REPORT: "Package may be incomplete. Continuing with cleanup..."
CATCH error:
REPORT: "❌ ERROR: Reference package generation failed"
REPORT: "Error: ${error}"
Bash(rm -rf .workflow/${temp_id})
EXIT 1
```
**Example Command**:
```bash
/workflow:ui-design:reference-page-generator \
--design-run .workflow/codify-temp-20250111-123456 \
--package-name main-app-style-v1 \
--output-dir .workflow/reference_style
```
**Completion Criteria**:
-`reference-page-generator` executed successfully
- ✅ Reference package created at `${package_path}/`
- ✅ All required files present:
- `design-tokens.json` - Complete design token system
- `component-patterns.json` - Component catalog
- `preview.html` - Interactive multi-component showcase
- `preview.css` - Showcase styling
- `metadata.json` - Package metadata and version info
- `README.md` - Package documentation and usage guide
- ⭕ Optional files:
- `animation-tokens.json` - Animation specifications (if available from extraction)
<!-- TodoWrite: REMOVE Phase 2.1-2.4 tasks, restore to orchestrator view -->
**TodoWrite Update (Phase 2 completed - tasks collapsed)**:
```json
[
{"content": "Phase 0: Validate parameters and prepare session", "status": "completed", "activeForm": "Validating parameters"},
{"content": "Phase 1: Style extraction from source code (import-from-code)", "status": "completed", "activeForm": "Extracting styles"},
{"content": "Phase 2: Reference package generation (reference-page-generator)", "status": "completed", "activeForm": "Generating package"},
{"content": "Phase 3: Cleanup and verify package", "status": "in_progress", "activeForm": "Cleanup and verification"}
]
```
**Note**: Phase 2 tasks completed and collapsed to summary.
**Next Action**: TodoWrite restored → **Execute Phase 3** (orchestrator's own task)
---
### Phase 3: Cleanup & Verification
**Goal**: Clean up temporary workspace and report completion
**Operations**:
```bash
# Cleanup temporary workspace
TRY:
Bash(rm -rf .workflow/${temp_id})
CATCH error:
# Silent failure - not critical
# Quick verification
package_exists = Bash(test -d "${package_path}" && echo "exists" || echo "missing")
IF package_exists != "exists":
REPORT: "❌ ERROR: Package generation failed - directory not found"
EXIT 1
# 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 "○")
```
<!-- TodoWrite: Update Phase 3 → completed -->
**Final Action**: Display completion summary to user
---
## Completion Message
```
✅ Style reference package generated successfully
📦 Package: {package_name}
📂 Location: {absolute_package_path}/
📄 Source: {source}
📊 Components: {component_count}
Files: design-tokens.json, style-guide.md, component-patterns.json, preview.html, preview.css, metadata.json, README.md
Preview: file://{absolute_package_path}/preview.html
Next: /memory:style-skill-memory {package_name}
```
---
## TodoWrite Pattern
```javascript
// Initialize IMMEDIATELY at the start to track orchestrator workflow (4 high-level tasks)
TodoWrite({todos: [
{"content": "Phase 0: Validate parameters and prepare session", "status": "in_progress", "activeForm": "Validating parameters"},
{"content": "Phase 1: Style extraction from source code (import-from-code)", "status": "pending", "activeForm": "Extracting styles"},
{"content": "Phase 2: Reference package generation (reference-page-generator)", "status": "pending", "activeForm": "Generating package"},
{"content": "Phase 3: Cleanup and verify package", "status": "pending", "activeForm": "Cleanup and verification"}
]})
// ⚠️ CRITICAL: Dynamic TodoWrite task attachment strategy:
//
// **Key Concept**: SlashCommand invocation ATTACHES tasks to current workflow.
// Orchestrator EXECUTES these attached tasks itself, not waiting for external completion.
//
// 1. INITIAL STATE: 4 orchestrator-level tasks only
//
// 2. PHASE 1 SlashCommand INVOCATION:
// - SlashCommand(/workflow:ui-design:import-from-code) ATTACHES 4 tasks
// - TodoWrite expands to: Phase 0 (completed) + 4 import-from-code tasks + Phase 2 + Phase 3
// - Orchestrator EXECUTES these 4 tasks sequentially (Phase 1.0 → 1.1 → 1.2 → 1.3)
// - First attached task marked as in_progress
//
// 3. PHASE 1 TASKS COMPLETED:
// - All 4 import-from-code tasks executed and completed
// - COLLAPSE completed tasks into Phase 1 summary
// - TodoWrite becomes: Phase 0-1 (completed) + Phase 2 + Phase 3
//
// 4. PHASE 2 SlashCommand INVOCATION:
// - SlashCommand(/workflow:ui-design:reference-page-generator) ATTACHES 4 tasks
// - TodoWrite expands to: Phase 0-1 (completed) + 4 reference-page-generator tasks + Phase 3
// - Orchestrator EXECUTES these 4 tasks sequentially (Phase 2.1 → 2.2 → 2.3 → 2.4)
//
// 5. PHASE 2 TASKS COMPLETED:
// - All 4 reference-page-generator tasks executed and completed
// - COLLAPSE completed tasks into Phase 2 summary
// - TodoWrite returns to: Phase 0-2 (completed) + Phase 3 (in_progress)
//
// 6. PHASE 3 EXECUTION:
// - Orchestrator's own task (no SlashCommand attachment)
// - Mark Phase 3 as completed
// - Final state: All 4 orchestrator tasks completed
//
// Benefits:
// ✓ Real-time visibility into attached tasks during execution
// ✓ Clean orchestrator-level summary after tasks complete
// ✓ Clear mental model: SlashCommand = attach tasks, not delegate work
// ✓ Dynamic attachment/collapse maintains clarity
```
---
## Execution Flow Diagram
```
User triggers: /workflow:ui-design:codify-style ./src --package-name my-style-v1
[TodoWrite Init] 4 orchestrator-level tasks
├─ Phase 0: Validate parameters and prepare session (in_progress)
├─ Phase 1: Style extraction from source code (pending)
├─ Phase 2: Reference package generation (pending)
└─ Phase 3: Cleanup and verify package (pending)
[Phase 0] Parameter validation & preparation
├─ Parse positional path parameter
├─ Validate source directory exists
├─ Auto-generate or validate package name
├─ Check package overwrite protection
├─ Create temporary workspace
└─ Display configuration summary
[Phase 0 Complete] → TodoWrite: Phase 0 → completed
[Phase 1 Invoke] → SlashCommand(/workflow:ui-design:import-from-code) ATTACHES 4 tasks
├─ Phase 0 (completed)
├─ Phase 1.0: Discover and categorize code files (in_progress) ← ATTACHED
├─ Phase 1.1: Style Agent extraction (pending) ← ATTACHED
├─ Phase 1.2: Animation Agent extraction (pending) ← ATTACHED
├─ Phase 1.3: Layout Agent extraction (pending) ← ATTACHED
├─ Phase 2: Reference package generation (pending)
└─ Phase 3: Cleanup and verify package (pending)
[Execute Phase 1.0] → Discover files (orchestrator executes this)
[Execute Phase 1.1-1.3] → Run 3 agents in parallel (orchestrator executes these)
└─ Outputs: design-tokens.json, style-guide.md, animation-tokens.json, layout-templates.json
[Phase 1 Complete] → TodoWrite: COLLAPSE Phase 1.0-1.3 into Phase 1 summary
[Phase 2 Invoke] → SlashCommand(/workflow:ui-design:reference-page-generator) ATTACHES 4 tasks
├─ Phase 0 (completed)
├─ Phase 1: Style extraction from source code (completed) ← COLLAPSED
├─ Phase 2.1: Validation and preparation (in_progress) ← ATTACHED
├─ Phase 2.2: Component pattern extraction (pending) ← ATTACHED
├─ Phase 2.3: Generate preview pages (pending) ← ATTACHED
├─ Phase 2.4: Generate metadata and documentation (pending) ← ATTACHED
└─ Phase 3: Cleanup and verify package (pending)
[Execute Phase 2.1] → Validate parameters (orchestrator executes this)
[Execute Phase 2.2] → Extract component patterns (orchestrator executes this)
[Execute Phase 2.3] → Generate preview pages (orchestrator executes this)
[Execute Phase 2.4] → Generate metadata and docs (orchestrator executes this)
└─ Outputs: component-patterns.json, preview.html, preview.css, metadata.json, README.md
[Phase 2 Complete] → TodoWrite: COLLAPSE Phase 2.1-2.4 into Phase 2 summary
├─ Phase 0 (completed)
├─ Phase 1: Style extraction from source code (completed)
├─ Phase 2: Reference package generation (completed) ← COLLAPSED
└─ Phase 3: Cleanup and verify package (in_progress)
[Execute Phase 3] → Orchestrator's own task (no attachment needed)
├─ Remove temporary workspace (.workflow/codify-temp-{timestamp}/)
├─ Verify package directory
├─ Extract component count
└─ Display completion summary
[Phase 3 Complete] → TodoWrite: Phase 3 → completed
├─ Phase 0 (completed)
├─ Phase 1 (completed)
├─ Phase 2 (completed)
└─ Phase 3 (completed)
```
---
## Error Handling
### Common Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Missing --source or --package-name | Required parameters not provided | Provide both flags |
| Invalid package name | Contains uppercase, special chars | Use lowercase, alphanumeric, hyphens only |
| import-from-code failed | Source path invalid or no files found | Verify source path, check glob patterns |
| reference-page-generator failed | Design run incomplete | Check import-from-code output, verify extraction files |
| Package verification failed | Output directory creation failed | Check file permissions |
### Error Recovery
- If Phase 2 fails: Cleanup temporary session and report error
- If Phase 3 fails: Keep design run for debugging, report error
- User can manually inspect `${design_run_path}` if needed
---
## Implementation Details
### Critical Rules
1. **No User Prompts Between Phases**: Never ask user questions or wait for input between phases
2. **Immediate Phase Transition**: After TodoWrite update, immediately execute next phase command
3. **Status-Driven Execution**: Check TodoList status after each phase
4. **Phase Completion Pattern**:
```
Phase N completes → Update TodoWrite (N=completed, N+1=in_progress) → Execute Phase N+1
```
### Parameter Pass-Through
Only essential parameters are passed to `import-from-code`:
- `--design-id` → temporary design run ID (auto-generated)
- `--source` → user-specified source directory
File discovery is fully automatic - no glob patterns needed.
### Output Directory Structure
```
.workflow/
├── reference_style/ # Default output directory
│ └── {package-name}/
│ ├── design-tokens.json
│ ├── style-guide.md
│ ├── component-patterns.json
│ ├── animation-tokens.json (optional)
│ ├── preview.html
│ ├── preview.css
│ ├── metadata.json
│ └── README.md
└── codify-temp-{timestamp}/ # Temporary workspace (cleaned up after completion)
├── style-extraction/
├── animation-extraction/
└── layout-extraction/
```
---
## Benefits
- **Simplified Interface**: Single path parameter with intelligent defaults
- **Auto-Generation**: Package names auto-generated from directory names
- **Automatic Discovery**: No need to specify file patterns - finds all style files automatically
- **Pure Orchestrator**: No direct agent execution, delegates to specialized commands
- **Auto-Continue**: Autonomous 4-phase execution without user interaction
- **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
- **Easy Maintenance**: Changes to sub-commands automatically apply
## Architecture
```
codify-style (orchestrator - simplified interface)
├─ Phase 0: Intelligent Validation
│ ├─ Parse positional path parameter
│ ├─ Auto-generate package name (if not provided)
│ ├─ 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
Design Principles:
✓ No task JSON created by this command
✓ 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
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)
---
@@ -18,35 +18,60 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
**Autonomous Flow** (⚠️ CONTINUOUS EXECUTION - DO NOT STOP):
1. User triggers: `/workflow:ui-design:explore-auto [params]`
2. Phase 0c: Target confirmation → User confirms → **IMMEDIATELY triggers Phase 1**
3. Phase 1 (style-extract) → **WAIT for completion** → Auto-continues
4. Phase 2.3 (animation-extract, optional)**WAIT for completion** → Auto-continues
5. Phase 2.5 (layout-extract) → **WAIT for completion** → Auto-continues
6. **Phase 3 (ui-assembly)****WAIT for completion** → Auto-continues
7. Phase 4 (design-update) → **WAIT for completion** → Auto-continues
8. Phase 5 (batch-plan, optional) → Reports completion
2. Phase 5: Target confirmation → User confirms → **IMMEDIATELY triggers Phase 7**
3. Phase 7 (style-extract) → **Attach tasks → Execute → Collapse** → Auto-continues to Phase 8
4. Phase 8 (animation-extract, conditional):
- **IF should_extract_animation**: **Attach tasks → Execute → Collapse** → Auto-continues to Phase 9
- **ELSE**: Skip (use code import) → Auto-continues to Phase 9
5. Phase 9 (layout-extract) → **Attach tasks → Execute → Collapse** → Auto-continues to Phase 10
6. **Phase 10 (ui-assembly)****Attach tasks → Execute → Collapse** → Auto-continues to Phase 11
7. Phase 11 (design-update) → **Attach tasks → Execute → Collapse** → Auto-continues to Phase 12 (if --batch-plan)
8. Phase 12 (batch-plan, optional) → Reports completion
**Phase Transition Mechanism**:
- **Phase 0c (User Interaction)**: User confirms targets → IMMEDIATELY triggers Phase 1
- **Phase 1-5 (Autonomous)**: `SlashCommand` is BLOCKING - execution pauses until completion
- Upon each phase completion: Automatically process output and execute next phase
- No additional user interaction after Phase 0c confirmation
- **Phase 5 (User Interaction)**: User confirms targets → IMMEDIATELY triggers Phase 7
- **Phase 7-12 (Autonomous)**: `SlashCommand` invocation **ATTACHES** tasks to current workflow
- **Task Execution**: Orchestrator **EXECUTES** these attached tasks itself
- **Task Collapse**: After tasks complete, collapse them into phase summary
- **Phase Transition**: Automatically execute next phase after collapsing
- No additional user interaction after Phase 5 confirmation
**Auto-Continue Mechanism**: TodoWrite tracks phase status. Upon each phase completion, you MUST immediately construct and execute the next phase command. No user intervention required. The workflow is NOT complete until reaching Phase 4 (or Phase 5 if --batch-plan).
**Auto-Continue Mechanism**: TodoWrite tracks phase status with dynamic task attachment/collapse. After executing all attached tasks, you MUST immediately collapse them, restore phase summary, and execute the next phase. No user intervention required. The workflow is NOT complete until reaching Phase 11 (or Phase 12 if --batch-plan).
**Task Attachment Model**: SlashCommand invocation is NOT delegation - it's task expansion. The orchestrator executes these attached tasks itself, not waiting for external completion.
**Target Type Detection**: Automatically inferred from prompt/targets, or explicitly set via `--target-type`.
## Core Rules
1. **Start Immediately**: TodoWrite initialization → Phase 1 execution
1. **Start Immediately**: TodoWrite initialization → Phase 7 execution
2. **No Preliminary Validation**: Sub-commands handle their own validation
3. **Parse & Pass**: Extract data from each output for next phase
4. **Default to All**: When selecting variants/prototypes, use ALL generated items
5. **Track Progress**: Update TodoWrite after each phase
6. **⚠️ CRITICAL: DO NOT STOP** - This is a continuous multi-phase workflow. After each SlashCommand completes, you MUST wait for completion, then immediately execute the next phase. Workflow is NOT complete until Phase 4 (or Phase 5 if --batch-plan).
5. **Track Progress**: Update TodoWrite dynamically with task attachment/collapse pattern
6. **⚠️ CRITICAL: Task Attachment Model** - SlashCommand invocation **ATTACHES** tasks to current workflow. Orchestrator **EXECUTES** these attached tasks itself, not waiting for external completion. This is NOT delegation - it's task expansion.
7. **⚠️ CRITICAL: DO NOT STOP** - This is a continuous multi-phase workflow. After executing all attached tasks, you MUST immediately collapse them and execute the next phase. Workflow is NOT complete until Phase 11 (or Phase 12 if --batch-plan).
## 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):
- `--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)
@@ -56,19 +81,17 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
- **Tablet**: 768×1024px - Hybrid touch/mouse layouts
- **Responsive**: 1920×1080px base with mobile-first breakpoints
- `--session <id>`: Workflow session ID (standalone mode if omitted)
- `--images "<glob>"`: Reference image paths (default: `design-refs/*`)
- `--prompt "<description>"`: Design style and target description
- `--style-variants <count>`: Style variants (default: inferred from prompt or 3, range: 1-5)
- `--layout-variants <count>`: Layout variants per style (default: inferred or 3, range: 1-5)
- `--batch-plan`: Auto-generate implementation tasks after design-update
**Legacy Parameters** (maintained for backward compatibility):
**Legacy Target Parameters** (maintained for backward compatibility):
- `--pages "<list>"`: Alias for `--targets` with `--target-type page`
- `--components "<list>"`: Alias for `--targets` with `--target-type component`
**Input Rules**:
- Must provide at least one: `--images` or `--prompt` or `--targets`
- Multiple parameters can be combined for guided analysis
- Must provide: `--input` OR (legacy: `--images`/`--prompt`) OR `--targets`
- `--input` can combine multiple input types
- If `--targets` not provided, intelligently inferred from prompt/session
**Supported Target Types**:
@@ -105,27 +128,63 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
**Integrated vs. Standalone**:
- `--session` flag determines session integration or standalone execution
## 6-Phase Execution
## 12-Phase Execution
### Phase 0a: Intelligent Path Detection & Source Selection
### Phase 1: Parameter Parsing & Input Detection
```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_base_path = null
has_visual_input = false
IF --prompt:
IF prompt_text:
# 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:
IF file_or_directory_exists(path):
code_files_detected = true
code_base_path = path
BREAK
IF --images:
IF images_input:
# Check if images parameter points to existing files
IF glob_matches_files(--images):
IF glob_matches_files(images_input):
has_visual_input = true
# Step 2: Determine design source strategy
@@ -143,12 +202,12 @@ ELSE:
STORE: design_source, code_base_path, has_visual_input
```
### Phase 0a-2: Intelligent Prompt Parsing
### Phase 2: Intelligent Prompt Parsing
```bash
# Parse variant counts from prompt or use explicit/default values
IF --prompt AND (NOT --style-variants OR NOT --layout-variants):
style_variants = regex_extract(prompt, r"(\d+)\s*style") OR --style-variants OR 3
layout_variants = regex_extract(prompt, r"(\d+)\s*layout") OR --layout-variants OR 3
IF prompt_text AND (NOT --style-variants OR NOT --layout-variants):
style_variants = regex_extract(prompt_text, r"(\d+)\s*style") OR --style-variants OR 3
layout_variants = regex_extract(prompt_text, r"(\d+)\s*layout") OR --layout-variants OR 3
ELSE:
style_variants = --style-variants OR 3
layout_variants = --layout-variants OR 3
@@ -159,7 +218,7 @@ VALIDATE: 1 <= style_variants <= 5, 1 <= layout_variants <= 5
interactive_mode = true # Always use interactive mode
```
### Phase 0a-2: Device Type Inference
### Phase 3: Device Type Inference
```bash
# Device type inference
device_type = "auto"
@@ -170,14 +229,14 @@ IF --device-type AND --device-type != "auto":
device_source = "explicit"
ELSE:
# Step 2: Prompt analysis
IF --prompt:
IF prompt_text:
device_keywords = {
"desktop": ["desktop", "web", "laptop", "widescreen", "large screen"],
"mobile": ["mobile", "phone", "smartphone", "ios", "android"],
"tablet": ["tablet", "ipad", "medium screen"],
"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:
device_type = detected_device
device_source = "prompt_inference"
@@ -204,10 +263,10 @@ STORE: device_type, device_source
- Prompt contains "responsive", "adaptive" → responsive
- Otherwise: Inferred from target type (components→desktop, pages→responsive)
### Phase 0b: Run Initialization & Directory Setup
### Phase 4: Run Initialization & Directory Setup
```bash
run_id = "run-$(date +%Y%m%d)-$RANDOM"
relative_base_path = --session ? ".workflow/WFS-{session}/design-${run_id}" : ".workflow/.design/design-${run_id}"
design_id = "design-run-$(date +%Y%m%d)-$RANDOM"
relative_base_path = --session ? ".workflow/WFS-{session}/${design_id}" : ".workflow/${design_id}"
# Create directory and convert to absolute path
Bash(mkdir -p "${relative_base_path}/style-extraction")
@@ -215,19 +274,25 @@ Bash(mkdir -p "${relative_base_path}/prototypes")
base_path=$(cd "${relative_base_path}" && pwd)
Write({base_path}/.run-metadata.json): {
"run_id": "${run_id}", "session_id": "${session_id}", "timestamp": "...",
"design_id": "${design_id}", "session_id": "${session_id}", "timestamp": "...",
"workflow": "ui-design:auto",
"architecture": "style-centric-batch-generation",
"parameters": { "style_variants": ${style_variants}, "layout_variants": ${layout_variants},
"targets": "${inferred_target_list}", "target_type": "${target_type}",
"prompt": "${prompt_text}", "images": "${images_pattern}",
"prompt": "${prompt_text}", "images": "${images_input}",
"input": "${--input}",
"device_type": "${device_type}", "device_source": "${device_source}" },
"status": "in_progress",
"performance_mode": "optimized"
}
# Initialize default flags for animation extraction logic
animation_complete = false # Default: always extract animations unless code import proves complete
needs_visual_supplement = false # Will be set to true in hybrid mode
skip_animation_extraction = false # User preference for code import scenario
```
### Phase 0c: Unified Target Inference with Intelligent Type Detection
### Phase 5: Unified Target Inference with Intelligent Type Detection
```bash
# Priority: --pages/--components (legacy) → --targets → --prompt analysis → synthesis → default
target_list = []; target_type = "auto"; target_source = "none"
@@ -240,8 +305,8 @@ ELSE IF --targets:
target_type = --target-type != "auto" ? --target-type : detect_target_type(target_list)
# Step 3: Prompt analysis (Claude internal analysis)
ELSE IF --prompt:
analysis_result = analyze_prompt("{prompt_text}") # Extract targets, types, purpose
ELSE IF prompt_text:
analysis_result = analyze_prompt(prompt_text) # Extract targets, types, purpose
target_list = analysis_result.targets
target_type = analysis_result.primary_type OR detect_target_type(target_list)
target_source = "prompt_analysis"
@@ -292,7 +357,7 @@ MATCH user_input:
STORE: inferred_target_list, target_type, target_inference_source
# ⚠️ CRITICAL: User confirmation complete, IMMEDIATELY initialize TodoWrite and execute Phase 1
# ⚠️ CRITICAL: User confirmation complete, IMMEDIATELY initialize TodoWrite and execute Phase 7
# This is the only user interaction point in the workflow
# After this point, all subsequent phases execute automatically without user intervention
```
@@ -309,12 +374,29 @@ detect_target_type(target_list):
RETURN "component" IF component_matches > page_matches ELSE "page"
```
### Phase 0d: Code Import & Completeness Assessment (Conditional)
### Phase 6: Code Import & Completeness Assessment (Conditional)
```bash
IF design_source IN ["code_only", "hybrid"]:
REPORT: "🔍 Phase 0d: Code Import ({design_source})"
command = "/workflow:ui-design:import-from-code --base-path \"{base_path}\" --source \"{code_base_path}\""
SlashCommand(command)
REPORT: "🔍 Phase 6: Code Import ({design_source})"
command = "/workflow:ui-design:import-from-code --design-id \"{design_id}\" --source \"{code_base_path}\""
TRY:
# SlashCommand invocation ATTACHES import-from-code's tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself:
# - Phase 0: Discover and categorize code files
# - Phase 1.1-1.3: Style/Animation/Layout Agent extraction
SlashCommand(command)
CATCH error:
WARN: "⚠️ Code import failed: {error}"
WARN: "Cleaning up incomplete import directories"
Bash(rm -rf "{base_path}/style-extraction" "{base_path}/animation-extraction" "{base_path}/layout-extraction" 2>/dev/null)
IF design_source == "code_only":
REPORT: "Cannot proceed with code-only mode after import failure"
EXIT 1
ELSE: # hybrid mode
WARN: "Continuing with visual-only mode"
design_source = "visual_only"
# Check file existence and assess completeness
style_exists = exists("{base_path}/style-extraction/style-1/design-tokens.json")
@@ -383,66 +465,123 @@ IF design_source IN ["code_only", "hybrid"]:
ELSE IF design_source == "hybrid":
needs_visual_supplement = true
STORE: needs_visual_supplement, style_complete, animation_complete, layout_complete
# Animation reuse confirmation (code import with complete animations)
IF design_source == "code_only" AND animation_complete:
REPORT: "✅ 检测到完整的动画系统(来自代码导入)"
REPORT: " Duration scales: {duration_count} | Easing functions: {easing_count}"
REPORT: ""
REPORT: "Options:"
REPORT: " • 'reuse' (默认) - 复用已有动画系统"
REPORT: " • 'regenerate' - 重新生成动画系统(交互式)"
REPORT: " • 'cancel' - 取消工作流"
user_response = WAIT_FOR_USER_INPUT()
MATCH user_response:
"reuse"skip_animation_extraction = true
"regenerate"skip_animation_extraction = false
"cancel" → EXIT 0
default → skip_animation_extraction = true # Default: reuse
STORE: needs_visual_supplement, style_complete, animation_complete, layout_complete, skip_animation_extraction
```
### Phase 1: Style Extraction
### Phase 7: Style Extraction
```bash
IF design_source == "visual_only" OR needs_visual_supplement:
REPORT: "🎨 Phase 1: Style Extraction (variants: {style_variants})"
command = "/workflow:ui-design:style-extract --base-path \"{base_path}\" " +
(--images ? "--images \"{images}\" " : "") +
(--prompt ? "--prompt \"{prompt}\" " : "") +
REPORT: "🎨 Phase 7: Style Extraction (variants: {style_variants})"
command = "/workflow:ui-design:style-extract --design-id \"{design_id}\" " +
(images_input ? "--images \"{images_input}\" " : "") +
(prompt_text ? "--prompt \"{prompt_text}\" " : "") +
"--variants {style_variants} --interactive"
# SlashCommand invocation ATTACHES style-extract's tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself
SlashCommand(command)
# After executing all attached tasks, collapse them into phase summary
ELSE:
REPORT: "✅ Phase 1: Style (Using Code Import)"
REPORT: "✅ Phase 7: Style (Using Code Import)"
```
### Phase 2.3: Animation Extraction
### Phase 8: Animation Extraction
```bash
IF design_source == "visual_only" OR NOT animation_complete:
REPORT: "🚀 Phase 2.3: Animation Extraction"
command = "/workflow:ui-design:animation-extract --base-path \"{base_path}\" --mode interactive"
# Determine if animation extraction is needed
should_extract_animation = false
IF (design_source == "visual_only" OR needs_visual_supplement):
# Pure visual input or hybrid mode requiring visual supplement
should_extract_animation = true
ELSE IF NOT animation_complete:
# Code import but animations are incomplete
should_extract_animation = true
ELSE IF design_source == "code_only" AND animation_complete AND NOT skip_animation_extraction:
# Code import with complete animations, but user chose to regenerate
should_extract_animation = true
IF should_extract_animation:
REPORT: "🚀 Phase 8: Animation Extraction"
# Build command with available inputs
command_parts = [f"/workflow:ui-design:animation-extract --design-id \"{design_id}\""]
IF images_input:
command_parts.append(f"--images \"{images_input}\"")
IF prompt_text:
command_parts.append(f"--prompt \"{prompt_text}\"")
command_parts.append("--interactive")
command = " ".join(command_parts)
# SlashCommand invocation ATTACHES animation-extract's tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself
SlashCommand(command)
# After executing all attached tasks, collapse them into phase summary
ELSE:
REPORT: "✅ Phase 2.3: Animation (Using Code Import)"
REPORT: "✅ Phase 8: Animation (Using Code Import)"
# Output: animation-tokens.json + animation-guide.md
# SlashCommand blocks until phase complete
# Upon completion, IMMEDIATELY execute Phase 2.5 (auto-continue)
# When phase finishes, IMMEDIATELY execute Phase 9 (auto-continue)
```
### Phase 2.5: Layout Extraction
### Phase 9: Layout Extraction
```bash
targets_string = ",".join(inferred_target_list)
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})"
command = "/workflow:ui-design:layout-extract --base-path \"{base_path}\" " +
(--images ? "--images \"{images}\" " : "") +
(--prompt ? "--prompt \"{prompt}\" " : "") +
REPORT: "🚀 Phase 9: Layout Extraction ({targets_string}, variants: {layout_variants}, device: {device_type})"
command = "/workflow:ui-design:layout-extract --design-id \"{design_id}\" " +
(images_input ? "--images \"{images_input}\" " : "") +
(prompt_text ? "--prompt \"{prompt_text}\" " : "") +
"--targets \"{targets_string}\" --variants {layout_variants} --device-type \"{device_type}\" --interactive"
# SlashCommand invocation ATTACHES layout-extract's tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself
SlashCommand(command)
# After executing all attached tasks, collapse them into phase summary
ELSE:
REPORT: "✅ Phase 2.5: Layout (Using Code Import)"
REPORT: "✅ Phase 9: Layout (Using Code Import)"
```
### Phase 3: UI Assembly
### Phase 10: UI Assembly
```bash
command = "/workflow:ui-design:generate --base-path \"{base_path}\""
command = "/workflow:ui-design:generate --design-id \"{design_id}\"" + (--session ? " --session {session_id}" : "")
total = style_variants × layout_variants × len(inferred_target_list)
REPORT: "🚀 Phase 3: UI Assembly | Matrix: {s}×{l}×{n} = {total} prototypes"
REPORT: "🚀 Phase 10: UI Assembly | Matrix: {s}×{l}×{n} = {total} prototypes"
REPORT: " → Pure assembly: Combining layout templates + design tokens"
REPORT: " → Device: {device_type} (from layout templates)"
REPORT: " → Assembly tasks: {total} combinations"
# SlashCommand invocation ATTACHES generate's tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself
SlashCommand(command)
# SlashCommand blocks until phase complete
# Upon completion, IMMEDIATELY execute Phase 4 (auto-continue)
# After executing all attached tasks, collapse them into phase summary
# When phase finishes, IMMEDIATELY execute Phase 11 (auto-continue)
# Output:
# - {target}-style-{s}-layout-{l}.html (assembled prototypes)
# - {target}-style-{s}-layout-{l}.css
@@ -450,101 +589,60 @@ SlashCommand(command)
# - PREVIEW.md (usage instructions)
```
### Phase 4: Design System Integration
### Phase 11: Design System Integration
```bash
command = "/workflow:ui-design:update" + (--session ? " --session {session_id}" : "")
# SlashCommand invocation ATTACHES update's tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself
SlashCommand(command)
# SlashCommand blocks until phase complete
# Upon completion:
# - If --batch-plan flag present: IMMEDIATELY execute Phase 5 (auto-continue)
# After executing all attached tasks, collapse them into phase summary
# When phase finishes:
# - If --batch-plan flag present: IMMEDIATELY execute Phase 12 (auto-continue)
# - If no --batch-plan: Workflow complete, display final report
```
### Phase 5: Batch Task Generation (Optional)
### Phase 12: Batch Task Generation (Optional)
```bash
IF --batch-plan:
FOR target IN inferred_target_list:
task_desc = "Implement {target} {target_type} based on design system"
# SlashCommand invocation ATTACHES plan's tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself
SlashCommand("/workflow:plan --agent \"{task_desc}\"")
```
## TodoWrite Pattern
```javascript
// Initialize IMMEDIATELY after Phase 0c user confirmation to track multi-phase execution
// Initialize IMMEDIATELY after Phase 5 user confirmation to track multi-phase execution (5 orchestrator-level tasks)
TodoWrite({todos: [
{"content": "Execute style extraction", "status": "in_progress", "activeForm": "Executing..."},
{"content": "Execute layout extraction", "status": "pending", "activeForm": "Executing..."},
{"content": "Execute UI assembly", "status": "pending", "activeForm": "Executing..."},
{"content": "Execute design integration", "status": "pending", "activeForm": "Executing..."}
{"content": "Execute style extraction", "status": "in_progress", "activeForm": "Executing style extraction"},
{"content": "Execute animation extraction", "status": "pending", "activeForm": "Executing animation extraction"},
{"content": "Execute layout extraction", "status": "pending", "activeForm": "Executing layout extraction"},
{"content": "Execute UI assembly", "status": "pending", "activeForm": "Executing UI assembly"},
{"content": "Execute design integration", "status": "pending", "activeForm": "Executing design integration"}
]})
// ⚠️ CRITICAL: After EACH SlashCommand completion (Phase 1-5), you MUST:
// 1. SlashCommand blocks and returns when phase is complete
// 2. Update current phase: status → "completed"
// 3. Update next phase: status → "in_progress"
// 4. IMMEDIATELY execute next phase SlashCommand (auto-continue)
// This ensures continuous workflow tracking and prevents premature stopping
```
## Key Features
- **🚀 Performance**: Style-centric batch generation with S agent calls
- **🎨 Style-Aware**: HTML structure adapts to design_attributes
- **✅ Perfect Consistency**: Each style by single agent
- **📦 Autonomous**: No user intervention required between phases
- **🧠 Intelligent**: Parses natural language, infers targets/types
- **🔄 Reproducible**: Deterministic flow with isolated run directories
- **🎯 Flexible**: Supports pages, components, or mixed targets
## Examples
### 1. Page Mode (Prompt Inference)
```bash
/workflow:ui-design:explore-auto --prompt "Modern blog: home, article, author"
# Result: 27 prototypes (3×3×3) - responsive layouts (default)
```
### 2. Mobile-First Design
```bash
/workflow:ui-design:explore-auto --prompt "Mobile shopping app: home, product, cart" --device-type mobile
# Result: 27 prototypes (3×3×3) - mobile layouts (375×812px)
```
### 3. Desktop Application
```bash
/workflow:ui-design:explore-auto --targets "dashboard,analytics,settings" --device-type desktop --style-variants 2 --layout-variants 2
# Result: 12 prototypes (2×2×3) - desktop layouts (1920×1080px)
```
### 4. Tablet Interface
```bash
/workflow:ui-design:explore-auto --prompt "Educational app for tablets" --device-type tablet --targets "courses,lessons,profile"
# Result: 27 prototypes (3×3×3) - tablet layouts (768×1024px)
```
### 5. Custom Matrix with Session
```bash
/workflow:ui-design:explore-auto --session WFS-ecommerce --images "refs/*.png" --style-variants 2 --layout-variants 2
# Result: 2×2×N prototypes - device type inferred from session
```
### 6. Component Mode (Desktop)
```bash
/workflow:ui-design:explore-auto --targets "navbar,hero" --target-type "component" --device-type desktop --style-variants 3 --layout-variants 2
# Result: 12 prototypes (3×2×2) - desktop components
```
### 7. Intelligent Parsing + Batch Planning
```bash
/workflow:ui-design:explore-auto --prompt "Create 4 styles with 2 layouts for mobile dashboard and settings" --batch-plan
# Result: 16 prototypes (4×2×2) + auto-generated tasks - mobile-optimized (inferred from prompt)
```
### 8. Large Scale Responsive
```bash
/workflow:ui-design:explore-auto --targets "home,dashboard,settings,profile" --device-type responsive --style-variants 3 --layout-variants 3
# Result: 36 prototypes (3×3×4) - responsive layouts
// ⚠️ CRITICAL: Dynamic TodoWrite task attachment strategy:
//
// **Key Concept**: SlashCommand invocation ATTACHES tasks to current workflow.
// Orchestrator EXECUTES these attached tasks itself, not waiting for external completion.
//
// Phase 7-12 SlashCommand Invocation Pattern:
// 1. SlashCommand invocation ATTACHES sub-command tasks to TodoWrite
// 2. TodoWrite expands to include attached tasks
// 3. Orchestrator EXECUTES attached tasks sequentially
// 4. After all attached tasks complete, COLLAPSE them into phase summary
// 5. Update next phase to in_progress
// 6. IMMEDIATELY execute next phase SlashCommand (auto-continue)
//
// Benefits:
// ✓ Real-time visibility into sub-command task progress
// ✓ Clean orchestrator-level summary after each phase
// ✓ Clear mental model: SlashCommand = attach tasks, not delegate work
// ✓ Dynamic attachment/collapse maintains clarity
```
## Completion Output
@@ -555,16 +653,16 @@ Architecture: Style-Centric Batch Generation
Run ID: {run_id} | Session: {session_id or "standalone"}
Type: {icon} {target_type} | Device: {device_type} | Matrix: {s}×{l}×{n} = {total} prototypes
Phase 1: {s} complete design systems (style-extract with multi-select)
Phase 2: {n×l} layout templates (layout-extract with multi-select)
Phase 7: {s} complete design systems (style-extract with multi-select)
Phase 9: {n×l} layout templates (layout-extract with multi-select)
- Device: {device_type} layouts
- {n} targets × {l} layout variants = {n×l} structural templates
- User-selected concepts generated in parallel
Phase 3: UI Assembly (generate)
Phase 10: UI Assembly (generate)
- Pure assembly: layout templates + design tokens
- {s}×{l}×{n} = {total} final prototypes
Phase 4: Brainstorming artifacts updated
[Phase 5: {n} implementation tasks created] # if --batch-plan
Phase 11: Brainstorming artifacts updated
[Phase 12: {n} implementation tasks created] # if --batch-plan
Assembly Process:
✅ Separation of Concerns: Layout (structure) + Style (tokens) kept separate
@@ -581,9 +679,11 @@ Design Quality:
📂 {base_path}/
├── .intermediates/ (Intermediate analysis files)
│ ├── style-analysis/ (computed-styles.json, design-space-analysis.json)
── layout-analysis/ (analysis-options.json, user-selection.json, dom-structure-*.json)
│ ├── style-analysis/ (analysis-options.json with embedded user_selection, computed-styles.json if URL mode)
── animation-analysis/ (analysis-options.json with embedded user_selection, animations-*.json if URL mode)
│ └── layout-analysis/ (analysis-options.json with embedded user_selection, dom-structure-*.json if URL mode)
├── style-extraction/ ({s} complete design systems)
├── animation-extraction/ (animation-tokens.json, animation-guide.md)
├── layout-extraction/ ({n×l} layout template files: layout-{target}-{variant}.json)
├── prototypes/ ({total} assembled prototypes)
└── .run-metadata.json (includes device type)

View File

@@ -1,7 +1,7 @@
---
name: explore-layers
description: Interactive deep UI capture with depth-controlled layer exploration using MCP puppeteer
argument-hint: --url <url> --depth <1-5> [--session id] [--base-path path]
argument-hint: --url <url> --depth <1-5> [--design-id <id>] [--session <id>]
allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*), mcp__chrome-devtools__*
---
@@ -38,19 +38,37 @@ IF depth NOT IN [1, 2, 3, 4, 5]:
### Step 2: Determine Base Path
```bash
relative_path=$(if [ -n "$BASE_PATH" ]; then
echo "$BASE_PATH"
# Priority: --design-id > --session > create new
if [ -n "$DESIGN_ID" ]; then
# Exact match by design ID
relative_path=$(find .workflow -name "${DESIGN_ID}" -type d -print -quit)
if [ -z "$relative_path" ]; then
echo "ERROR: Design run not found: $DESIGN_ID"
echo "HINT: Run '/workflow:ui-design:list' to see available design runs"
exit 1
fi
elif [ -n "$SESSION_ID" ]; then
find .workflow/WFS-$SESSION_ID/design-* -type d -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2 || \
echo ".workflow/WFS-$SESSION_ID/design-run-$(date +%Y%m%d)-$RANDOM"
# Find latest in session or create new
relative_path=$(find .workflow/WFS-$SESSION_ID -name "design-run-*" -type d -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2)
if [ -z "$relative_path" ]; then
design_id="design-run-$(date +%Y%m%d)-$RANDOM"
relative_path=".workflow/WFS-$SESSION_ID/${design_id}"
fi
else
echo ".workflow/.design/design-run-$(date +%Y%m%d)-$RANDOM"
fi)
# Create new standalone design run
design_id="design-run-$(date +%Y%m%d)-$RANDOM"
relative_path=".workflow/${design_id}"
fi
# Create directory structure and convert to absolute path
bash(mkdir -p "$relative_path")
base_path=$(cd "$relative_path" && pwd)
# Extract and display design_id
design_id=$(basename "$base_path")
echo "✓ Design ID: $design_id"
echo "✓ Base path: $base_path"
# Create depth directories
bash(for i in $(seq 1 $depth); do mkdir -p "$base_path"/screenshots/depth-$i; done)
```

View File

@@ -1,7 +1,7 @@
---
name: generate
description: Assemble UI prototypes by combining layout templates with design tokens, pure assembler without new content generation
argument-hint: [--base-path <path>] [--session <id>]
description: Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation
argument-hint: [--design-id <id>] [--session <id>]
allowed-tools: TodoWrite(*), Read(*), Write(*), Task(ui-design-agent), Bash(*)
---
@@ -25,14 +25,27 @@ Pure assembler that combines pre-extracted layout templates with design tokens t
### Step 1: Resolve Base Path & Parse Configuration
```bash
# Determine working directory (relative path - finds latest)
relative_path=$(find .workflow -type d -name "design-run-*" -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2)
# Determine base path with priority: --design-id > --session > auto-detect
if [ -n "$DESIGN_ID" ]; then
# Exact match by design ID
relative_path=$(find .workflow -name "${DESIGN_ID}" -type d -print -quit)
elif [ -n "$SESSION_ID" ]; then
# Latest in session
relative_path=$(find .workflow/WFS-$SESSION_ID -name "design-run-*" -type d -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2)
else
# Latest globally
relative_path=$(find .workflow -name "design-run-*" -type d -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2)
fi
# Validate and convert to absolute path
if [ -z "$relative_path" ] || [ ! -d "$relative_path" ]; then
echo "❌ ERROR: Design run not found"
echo "💡 HINT: Run '/workflow:ui-design:list' to see available design runs"
exit 1
fi
# Convert to absolute path
base_path=$(cd "$relative_path" && pwd)
# Verify absolute path
bash(test -d "$base_path" && echo "✓ Base path: $base_path" || echo "✗ Path not found")
bash(echo "✓ Base path: $base_path")
# Get style count
bash(ls "$base_path"/style-extraction/style-* -d | wc -l)
@@ -86,30 +99,97 @@ ELSE:
## Phase 2: Assembly (Agent)
**Executor**: `Task(ui-design-agent)` × `T × S × L` tasks (can be batched)
**Executor**: `Task(ui-design-agent)` grouped by `target × style` (max 10 layouts per agent, max 6 concurrent agents)
### Step 1: Launch Assembly Tasks
```bash
bash(mkdir -p {base_path}/prototypes)
**⚠️ Core Principle**: **Each agent processes ONLY ONE style** (but can process multiple layouts for that style)
### Agent Grouping Strategy
**Grouping Rules**:
1. **Style Isolation**: Each agent processes ONLY ONE style (never mixed)
2. **Balanced Distribution**: Layouts evenly split (e.g., 12→6+6, not 10+2)
3. **Target Separation**: Different targets use different agents
**Distribution Formula**:
```
agents_needed = ceil(layout_count / MAX_LAYOUTS_PER_AGENT)
base_count = floor(layout_count / agents_needed)
remainder = layout_count % agents_needed
# First 'remainder' agents get (base_count + 1), others get base_count
```
For each `target × style_id × layout_id`:
**Examples** (MAX=10):
| Scenario | Result | Explanation |
|----------|--------|-------------|
| 3 styles × 3 layouts | 3 agents | Each style: 1 agent (3 layouts) |
| 3 styles × 12 layouts | 6 agents | Each style: 2 agents (6+6 layouts) |
| 2 styles × 5 layouts × 2 targets | 4 agents | Each (target, style): 1 agent (5 layouts) |
### Step 1: Calculate Agent Grouping Plan
```bash
bash(mkdir -p {base_path}/prototypes)
MAX_LAYOUTS_PER_AGENT = 10
MAX_PARALLEL = 6
agent_groups = []
FOR each target in targets:
FOR each style_id in [1..S]:
layouts_for_this_target_style = filter layouts by current target
layout_count = len(layouts_for_this_target_style)
# Balanced distribution (e.g., 12 layouts → 6+6)
agents_needed = ceil(layout_count / MAX_LAYOUTS_PER_AGENT)
base_count = floor(layout_count / agents_needed)
remainder = layout_count % agents_needed
layout_chunks = []
start_idx = 0
FOR i in range(agents_needed):
chunk_size = base_count + 1 if i < remainder else base_count
layout_chunks.append(layouts[start_idx : start_idx + chunk_size])
start_idx += chunk_size
FOR each chunk in layout_chunks:
agent_groups.append({
target: target, # Single target
style_id: style_id, # Single style
layout_ids: chunk # Balanced layouts (≤10)
})
total_agents = len(agent_groups)
total_batches = ceil(total_agents / MAX_PARALLEL)
TodoWrite({todos: [
{content: "Setup and validation", status: "completed", activeForm: "Loading design systems"},
{content: "Batch 1/{total_batches}: Assemble up to 6 agent groups", status: "in_progress", activeForm: "Assembling batch 1"},
{content: "Batch 2/{total_batches}: Assemble up to 6 agent groups", status: "pending", activeForm: "Assembling batch 2"},
... (continue for all batches)
]})
```
### Step 2: Launch Batched Assembly Tasks
For each batch (up to 6 parallel agents per batch):
For each agent group `{target, style_id, layout_ids[]}` in current batch:
```javascript
Task(ui-design-agent): `
[LAYOUT_STYLE_ASSEMBLY]
🎯 Assembly task: {target} × Style-{style_id} × Layout-{layout_id}
Combine: Pre-extracted layout structure + design tokens → Final HTML/CSS
🎯 {target} × Style-{style_id} × Layouts-{layout_ids}
⚠️ CONSTRAINT: Use ONLY style-{style_id}/design-tokens.json (never mix styles)
TARGET: {target} | STYLE: {style_id} | LAYOUT: {layout_id}
TARGET: {target} | STYLE: {style_id} | LAYOUTS: {layout_ids} (max 10)
BASE_PATH: {base_path}
## Inputs (READ ONLY - NO DESIGN DECISIONS)
1. Layout Template:
Read("{base_path}/layout-extraction/layout-{target}-{layout_id}.json")
This file contains the specific layout template for this target and variant.
Extract: dom_structure, css_layout_rules, device_type, source_image_path (from template field)
1. Layout Templates (LOOP THROUGH):
FOR each layout_id in layout_ids:
Read("{base_path}/layout-extraction/layout-{target}-{layout_id}.json")
This file contains the specific layout template for this target and variant.
Extract: dom_structure, css_layout_rules, device_type, source_image_path (from template field)
2. Design Tokens:
2. Design Tokens (SHARED - READ ONCE):
Read("{base_path}/style-extraction/style-{style_id}/design-tokens.json")
Extract: ALL token values including:
* colors, typography (with combinations), spacing, opacity
@@ -133,61 +213,70 @@ Task(ui-design-agent): `
ELSE:
Use generic placeholder content
## Assembly Process
1. Build HTML: {base_path}/prototypes/{target}-style-{style_id}-layout-{layout_id}.html
- Recursively build from template.dom_structure
- Add: <!DOCTYPE html>, <head>, <meta viewport>
- CSS link: <link href="{target}-style-{style_id}-layout-{layout_id}.css">
- Inject placeholder content:
* Default: Use Lorem ipsum, generic sample data
* If reference image available: Generate more contextually appropriate placeholders
(e.g., realistic headings, meaningful text snippets that match the visual context)
- Preserve all attributes from dom_structure
## Assembly Process (LOOP FOR EACH LAYOUT)
FOR each layout_id in layout_ids:
2. Build CSS: {base_path}/prototypes/{target}-style-{style_id}-layout-{layout_id}.css
- Start with template.css_layout_rules
- Replace ALL var(--*) with actual token values from design-tokens.json
Example: var(--spacing-4) → 1rem (from tokens.spacing.4)
Example: var(--breakpoint-md) → 768px (from tokens.breakpoints.md)
Example: var(--opacity-80) → 0.8 (from tokens.opacity.80)
- Add visual styling using design tokens:
* Colors: tokens.colors.*
* Typography: tokens.typography.* (including combinations)
* Opacity: tokens.opacity.*
* Shadows: tokens.shadows.*
* Border radius: tokens.border_radius.*
- IF tokens.component_styles exists: Add component style classes
* Generate classes for button variants (.btn-primary, .btn-secondary)
* Generate classes for card variants (.card-default, .card-interactive)
* Generate classes for input variants (.input-default, .input-focus, .input-error)
* Use var() references that resolve to actual token values
- IF tokens.typography.combinations exists: Add typography preset classes
* Generate classes for typography presets (.text-heading-primary, .text-body-regular, .text-caption)
* Use var() references for family, size, weight, line-height, letter-spacing
- IF has_animations == true: Inject animation tokens
* Add CSS Custom Properties for animations at :root level:
--duration-instant, --duration-fast, --duration-normal, etc.
--easing-linear, --easing-ease-out, etc.
* Add @keyframes rules from animation_tokens.keyframes
* Add interaction classes (.button-hover, .card-hover) from animation_tokens.interactions
* Add utility classes (.transition-color, .transition-transform) from animation_tokens.transitions
* Include prefers-reduced-motion media query for accessibility
- Device-optimized for template.device_type
1. Build HTML: {base_path}/prototypes/{target}-style-{style_id}-layout-{layout_id}.html
- Recursively build from template.dom_structure
- Add: <!DOCTYPE html>, <head>, <meta viewport>
- CSS link: <link href="{target}-style-{style_id}-layout-{layout_id}.css">
- Inject placeholder content:
* Default: Use Lorem ipsum, generic sample data
* If reference image available: Generate more contextually appropriate placeholders
(e.g., realistic headings, meaningful text snippets that match the visual context)
- Preserve all attributes from dom_structure
2. Build CSS: {base_path}/prototypes/{target}-style-{style_id}-layout-{layout_id}.css
- Start with template.css_layout_rules
- Replace ALL var(--*) with actual token values from design-tokens.json
Example: var(--spacing-4) → 1rem (from tokens.spacing.4)
Example: var(--breakpoint-md) → 768px (from tokens.breakpoints.md)
Example: var(--opacity-80) → 0.8 (from tokens.opacity.80)
- Add visual styling using design tokens:
* Colors: tokens.colors.*
* Typography: tokens.typography.* (including combinations)
* Opacity: tokens.opacity.*
* Shadows: tokens.shadows.*
* Border radius: tokens.border_radius.*
- IF tokens.component_styles exists: Add component style classes
* Generate classes for button variants (.btn-primary, .btn-secondary)
* Generate classes for card variants (.card-default, .card-interactive)
* Generate classes for input variants (.input-default, .input-focus, .input-error)
* Use var() references that resolve to actual token values
- IF tokens.typography.combinations exists: Add typography preset classes
* Generate classes for typography presets (.text-heading-primary, .text-body-regular, .text-caption)
* Use var() references for family, size, weight, line-height, letter-spacing
- IF has_animations == true: Inject animation tokens (ONCE, shared across layouts)
* Add CSS Custom Properties for animations at :root level:
--duration-instant, --duration-fast, --duration-normal, etc.
--easing-linear, --easing-ease-out, etc.
* Add @keyframes rules from animation_tokens.keyframes
* Add interaction classes (.button-hover, .card-hover) from animation_tokens.interactions
* Add utility classes (.transition-color, .transition-transform) from animation_tokens.transitions
* Include prefers-reduced-motion media query for accessibility
- Device-optimized for template.device_type
3. Write files IMMEDIATELY after each layout completes
## Assembly Rules
- ✅ Pure assembly: Combine existing structure + existing style
- ❌ NO layout design decisions (structure pre-defined)
- ❌ NO style design decisions (tokens pre-defined)
- ✅ Pure assembly: Combine pre-extracted structure + tokens
- ❌ NO design decisions (layout/style pre-defined)
- ✅ Read tokens ONCE, apply to all layouts in this batch
- ✅ Replace var() with actual values
- ✅ Add placeholder content only
- Write files IMMEDIATELY
- CSS filename MUST match HTML <link href="...">
- ✅ CSS filename MUST match HTML <link href="...">
## Output
- Files: {len(layout_ids) × 2} (HTML + CSS pairs)
- Each layout generates 2 files independently
`
# After each batch completes
TodoWrite: Mark current batch completed, next batch in_progress
```
### Step 2: Verify Generated Files
### Step 3: Verify Generated Files
```bash
# Count expected vs found
# Count expected vs found (should equal S × L × T)
bash(ls {base_path}/prototypes/{target}-style-*-layout-*.html | wc -l)
# Validate samples
@@ -195,7 +284,7 @@ Read({base_path}/prototypes/{target}-style-{style_id}-layout-{layout_id}.html)
# Check: <!DOCTYPE html>, correct CSS href, sufficient CSS length
```
**Output**: `S × L × T × 2` files verified
**Output**: `total_files = S × L × T × 2` files verified (HTML + CSS pairs)
## Phase 3: Generate Preview Files
@@ -222,10 +311,10 @@ bash(ls {base_path}/prototypes/compare.html {base_path}/prototypes/index.html {b
```javascript
TodoWrite({todos: [
{content: "Setup and validation", status: "completed", activeForm: "Loading design systems"},
{content: "Load layout templates", status: "completed", activeForm: "Reading layout templates"},
{content: "Assembly (agent)", status: "completed", activeForm: "Assembling prototypes"},
{content: "Verify files", status: "completed", activeForm: "Validating output"},
{content: "Generate previews", status: "completed", activeForm: "Creating preview files"}
{content: "Batch 1/{total_batches}: Assemble 6 tasks", status: "completed", activeForm: "Assembling batch 1"},
{content: "Batch 2/{total_batches}: Assemble 6 tasks", status: "completed", activeForm: "Assembling batch 2"},
... (all batches completed)
{content: "Verify files & generate previews", status: "completed", activeForm: "Creating previews"}
]});
```
@@ -240,17 +329,24 @@ Configuration:
- Targets: {targets}
- Total Prototypes: {S × L × T}
- Image Reference: Auto-detected (uses source images when available in layout templates)
- Animation Support: {has_animations ? 'Enabled (animation-tokens.json loaded)' : 'Not available'}
Assembly Process:
- Pure assembly: Combined pre-extracted layouts + design tokens
- No design decisions: All structure and style pre-defined
- Assembly tasks: T×S×L = {T}×{S}×{L} = {T×S×L} combinations
- Agent grouping: target × style (max 10 layouts per agent)
- Balanced distribution: Layouts evenly split (e.g., 12 → 6+6, not 10+2)
Batch Execution:
- Total agents: {total_agents} (each processes ONE style only)
- Batches: {total_batches} (max 6 agents parallel)
- Token efficiency: Read once per agent, apply to all layouts
Quality:
- Structure: From layout-extract (DOM, CSS layout rules)
- Style: From style-extract (design tokens)
- CSS: Token values directly applied (var() replaced)
- Device-optimized: Layouts match device_type from templates
- Animations: {has_animations ? 'CSS custom properties and @keyframes injected' : 'Static styles only'}
Generated Files:
{base_path}/prototypes/
@@ -362,10 +458,9 @@ ERROR: Script permission denied
## Key Features
- **Pure Assembly**: No design decisions, only combination
- **Separation of Concerns**: Layout (structure) + Style (tokens) kept separate until final assembly
- **Token Resolution**: var() placeholders replaced with actual values
- **Pre-validated**: Inputs already validated by extract/consolidate
- **Efficient**: Simple assembly vs complex generation
- **Token Resolution**: var() → actual values
- **Efficient Grouping**: target × style (max 10 layouts/agent, balanced split)
- **Style Isolation**: Each agent processes ONE style only
- **Production-Ready**: Semantic, accessible, token-driven
## Integration

View File

@@ -1,7 +1,7 @@
---
name: imitate-auto
description: High-speed multi-page UI replication with batch screenshot capture and design token extraction
argument-hint: --url-map "<map>" [--capture-mode <batch|deep>] [--depth <1-5>] [--session <id>] [--prompt "<desc>"]
description: UI design workflow with direct code/image input for design token extraction and prototype generation
argument-hint: "[--input "<value>"] [--session <id>]"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*)
---
@@ -9,79 +9,85 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*)
## Overview & Execution Model
**Fully autonomous replication orchestrator**: Efficiently replicate multiple web pages through sequential execution from screenshot capture to design integration.
**Fully autonomous design orchestrator**: Efficiently create UI prototypes through sequential execution from design token extraction to system integration.
**Dual Capture Strategy**: Supports two capture modes for different use cases:
- **Batch Mode** (default): Fast multi-URL screenshot capture via `/workflow:ui-design:capture`
- **Deep Mode**: Interactive layer exploration for single URL via `/workflow:ui-design:explore-layers`
**Direct Input Strategy**: Accepts local code files and images:
- **Code Files**: Detect file paths in `--prompt` parameter
- **Images**: Reference images via `--images` glob pattern
- **Hybrid**: Combine both code and visual inputs
**Autonomous Flow** (⚠️ CONTINUOUS EXECUTION - DO NOT STOP):
1. User triggers: `/workflow:ui-design:imitate-auto --url-map "..."`
2. Phase 0: Initialize and parse parameters
3. Phase 1: Screenshot capture (batch or deep mode) → **WAIT for completion** → Auto-continues
4. Phase 2: Style extraction (complete design systems) → **WAIT for completion** → Auto-continues
5. Phase 2.3: Animation extraction (CSS auto mode) → **WAIT for completion** → Auto-continues
6. Phase 2.5: Layout extraction (structure templates) → **WAIT for completion** → Auto-continues
7. Phase 3: Batch UI assembly → **WAIT for completion** → Auto-continues
8. Phase 4: Design system integration → Reports completion
1. User triggers: `/workflow:ui-design:imitate-auto [--input "..."]`
2. Phase 0: Initialize and detect input sources
3. Phase 2: Style extraction → **Attach tasks → Execute → Collapse** → Auto-continues
4. Phase 2.3: Animation extraction → **Attach tasks → Execute → Collapse** → Auto-continues
5. Phase 2.5: Layout extraction **Attach tasks → Execute → Collapse** → Auto-continues
6. Phase 3: Batch UI assembly → **Attach tasks → Execute → Collapse** → Auto-continues
7. Phase 4: Design system integration → **Execute orchestrator task** → Reports completion
**Phase Transition Mechanism**:
- `SlashCommand` is BLOCKING - execution pauses until completion
- Upon each phase completion: Automatically process output and execute next phase
- **Task Attachment**: `SlashCommand` invocation **ATTACHES** tasks to current workflow
- **Task Execution**: Orchestrator **EXECUTES** these attached tasks itself
- **Task Collapse**: After tasks complete, collapse them into phase summary
- **Phase Transition**: Automatically execute next phase after collapsing
- No user interaction required after initial parameter parsing
**Auto-Continue Mechanism**: TodoWrite tracks phase status. Upon each phase completion, you MUST immediately construct and execute the next phase command. No user intervention required. The workflow is NOT complete until reaching Phase 5.
**Auto-Continue Mechanism**: TodoWrite tracks phase status with dynamic task attachment/collapse. After executing all attached tasks, you MUST immediately collapse them, restore phase summary, and execute the next phase. No user intervention required. The workflow is NOT complete until reaching Phase 4.
**Task Attachment Model**: SlashCommand invocation is NOT delegation - it's task expansion. The orchestrator executes these attached tasks itself, not waiting for external completion.
## Core Rules
1. **Start Immediately**: TodoWrite initialization → Phase 1 execution
1. **Start Immediately**: TodoWrite initialization → Phase 2 execution
2. **No Preliminary Validation**: Sub-commands handle their own validation
3. **Parse & Pass**: Extract data from each output for next phase
4. **Track Progress**: Update TodoWrite after each phase
5. **⚠️ CRITICAL: DO NOT STOP** - This is a continuous multi-phase workflow. After each SlashCommand completes, you MUST wait for completion, then immediately execute the next phase. Workflow is NOT complete until Phase 5.
4. **Track Progress**: Update TodoWrite dynamically with task attachment/collapse pattern
5. **⚠️ CRITICAL: Task Attachment Model** - SlashCommand invocation **ATTACHES** tasks to current workflow. Orchestrator **EXECUTES** these attached tasks itself, not waiting for external completion. This is NOT delegation - it's task expansion.
6. **⚠️ CRITICAL: DO NOT STOP** - This is a continuous multi-phase workflow. After executing all attached tasks, you MUST immediately collapse them and execute the next phase. Workflow is NOT complete until Phase 4.
## Parameter Requirements
**Required Parameters**:
- `--url-map "<map>"`: Target page mapping
- Format: `"target1:url1, target2:url2, ..."`
- Example: `"home:https://linear.app, pricing:https://linear.app/pricing"`
- First target serves as primary style source
**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): `"Focus on dark mode"`, `"Emphasize minimalist design"`
- **Combination**: `"design-refs/* modern dashboard style"` (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 "<desc>"`: Design description (shows deprecation warning)
**Optional Parameters**:
- `--capture-mode <batch|deep>` (Optional, default: batch): Screenshot capture strategy
- `batch` (default): Multi-URL fast batch capture via `/workflow:ui-design:capture`
- `deep`: Single-URL interactive depth exploration via `/workflow:ui-design:explore-layers`
- **Note**: `deep` mode only uses first URL from url-map
- `--depth <1-5>` (Optional, default: 3): Capture depth for deep mode
- `1`: Page level (full-page screenshot)
- `2`: Element level (+ key components)
- `3`: Interaction level (+ modals, dropdowns)
- `4`: Embedded level (+ iframes)
- `5`: Shadow DOM (+ web components)
- **Only applies when** `--capture-mode deep`
- `--session <id>` (Optional): Workflow session ID
- `--session <id>`: Workflow session ID
- Integrate into existing session (`.workflow/WFS-{session}/`)
- Enable automatic design system integration (Phase 5)
- If not provided: standalone mode (`.workflow/.design/`)
- Enable automatic design system integration (Phase 4)
- If not provided: standalone mode (`.workflow/`)
- `--prompt "<desc>"` (Optional): Style extraction guidance
- Influences extract command analysis focus
- Example: `"Focus on dark mode"`, `"Emphasize minimalist design"`
- **Note**: Design systems are now production-ready by default (no separate consolidate step)
**Input Rules**:
- Must provide: `--input` OR (legacy: `--images`/`--prompt`)
- `--input` can combine multiple input types
- File paths are automatically detected and trigger code import
## Execution Modes
**Capture Modes**:
- **Batch Mode** (default): Multi-URL screenshot capture for fast replication
- Uses `/workflow:ui-design:capture` for parallel screenshot capture
- Optimized for replicating multiple pages efficiently
- **Deep Mode**: Single-URL layer exploration for detailed analysis
- Uses `/workflow:ui-design:explore-layers` for interactive depth traversal
- Captures page layers at different depths (1-5)
- Only processes first URL from url-map
**Input Sources**:
- **Code Files**: Automatically detected from `--prompt` file paths
- Triggers `/workflow:ui-design:import-from-code` for token extraction
- Analyzes existing CSS/JS/HTML files
- **Visual Input**: Images via `--images` glob pattern
- Reference images for style extraction
- Screenshots or design mockups
- **Hybrid Mode**: Combines code import with visual supplements
- Code provides base tokens
- Images supplement missing design elements
**Token Processing**:
- **Direct Generation**: Complete design systems generated in style-extract phase
@@ -92,124 +98,134 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*)
**Session Integration**:
- `--session` flag determines session integration or standalone execution
- Integrated: Design system automatically added to session artifacts
- Standalone: Output in `.workflow/.design/{run_id}/`
- Standalone: Output in `.workflow/{run_id}/`
## 6-Phase Execution
## 5-Phase Execution
### Phase 0: Initialization and Target Parsing
### Phase 0: Parameter Parsing & Input Detection
```bash
# Generate run ID
run_id = "run-$(date +%Y%m%d)-$RANDOM"
# 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_base_path = null
has_visual_input = false
IF prompt_text:
# Extract potential file paths from prompt
potential_paths = extract_paths_from_text(prompt_text)
FOR path IN potential_paths:
IF file_or_directory_exists(path):
code_files_detected = true
code_base_path = path
BREAK
IF images_input:
# Check if images parameter points to existing files
IF glob_matches_files(images_input):
has_visual_input = true
# Step 2: Determine design source strategy
design_source = "unknown"
IF code_files_detected AND has_visual_input:
design_source = "hybrid" # Both code and visual
ELSE IF code_files_detected:
design_source = "code_only" # Only code files
ELSE IF has_visual_input OR --prompt:
design_source = "visual_only" # Only visual/prompt
ELSE:
ERROR: "No design source provided (code files, images, or prompt required)"
EXIT 1
STORE: design_source, code_base_path, has_visual_input
# Step 3: Initialize directories
design_id = "design-run-$(date +%Y%m%d)-$RANDOM"
# Determine base path and session mode
IF --session:
session_id = {provided_session}
relative_base_path = ".workflow/WFS-{session_id}/design-{run_id}"
relative_base_path = ".workflow/WFS-{session_id}/{design_id}"
session_mode = "integrated"
ELSE:
session_id = null
relative_base_path = ".workflow/.design/design-{run_id}"
relative_base_path = ".workflow/{design_id}"
session_mode = "standalone"
# Create base directory and convert to absolute path
Bash(mkdir -p "{relative_base_path}")
base_path=$(cd "{relative_base_path}" && pwd)
# Step 0.1: Intelligent Path Detection
code_files_detected = false
code_base_path = null
design_source = "web" # Default for imitate-auto
IF --prompt:
# Extract potential file paths from prompt
potential_paths = extract_paths_from_text(--prompt)
FOR path IN potential_paths:
IF file_or_directory_exists(path):
code_files_detected = true
code_base_path = path
design_source = "hybrid" # Web + Code
BREAK
STORE: design_source, code_base_path
# Parse url-map
url_map_string = {--url-map}
VALIDATE: url_map_string is not empty, "--url-map parameter is required"
# Parse 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] # First target as primary style source
# Parse capture mode
capture_mode = --capture-mode OR "batch"
depth = int(--depth OR 3)
# Validate capture mode
IF capture_mode NOT IN ["batch", "deep"]:
ERROR: "Invalid --capture-mode: {capture_mode}"
ERROR: "Valid options: batch, deep"
EXIT 1
# Validate depth (only for deep mode)
IF capture_mode == "deep":
IF depth NOT IN [1, 2, 3, 4, 5]:
ERROR: "Invalid --depth: {depth}"
ERROR: "Valid range: 1-5"
EXIT 1
# Warn if multiple URLs in deep mode
IF len(target_names) > 1:
WARN: "⚠️ Deep mode only uses first URL: '{primary_target}'"
WARN: " Other URLs will be ignored: {', '.join(target_names[1:])}"
WARN: " For multi-URL, use --capture-mode batch"
# Write metadata
metadata = {
"workflow": "imitate-auto",
"run_id": run_id,
"run_id": design_id,
"session_id": session_id,
"timestamp": current_timestamp(),
"parameters": {
"url_map": url_map,
"capture_mode": capture_mode,
"depth": depth IF capture_mode == "deep" ELSE null,
"prompt": --prompt OR null
"design_source": design_source,
"code_base_path": code_base_path,
"images": images_input OR null,
"prompt": prompt_text OR null,
"input": --input OR null # Store original --input for reference
},
"targets": target_names,
"status": "in_progress"
}
Write("{base_path}/.run-metadata.json", JSON.stringify(metadata, null, 2))
# Initialize default flags
animation_complete = false
needs_visual_supplement = false
style_complete = false
layout_complete = false
# Initialize TodoWrite
TodoWrite({todos: [
{content: "Initialize and parse url-map", status: "completed", activeForm: "Initializing"},
{content: capture_mode == "batch" ? f"Batch screenshot capture ({len(target_names)} targets)" : f"Deep exploration (depth {depth})", status: "pending", activeForm: "Capturing screenshots"},
{content: "Initialize and detect design source", status: "completed", activeForm: "Initializing"},
{content: "Extract style (complete design systems)", status: "pending", activeForm: "Extracting style"},
{content: "Extract animation (CSS auto mode)", status: "pending", activeForm: "Extracting animation"},
{content: "Extract layout (structure templates)", status: "pending", activeForm: "Extracting layout"},
{content: f"Assemble UI for {len(target_names)} targets", status: "pending", activeForm: "Assembling UI"},
{content: "Assemble UI prototypes", status: "pending", activeForm: "Assembling UI"},
{content: session_id ? "Integrate design system" : "Standalone completion", status: "pending", activeForm: "Completing"}
]})
```
@@ -225,10 +241,14 @@ IF design_source == "hybrid":
REPORT: " → Source: {code_base_path}"
REPORT: " → Mode: Hybrid (Web + Code)"
command = "/workflow:ui-design:import-from-code --base-path \"{base_path}\" " +
command = "/workflow:ui-design:import-from-code --design-id \"{design_id}\" " +
"--source \"{code_base_path}\""
TRY:
# SlashCommand invocation ATTACHES import-from-code's tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself:
# - Phase 0: Discover and categorize code files
# - Phase 1.1-1.3: Style/Animation/Layout Agent extraction
SlashCommand(command)
CATCH error:
WARN: "Code import failed: {error}"
@@ -310,148 +330,120 @@ IF design_source == "hybrid":
STORE: style_complete, animation_complete, layout_complete
TodoWrite(mark_completed: "Initialize and parse url-map",
mark_in_progress: capture_mode == "batch" ? f"Batch screenshot capture ({len(target_names)} targets)" : f"Deep exploration (depth {depth})")
```
### Phase 1: Screenshot Capture (Dual Mode)
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 Phase 1: Screenshot Capture"
IF design_source == "hybrid":
REPORT: " → Purpose: Verify and supplement code analysis"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
IF capture_mode == "batch":
# Mode A: Batch Multi-URL Capture
url_map_command_string = ",".join([f"{name}:{url}" for name, url in url_map.items()])
capture_command = f"/workflow:ui-design:capture --base-path \"{base_path}\" --url-map \"{url_map_command_string}\""
TRY:
SlashCommand(capture_command)
CATCH error:
ERROR: "Batch capture failed: {error}"
ERROR: "Cannot proceed without screenshots"
EXIT 1
# Verify batch capture results
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
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)}"
IF captured_count == 0:
ERROR: "No screenshots captured - cannot proceed"
EXIT 1
ELSE: # capture_mode == "deep"
# Mode B: Deep Interactive Layer Exploration
primary_url = url_map[primary_target]
explore_command = f"/workflow:ui-design:explore-layers --url \"{primary_url}\" --depth {depth} --base-path \"{base_path}\""
TRY:
SlashCommand(explore_command)
CATCH error:
ERROR: "Deep exploration failed: {error}"
ERROR: "Cannot proceed without screenshots"
EXIT 1
# Verify deep exploration results
layer_map_path = "{base_path}/screenshots/layer-map.json"
IF NOT exists(layer_map_path):
ERROR: "explore-layers did not generate layer-map.json"
ERROR: "Expected: {layer_map_path}"
EXIT 1
layer_map = Read(layer_map_path)
captured_count = layer_map.summary.total_captures
total_requested = captured_count # For consistency with batch mode
TodoWrite(mark_completed: f"Batch screenshot capture ({len(target_names)} targets)" IF capture_mode == "batch" ELSE f"Deep exploration (depth {depth})",
mark_in_progress: "Extract style (visual tokens)")
TodoWrite(mark_completed: "Initialize and detect design source",
mark_in_progress: "Extract style (complete design systems)")
```
### Phase 2: Style Extraction
```bash
# Determine if style extraction needed
skip_style = (design_source == "hybrid" AND style_complete)
skip_style = (design_source == "code_only" AND style_complete)
IF skip_style:
REPORT: "✅ Phase 2: Style (Using Code Import)"
ELSE:
REPORT: "🚀 Phase 2: Style Extraction"
IF capture_mode == "batch":
images_glob = f"{base_path}/screenshots/*.{{png,jpg,jpeg,webp}}"
ELSE:
images_glob = f"{base_path}/screenshots/**/*.{{png,jpg,jpeg,webp}}"
IF --prompt:
extraction_prompt = f"Extract visual style tokens from '{primary_target}'. {--prompt}"
ELSE:
# Build command with available inputs
command_parts = [f"/workflow:ui-design:style-extract --design-id \"{design_id}\""]
IF images_input:
command_parts.append(f"--images \"{images_input}\"")
IF prompt_text:
extraction_prompt = prompt_text
IF design_source == "hybrid":
extraction_prompt = f"Extract visual style tokens from '{primary_target}' to supplement code-imported design tokens."
ELSE:
extraction_prompt = f"Extract visual style tokens from '{primary_target}' with consistency across all pages."
extraction_prompt = f"{prompt_text} (supplement code-imported tokens)"
command_parts.append(f"--prompt \"{extraction_prompt}\"")
url_map_for_extract = ",".join([f"{name}:{url}" for name, url in url_map.items()])
extract_command = f"/workflow:ui-design:style-extract --base-path \"{base_path}\" --images \"{images_glob}\" --urls \"{url_map_for_extract}\" --prompt \"{extraction_prompt}\" --variants 1 --interactive"
command_parts.extend(["--variants 1", "--refine", "--interactive"])
extract_command = " ".join(command_parts)
# SlashCommand invocation ATTACHES style-extract's tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself
SlashCommand(extract_command)
TodoWrite(mark_completed: "Extract style", mark_in_progress: "Extract animation")
# After executing all attached tasks, collapse them into phase summary
TodoWrite(mark_completed: "Extract style", mark_in_progress: "Extract animation")
```
### Phase 2.3: Animation Extraction
```bash
skip_animation = (design_source == "hybrid" AND animation_complete)
skip_animation = (design_source == "code_only" AND animation_complete)
IF skip_animation:
REPORT: "✅ Phase 2.3: Animation (Using Code Import)"
ELSE:
REPORT: "🚀 Phase 2.3: Animation Extraction"
url_map_for_animation = ",".join([f"{target}:{url}" for target, url in url_map.items()])
animation_extract_command = f"/workflow:ui-design:animation-extract --base-path \"{base_path}\" --urls \"{url_map_for_animation}\" --mode auto"
# Build command with available inputs
command_parts = [f"/workflow:ui-design:animation-extract --design-id \"{design_id}\""]
IF images_input:
command_parts.append(f"--images \"{images_input}\"")
IF prompt_text:
command_parts.append(f"--prompt \"{prompt_text}\"")
command_parts.extend(["--refine", "--interactive"])
animation_extract_command = " ".join(command_parts)
# SlashCommand invocation ATTACHES animation-extract's tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself
SlashCommand(animation_extract_command)
# After executing all attached tasks, collapse them into phase summary
TodoWrite(mark_completed: "Extract animation", mark_in_progress: "Extract layout")
```
### Phase 2.5: Layout Extraction
```bash
skip_layout = (design_source == "hybrid" AND layout_complete)
skip_layout = (design_source == "code_only" AND layout_complete)
IF skip_layout:
REPORT: "✅ Phase 2.5: Layout (Using Code Import)"
ELSE:
REPORT: "🚀 Phase 2.5: Layout Extraction"
url_map_for_layout = ",".join([f"{target}:{url}" for target, url in url_map.items()])
layout_extract_command = f"/workflow:ui-design:layout-extract --base-path \"{base_path}\" --images \"{images_glob}\" --urls \"{url_map_for_layout}\" --targets \"{','.join(target_names)}\" --variants 1 --interactive"
# Build command with available inputs
command_parts = [f"/workflow:ui-design:layout-extract --design-id \"{design_id}\""]
IF images_input:
command_parts.append(f"--images \"{images_input}\"")
IF prompt_text:
command_parts.append(f"--prompt \"{prompt_text}\"")
# Default target if not specified
command_parts.append("--targets \"home\"")
command_parts.extend(["--variants 1", "--refine", "--interactive"])
layout_extract_command = " ".join(command_parts)
# SlashCommand invocation ATTACHES layout-extract's tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself
SlashCommand(layout_extract_command)
TodoWrite(mark_completed: "Extract layout", mark_in_progress: "Assemble UI")
# After executing all attached tasks, collapse them into phase summary
TodoWrite(mark_completed: "Extract layout", mark_in_progress: "Assemble UI")
```
### Phase 3: UI Assembly
```bash
REPORT: "🚀 Phase 3: UI Assembly"
generate_command = f"/workflow:ui-design:generate --base-path \"{base_path}\" --style-variants 1 --layout-variants 1"
generate_command = f"/workflow:ui-design:generate --design-id \"{design_id}\""
# SlashCommand invocation ATTACHES generate's tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself
SlashCommand(generate_command)
# After executing all attached tasks, collapse them into phase summary
TodoWrite(mark_completed: "Assemble UI", mark_in_progress: session_id ? "Integrate design system" : "Completion")
```
@@ -461,6 +453,9 @@ TodoWrite(mark_completed: "Assemble UI", mark_in_progress: session_id ? "Integra
IF session_id:
REPORT: "🚀 Phase 4: Design System Integration"
update_command = f"/workflow:ui-design:update --session {session_id}"
# SlashCommand invocation ATTACHES update's tasks to current workflow
# Orchestrator will EXECUTE these attached tasks itself
SlashCommand(update_command)
# Update metadata
@@ -490,7 +485,7 @@ TodoWrite({todos: [
]})
```
### Phase 6: Completion Report
### Phase 4: Completion Report
**Completion Message**:
```
@@ -500,26 +495,24 @@ TodoWrite({todos: [
━━━ 📊 Workflow Summary ━━━
Mode: {capture_mode == "batch" ? "Batch Multi-Page Replication" : f"Deep Interactive Exploration (depth {depth})"}
Mode: Direct Input ({design_source})
Session: {session_id or "standalone"}
Run ID: {run_id}
Phase 1 - Screenshot Capture: ✅ {IF capture_mode == "batch": f"{captured_count}/{total_requested} screenshots" ELSE: f"{captured_count} screenshots ({total_layers} layers)"}
{IF capture_mode == "batch" AND captured_count < total_requested: f"⚠️ {total_requested - captured_count} missing" ELSE: "All targets captured"}
Phase 0 - Input Detection: ✅ {design_source} mode
{IF design_source == "code_only": "Code files imported" ELSE IF design_source == "hybrid": "Code + visual inputs" ELSE: "Visual inputs"}
Phase 2 - Style Extraction: ✅ Production-ready design systems
Output: style-extraction/style-1/ (design-tokens.json + style-guide.md)
Quality: WCAG AA compliant, OKLCH colors
Phase 2.3 - Animation Extraction: ✅ CSS animations and transitions
Phase 2.3 - Animation Extraction: ✅ Animation tokens
Output: animation-extraction/ (animation-tokens.json + animation-guide.md)
Method: Auto-extracted from live URLs via Chrome DevTools
Phase 2.5 - Layout Extraction: ✅ Structure templates
Templates: {template_count} layout structures
Phase 3 - UI Assembly: ✅ {generated_count} pages assembled
Targets: {', '.join(target_names)}
Phase 3 - UI Assembly: ✅ {generated_count} prototypes assembled
Configuration: 1 style × 1 layout × {generated_count} pages
Phase 4 - Integration: {IF session_id: "✅ Integrated into session" ELSE: "⏭️ Standalone mode"}
@@ -527,20 +520,6 @@ Phase 4 - Integration: {IF session_id: "✅ Integrated into session" ELSE: "⏭
━━━ 📂 Output Structure ━━━
{base_path}/
├── screenshots/ # {captured_count} screenshots
{IF capture_mode == "batch":
│ ├── {target1}.png
│ ├── {target2}.png
│ └── capture-metadata.json
ELSE:
│ ├── depth-1/
│ │ └── full-page.png
│ ├── depth-2/
│ │ └── {elements}.png
│ ├── depth-{depth}/
│ │ └── {layers}.png
│ └── layer-map.json
}
├── style-extraction/ # Production-ready design systems
│ └── style-1/
│ ├── design-tokens.json
@@ -549,19 +528,18 @@ ELSE:
│ ├── animation-tokens.json
│ └── animation-guide.md
├── layout-extraction/ # Structure templates
│ └── layout-{target}-1.json # One file per target
│ └── layout-home-1.json # Layout templates
└── prototypes/ # {generated_count} HTML/CSS files
├── {target1}-style-1-layout-1.html + .css
├── {target2}-style-1-layout-1.html + .css
├── home-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}
Animation extraction: ~{animation_time}
Layout extraction: ~{layout_time}
UI generation: ~{generate_time}
━━━ 🌐 Next Steps ━━━
@@ -590,103 +568,81 @@ ELSE:
## TodoWrite Pattern
```javascript
// Initialize IMMEDIATELY at start of Phase 0 to track multi-phase execution
// Initialize IMMEDIATELY at start of Phase 0 to track multi-phase execution (6 orchestrator-level tasks)
TodoWrite({todos: [
{content: "Initialize and parse url-map", status: "in_progress", activeForm: "Initializing"},
{content: "Batch screenshot capture", status: "pending", activeForm: "Capturing screenshots"},
{content: "Initialize and detect design source", status: "in_progress", activeForm: "Initializing"},
{content: "Extract style (complete design systems)", status: "pending", activeForm: "Extracting style"},
{content: "Extract animation (CSS auto mode)", status: "pending", activeForm: "Extracting animation"},
{content: "Extract layout (structure templates)", status: "pending", activeForm: "Extracting layout"},
{content: "Assemble UI for all targets", status: "pending", activeForm: "Assembling UI"},
{content: "Assemble UI prototypes", status: "pending", activeForm: "Assembling UI"},
{content: "Integrate design system", status: "pending", activeForm: "Integrating"}
]})
// ⚠️ CRITICAL: After EACH SlashCommand completion (Phase 1-5), you MUST:
// 1. SlashCommand blocks and returns when phase is complete
// 2. Update current phase: status → "completed"
// 3. Update next phase: status → "in_progress"
// 4. IMMEDIATELY execute next phase SlashCommand (auto-continue)
// This ensures continuous workflow tracking and prevents premature stopping
// ⚠️ CRITICAL: Dynamic TodoWrite task attachment strategy:
//
// **Key Concept**: SlashCommand invocation ATTACHES tasks to current workflow.
// Orchestrator EXECUTES these attached tasks itself, not waiting for external completion.
//
// Phase 2-4 SlashCommand Invocation Pattern:
// 1. SlashCommand invocation ATTACHES sub-command tasks to TodoWrite
// 2. TodoWrite expands to include attached tasks
// 3. Orchestrator EXECUTES attached tasks sequentially
// 4. After all attached tasks complete, COLLAPSE them into phase summary
// 5. Update next phase to in_progress
// 6. IMMEDIATELY execute next phase SlashCommand (auto-continue)
//
// Benefits:
// ✓ Real-time visibility into sub-command task progress
// ✓ Clean orchestrator-level summary after each phase
// ✓ Clear mental model: SlashCommand = attach tasks, not delegate work
// ✓ Dynamic attachment/collapse maintains clarity
```
## 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
- **Input validation**: Must provide at least one of --images or --prompt
- **Design source detection**: Error if no valid inputs found
- **Code import failure**: Fallback to visual-only mode in hybrid, error in code-only mode
### Phase-Specific Errors
- **Screenshot capture failure (Phase 1)**:
- If total_captured == 0: Terminate workflow
- If partial failure: Warn but continue with available screenshots
- **Code import failure (Phase 0.5)**:
- code_only mode: Terminate with clear error
- hybrid mode: Warn and fallback to visual-only mode
- **Style extraction failure (Phase 2)**:
- If extract fails: Terminate with clear error
- If style-cards.json missing: Terminate with debugging info
- If design-tokens.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
- **Animation extraction failure (Phase 2.3)**:
- Non-critical: Warn but continue
- Can proceed without animation tokens
- **UI generation failure (Phase 4)**:
- **Layout extraction failure (Phase 2.5)**:
- If extract fails: Terminate with error
- Need layout templates for assembly
- **UI generation failure (Phase 3)**:
- If generate fails: Terminate with error
- If generated_count < target_count: Warn but proceed
- If generated_count < expected: Warn but proceed
- **Integration failure (Phase 5)**:
- **Integration failure (Phase 4)**:
- 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
- **Code import failure**: Automatic fallback to visual-only in hybrid mode
- **Generate failure**: Report specific failures, user can re-generate individually
- **Integration failure**: Prototypes still usable, can integrate manually
## Key Features
- **🚀 Dual Capture**: Batch mode for speed, deep mode for detail
- **⚡ Production-Ready**: Complete design systems generated directly (~30-60s faster)
- **🎨 High-Fidelity**: Single unified design system from primary target
- **📦 Autonomous**: No user intervention required between phases
- **🔄 Reproducible**: Deterministic flow with isolated run directories
- **🎯 Flexible**: Standalone or session-integrated modes
## Examples
### 1. Basic Multi-Page Replication
```bash
/workflow:ui-design:imitate-auto --url-map "home:https://linear.app, features:https://linear.app/features"
# Result: 2 prototypes with fast-track tokens
```
### 2. Session Integration
```bash
/workflow:ui-design:imitate-auto --session WFS-payment --url-map "pricing:https://stripe.com/pricing"
# Result: 1 prototype with production-ready design system, integrated into session
```
### 3. Deep Exploration Mode
```bash
/workflow:ui-design:imitate-auto --url-map "app:https://app.com" --capture-mode deep --depth 3
# Result: Interactive layer capture + prototype
```
### 4. Guided Style Extraction
```bash
/workflow:ui-design:imitate-auto --url-map "home:https://example.com, about:https://example.com/about" --prompt "Focus on minimalist design"
# Result: 2 prototypes with minimalist style focus
```
## Integration Points
- **Input**: `--url-map` (multiple target:url pairs) + optional `--capture-mode`, `--depth`, `--session`, `--prompt`
- **Output**: Complete design system in `{base_path}/` (screenshots, style-extraction, layout-extraction, prototypes)
- **Input**: `--images` (glob pattern) and/or `--prompt` (text/file paths) + optional `--session`
- **Output**: Complete design system in `{base_path}/` (style-extraction, layout-extraction, prototypes)
- **Sub-commands Called**:
1. Phase 1 (conditional):
- `--capture-mode batch`: `/workflow:ui-design:capture` (multi-URL batch)
- `--capture-mode deep`: `/workflow:ui-design:explore-layers` (single-URL depth exploration)
1. `/workflow:ui-design:import-from-code` (Phase 0.5, conditional - if code files detected)
2. `/workflow:ui-design:style-extract` (Phase 2 - complete design systems)
3. `/workflow:ui-design:animation-extract` (Phase 2.3 - CSS animations and transitions)
3. `/workflow:ui-design:animation-extract` (Phase 2.3 - animation tokens)
4. `/workflow:ui-design:layout-extract` (Phase 2.5 - structure templates)
5. `/workflow:ui-design:generate` (Phase 3 - pure assembly)
6. `/workflow:ui-design:update` (Phase 4, if --session)
@@ -696,30 +652,31 @@ TodoWrite({todos: [
```
✅ UI Design Imitate-Auto Workflow Complete!
Mode: {capture_mode} | Session: {session_id or "standalone"}
Mode: Direct Input ({design_source}) | Session: {session_id or "standalone"}
Run ID: {run_id}
Phase 1 - Screenshot Capture: ✅ {captured_count} screenshots
Phase 0 - Input Detection: ✅ {design_source} mode
Phase 2 - Style Extraction: ✅ Production-ready design systems
Phase 2.3 - Animation Extraction: ✅ Animation tokens
Phase 2.5 - Layout Extraction: ✅ Structure templates
Phase 3 - UI Assembly: ✅ {generated_count} pages assembled
Phase 3 - UI Assembly: ✅ {generated_count} prototypes assembled
Phase 4 - Integration: {IF session_id: "✅ Integrated" ELSE: "⏭️ Standalone"}
Design Quality:
✅ High-Fidelity Replication: Accurate style from primary target
✅ Token-Driven Styling: 100% var() usage
✅ Production-Ready: WCAG AA compliant, OKLCH colors
✅ Multi-Source: Code import + visual extraction
📂 {base_path}/
├── screenshots/ # {captured_count} screenshots
├── style-extraction/style-1/ # Production-ready design system
├── animation-extraction/ # Animation tokens
├── layout-extraction/ # Structure templates
└── prototypes/ # {generated_count} HTML/CSS files
🌐 Preview: {base_path}/prototypes/compare.html
- Interactive preview
- Side-by-side comparison
- {generated_count} replicated pages
- Design token driven
- {generated_count} assembled prototypes
Next: [/workflow:execute] OR [Open compare.html → /workflow:plan]
```

View File

@@ -1,7 +1,7 @@
---
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
argument-hint: "[--base-path <path>] [--source <path>] [--css \"<glob>\"] [--js \"<glob>\"] [--scss \"<glob>\"] [--html \"<glob>\"] [--style-files \"<glob>\"] [--session <id>]"
description: Import design system from code files (CSS/JS/HTML/SCSS) with automatic file discovery and parallel agent analysis
argument-hint: "[--design-id <id>] [--session <id>] [--source <path>]"
allowed-tools: Read,Write,Bash,Glob,Grep,Task,TodoWrite
auto-continue: true
---
@@ -34,36 +34,12 @@ Extract design system tokens from source code files (CSS/SCSS/JS/TS/HTML) using
/workflow:ui-design:import-from-code [FLAGS]
# Flags
--base-path <path> Output directory for extracted design tokens (default: current directory)
--source <path> Source code directory to analyze (default: base-path)
--css "<glob>" CSS file glob pattern (e.g., "theme/*.css")
--scss "<glob>" SCSS file glob pattern (e.g., "styles/*.scss")
--js "<glob>" JavaScript file glob pattern (e.g., "theme/*.js")
--html "<glob>" HTML file glob pattern (e.g., "pages/*.html")
--style-files "<glob>" Universal style file glob (applies to CSS/SCSS/JS)
--session <id> Session identifier for workflow tracking
--design-id <id> Design run ID to import into (must exist)
--session <id> Session ID (uses latest design run in session)
--source <path> Source code directory to analyze (required)
```
### Usage Examples
```bash
# Basic usage - auto-discover all files
/workflow:ui-design:import-from-code --base-path ./design-system --source ./src
# Target specific directories
/workflow:ui-design:import-from-code --base-path ./design-system --source ./src --css "theme/*.css" --js "theme/*.js"
# Tailwind config only (output to current directory)
/workflow:ui-design:import-from-code --source ./ --js "tailwind.config.js"
# CSS framework import
/workflow:ui-design:import-from-code --base-path ./design-system --source ./src --css "styles/**/*.scss" --html "components/**/*.html"
# Universal style files
/workflow:ui-design:import-from-code --base-path ./design-system --source ./src --style-files "**/theme.*"
```
---
**Note**: All file discovery is automatic. The command will scan the source directory and find all relevant style files (CSS, SCSS, JS, HTML) automatically.
## Execution Process
@@ -74,13 +50,46 @@ Extract design system tokens from source code files (CSS/SCSS/JS/TS/HTML) using
**Operations**:
```bash
# 1. Initialize directories
base_path="${base_path:-.}"
source="${source:-$base_path}"
# 1. Determine base path with priority: --design-id > --session > error
if [ -n "$DESIGN_ID" ]; then
# Exact match by design ID
relative_path=$(find .workflow -name "${DESIGN_ID}" -type d -print -quit)
if [ -z "$relative_path" ]; then
echo "ERROR: Design run not found: $DESIGN_ID"
echo "HINT: Run '/workflow:ui-design:list' to see available design runs"
exit 1
fi
elif [ -n "$SESSION_ID" ]; then
# Latest in session
relative_path=$(find .workflow/WFS-$SESSION_ID -name "design-run-*" -type d -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2)
if [ -z "$relative_path" ]; then
echo "ERROR: No design run found in session: $SESSION_ID"
echo "HINT: Create a design run first or provide --design-id"
exit 1
fi
else
echo "ERROR: Must provide --design-id or --session parameter"
exit 1
fi
base_path=$(cd "$relative_path" && pwd)
design_id=$(basename "$base_path")
# 2. Initialize directories
source="${source:-.}"
intermediates_dir="${base_path}/.intermediates/import-analysis"
mkdir -p "$intermediates_dir"
echo "[Phase 0] File Discovery Started (source: $source, output: $base_path)"
echo "[Phase 0] File Discovery Started"
echo " Design ID: $design_id"
echo " Source: $source"
echo " Output: $base_path"
# 3. Discover files using script
discovery_file="${intermediates_dir}/discovered-files.json"
~/.claude/scripts/discover-design-files.sh "$source" "$discovery_file"
echo " Output: $discovery_file"
```
<!-- TodoWrite: Initialize todo list -->
@@ -89,70 +98,23 @@ echo "[Phase 0] File Discovery Started (source: $source, output: $base_path)"
```json
[
{"content": "Phase 0: 发现和分类代码文件", "status": "in_progress", "activeForm": "发现代码文件"},
{"content": "Phase 1: 并行Agent分析并生成completeness-report.json", "status": "pending", "activeForm": "生成design system"}
{"content": "Phase 1.1: Style Agent - 提取视觉token及代码片段 (design-tokens.json + code_snippets)", "status": "pending", "activeForm": "提取视觉token"},
{"content": "Phase 1.2: Animation Agent - 提取动画token及代码片段 (animation-tokens.json + code_snippets)", "status": "pending", "activeForm": "提取动画token"},
{"content": "Phase 1.3: Layout Agent - 提取布局模式及代码片段 (layout-templates.json + code_snippets)", "status": "pending", "activeForm": "提取布局模式"}
]
```
**File Discovery Logic**:
**File Discovery Behavior**:
```bash
# 2. Discover files by type
cd "$source" || exit 1
- **Automatic discovery**: Intelligently scans source directory for all style-related files
- **Supported file types**: CSS, SCSS, JavaScript, TypeScript, HTML
- **Smart filtering**: Finds theme-related JS/TS files (e.g., tailwind.config.js, theme.js, styled-components)
- **Exclusions**: Automatically excludes `node_modules/`, `dist/`, `.git/`, and build directories
- **Output**: Single JSON file `discovered-files.json` in `.intermediates/import-analysis/`
- Structure: `{ "css": [...], "js": [...], "html": [...], "counts": {...}, "discovery_time": "..." }`
- Generated via bash commands using `find` + JSON formatting
# CSS files
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**:
```json
[
{"content": "Phase 0: 发现和分类代码文件", "status": "completed", "activeForm": "发现代码文件"},
{"content": "Phase 1: 并行Agent分析并生成completeness-report.json", "status": "in_progress", "activeForm": "生成design system"}
]
```
<!-- TodoWrite: Update Phase 0 → completed, Phase 1.1-1.3 → in_progress (all 3 agents in parallel) -->
---
@@ -174,517 +136,217 @@ echo "[Phase 0] Discovered: CSS=$css_count, SCSS=$scss_count, JS=$js_count, HTML
echo "[Phase 1] Starting parallel agent analysis (3 agents)"
```
#### Style Agent Task (style-completeness-report.json)
#### Style Agent Task (design-tokens.json, style-guide.md)
**Agent Task**:
```javascript
Task(ui-design-agent): `
[STYLE_TOKENS_EXTRACTION]
Extract visual design tokens (colors, typography, spacing, shadows, borders) from ALL file types
Task(subagent_type="ui-design-agent",
prompt="[STYLE_TOKENS_EXTRACTION]
Extract visual design tokens from code files using code import extraction pattern.
MODE: style-extraction | SOURCE: ${source} | BASE_PATH: ${base_path}
## Input Files (Can reference ANY file type)
## Input Files
**CSS/SCSS files (${css_count})**:
$(cat "${intermediates_dir}/css-files.txt" 2>/dev/null | head -20)
**Discovered Files**: ${intermediates_dir}/discovered-files.json
$(cat \"${intermediates_dir}/discovered-files.json\" 2>/dev/null | grep -E '(count|files)' | head -30)
**JavaScript/TypeScript files (${js_count})**:
$(cat "${intermediates_dir}/js-files.txt" 2>/dev/null | head -20)
## Code Import Extraction Strategy
**HTML files (${html_count})**:
$(cat "${intermediates_dir}/html-files.txt" 2>/dev/null | head -20)
**Step 1: Load file list**
- Read(${intermediates_dir}/discovered-files.json)
- Extract: file_types.css.files, file_types.js.files, file_types.html.files
## Extraction Strategy
**Step 2: Cross-source token extraction**
- CSS/SCSS: Colors, typography, spacing, shadows, borders
- JavaScript/TypeScript: Theme configs (Tailwind, styled-components, CSS-in-JS)
- HTML: Inline styles, usage patterns
**You can read ALL file types** - Cross-reference for better extraction:
1. **CSS/SCSS**: Primary source for colors, typography, spacing, shadows, borders
2. **JavaScript/TypeScript**: Theme objects (styled-components, Tailwind config, CSS-in-JS tokens)
3. **HTML**: Inline styles, class usage patterns, component examples
**Step 3: Smart inference for gaps**
- Infer missing tokens from existing patterns
- Normalize inconsistent values into systematic scales
- Fill missing categories from cross-file references
**Smart inference** - Fill gaps using cross-source data:
- Missing CSS colors? Check JS theme objects
- Missing spacing scale? Infer from existing values in any file type
- Missing typography? Check font-family usage in CSS + HTML + JS configs
## Output Files
## Output Requirements
**Target Directory**: ${base_path}/style-extraction/style-1/
Generate 2 files in ${base_path}/style-extraction/style-1/:
1. design-tokens.json (production-ready design tokens)
2. style-guide.md (design philosophy and usage guide)
**Files to Generate**:
1. **design-tokens.json**
- Follow [DESIGN_SYSTEM_GENERATION_TASK] standard token structure
- Add \"_metadata.extraction_source\": \"code_import\"
- Add \"_metadata.files_analyzed\": {css, js, html file lists}
- Add \"_metadata.completeness\": {status, missing_categories, recommendations}
- Add \"_metadata.code_snippets\": Map of code snippets (see below)
- Include \"source\" field for each token (e.g., \"file.css:23\")
### design-tokens.json Structure:
{
"colors": {
"brand": {
"primary": {"value": "#0066cc", "source": "file.css:23"},
"secondary": {"value": "#6c757d", "source": "file.css:24"}
},
"surface": {
"background": {"value": "#ffffff", "source": "file.css:10"},
"card": {"value": "#f8f9fa", "source": "file.css:11"}
},
"semantic": {
"success": {"value": "#28a745", "source": "file.css:30"},
"warning": {"value": "#ffc107", "source": "file.css:31"},
"error": {"value": "#dc3545", "source": "file.css:32"}
},
"text": {
"primary": {"value": "#212529", "source": "file.css:15"},
"secondary": {"value": "#6c757d", "source": "file.css:16"}
},
"border": {
"default": {"value": "#dee2e6", "source": "file.css:20"}
}
},
"typography": {
"font_family": {
"base": {"value": "system-ui, sans-serif", "source": "theme.js:12"},
"heading": {"value": "Georgia, serif", "source": "theme.js:13"}
},
"font_size": {
"xs": {"value": "0.75rem", "source": "styles.css:5"},
"sm": {"value": "0.875rem", "source": "styles.css:6"},
"base": {"value": "1rem", "source": "styles.css:7"},
"lg": {"value": "1.125rem", "source": "styles.css:8"},
"xl": {"value": "1.25rem", "source": "styles.css:9"}
},
"font_weight": {
"normal": {"value": "400", "source": "styles.css:12"},
"medium": {"value": "500", "source": "styles.css:13"},
"bold": {"value": "700", "source": "styles.css:14"}
},
"line_height": {
"tight": {"value": "1.25", "source": "styles.css:18"},
"normal": {"value": "1.5", "source": "styles.css:19"},
"relaxed": {"value": "1.75", "source": "styles.css:20"}
},
"letter_spacing": {
"tight": {"value": "-0.025em", "source": "styles.css:24"},
"normal": {"value": "0", "source": "styles.css:25"},
"wide": {"value": "0.025em", "source": "styles.css:26"}
}
},
"spacing": {
"0": {"value": "0", "source": "styles.css:30"},
"1": {"value": "0.25rem", "source": "styles.css:31"},
"2": {"value": "0.5rem", "source": "styles.css:32"},
"3": {"value": "0.75rem", "source": "styles.css:33"},
"4": {"value": "1rem", "source": "styles.css:34"},
"6": {"value": "1.5rem", "source": "styles.css:35"},
"8": {"value": "2rem", "source": "styles.css:36"},
"12": {"value": "3rem", "source": "styles.css:37"}
},
"opacity": {
"0": {"value": "0", "source": "styles.css:40"},
"50": {"value": "0.5", "source": "styles.css:41"},
"100": {"value": "1", "source": "styles.css:42"}
},
"border_radius": {
"none": {"value": "0", "source": "styles.css:45"},
"sm": {"value": "0.125rem", "source": "styles.css:46"},
"base": {"value": "0.25rem", "source": "styles.css:47"},
"lg": {"value": "0.5rem", "source": "styles.css:48"},
"full": {"value": "9999px", "source": "styles.css:49"}
},
"shadows": {
"sm": {"value": "0 1px 2px rgba(0,0,0,0.05)", "source": "theme.css:45"},
"base": {"value": "0 1px 3px rgba(0,0,0,0.1)", "source": "theme.css:46"},
"md": {"value": "0 4px 6px rgba(0,0,0,0.1)", "source": "theme.css:47"},
"lg": {"value": "0 10px 15px rgba(0,0,0,0.1)", "source": "theme.css:48"}
},
"breakpoints": {
"sm": {"value": "640px", "source": "media.scss:3"},
"md": {"value": "768px", "source": "media.scss:4"},
"lg": {"value": "1024px", "source": "media.scss:5"},
"xl": {"value": "1280px", "source": "media.scss:6"}
},
"_metadata": {
"extraction_source": "code_import",
"files_analyzed": {
"css": ["list of CSS/SCSS files read"],
"js": ["list of JS/TS files read"],
"html": ["list of HTML files read"]
},
"completeness": {
"colors": "complete | partial | minimal",
"typography": "complete | partial | minimal",
"spacing": "complete | partial | minimal",
"missing_categories": ["accent", "warning"],
"recommendations": [
"Define accent color for interactive elements",
"Add semantic colors (warning, error, success)"
]
**Code Snippet Recording**:
- For each extracted token, record the actual code snippet in `_metadata.code_snippets`
- Structure:
```json
\"code_snippets\": {
\"file.css:23\": {
\"lines\": \"23-27\",
\"snippet\": \":root {\\n --color-primary: oklch(0.5555 0.15 270);\\n /* Primary brand color */\\n --color-primary-hover: oklch(0.6 0.15 270);\\n}\",
\"context\": \"css-variable\"
}
}
}
```
- Context types: \"css-variable\" | \"css-class\" | \"js-object\" | \"js-theme-config\" | \"inline-style\"
- Record complete code blocks with all dependencies and relevant comments
- Typical ranges: Simple declarations (1-5 lines), Utility classes (5-15 lines), Complete configs (15-50 lines)
- Preserve original formatting and indentation
### style-guide.md Structure:
# Design System Style Guide
## Overview
Extracted from code files: [list of source files]
## Colors
- **Brand**: Primary, Secondary
- **Surface**: Background, Card
- **Semantic**: Success, Warning, Error
- **Text**: Primary, Secondary
- **Border**: Default
## Typography
- **Font Families**: Base (system-ui), Heading (Georgia)
- **Font Sizes**: xs to xl (0.75rem - 1.25rem)
- **Font Weights**: Normal (400), Medium (500), Bold (700)
## Spacing
System: 8px-grid (0, 0.25rem, 0.5rem, ..., 3rem)
## Missing Elements
- Accent colors for interactive elements
- Extended shadow scale
## Usage
All tokens are production-ready and can be used with CSS variables.
## Completeness Criteria
- **colors**: ≥5 categories (brand, semantic, surface, text, border), ≥10 tokens
- **typography**: ≥3 font families, ≥8 sizes, ≥5 weights
- **spacing**: ≥8 values in consistent system
- **shadows**: ≥3 elevation levels
- **borders**: ≥3 radius values, ≥2 widths
## Critical Requirements
- ✅ Can read ANY file type (CSS/SCSS/JS/TS/HTML) - not restricted to CSS only
- ✅ Use Read() tool for each file you want to analyze (files are in SOURCE: ${source})
- ✅ Cross-reference between file types for better extraction
- ✅ Extract all visual token types systematically
- ✅ Create style-extraction/style-1/ directory first: Bash(mkdir -p "${base_path}/style-extraction/style-1")
- ✅ Use Write() to save both files:
- ${base_path}/style-extraction/style-1/design-tokens.json
- ${base_path}/style-extraction/style-1/style-guide.md
- ✅ Include _metadata.completeness field to track missing content
- ❌ NO external research or MCP calls
`
## Code Import Specific Requirements
- ✅ Read discovered-files.json FIRST to get file paths
- ✅ Track extraction source for each token (file:line)
- ✅ Record complete code snippets in _metadata.code_snippets (complete blocks with dependencies/comments)
- ✅ Include completeness assessment in _metadata
- ✅ Normalize inconsistent values into systematic scales
- ❌ NO external research or web searches (code-only extraction)
")
```
#### Animation Agent Task
#### Animation Agent Task (animation-tokens.json, animation-guide.md)
**Agent Task**:
```javascript
Task(ui-design-agent): `
[ANIMATION_TOKENS_EXTRACTION]
Extract animation/transition tokens from ALL file types
Task(subagent_type="ui-design-agent",
prompt="[ANIMATION_TOKEN_GENERATION_TASK]
Extract animation tokens from code files using code import extraction pattern.
MODE: animation-extraction | SOURCE: ${source} | BASE_PATH: ${base_path}
## Input Files (Can reference ANY file type)
## Input Files
**CSS/SCSS files (${css_count})**:
$(cat "${intermediates_dir}/css-files.txt" 2>/dev/null | head -20)
**Discovered Files**: ${intermediates_dir}/discovered-files.json
$(cat \"${intermediates_dir}/discovered-files.json\" 2>/dev/null | grep -E '(count|files)' | head -30)
**JavaScript/TypeScript files (${js_count})**:
$(cat "${intermediates_dir}/js-files.txt" 2>/dev/null | head -20)
## Code Import Extraction Strategy
**HTML files (${html_count})**:
$(cat "${intermediates_dir}/html-files.txt" 2>/dev/null | head -20)
**Step 1: Load file list**
- Read(${intermediates_dir}/discovered-files.json)
- Extract: file_types.css.files, file_types.js.files, file_types.html.files
## Extraction Strategy
**Step 2: Cross-source animation extraction**
- CSS/SCSS: @keyframes, transitions, animation properties
- JavaScript/TypeScript: Animation frameworks (Framer Motion, GSAP), CSS-in-JS
- HTML: Inline styles, data-animation attributes
**You can read ALL file types** - Find animations anywhere:
1. **CSS/SCSS**: @keyframes, transition properties, animation properties
2. **JavaScript/TypeScript**: Animation configs (Framer Motion, GSAP, CSS-in-JS animations)
3. **HTML**: Inline animation styles, data-animation attributes
**Step 3: Framework detection & normalization**
- Detect animation frameworks used (css-animations | framer-motion | gsap | none)
- Normalize into semantic token system
- Cross-reference CSS animations with JS configs
**Cross-reference**:
- CSS animations referenced in JS configs
- JS animation libraries with CSS class triggers
- HTML elements with animation classes/attributes
## Output Files
## Output Requirements
**Target Directory**: ${base_path}/animation-extraction/
Generate 2 files in ${base_path}/animation-extraction/:
1. animation-tokens.json (production-ready animation tokens)
2. animation-guide.md (animation usage guide)
**Files to Generate**:
1. **animation-tokens.json**
- Follow [ANIMATION_TOKEN_GENERATION_TASK] standard structure
- Add \"_metadata.framework_detected\"
- Add \"_metadata.files_analyzed\"
- Add \"_metadata.completeness\"
- Add \"_metadata.code_snippets\": Map of code snippets (same format as Style Agent)
- Include \"source\" field for each token
### animation-tokens.json Structure:
{
"duration": {
"instant": {"value": "0ms", "source": "animations.css:10"},
"fast": {"value": "150ms", "source": "animations.css:12"},
"base": {"value": "250ms", "source": "animations.css:13"},
"slow": {"value": "500ms", "source": "animations.css:14"}
},
"easing": {
"linear": {"value": "linear", "source": "animations.css:20"},
"ease-in": {"value": "cubic-bezier(0.4, 0, 1, 1)", "source": "theme.js:45"},
"ease-out": {"value": "cubic-bezier(0, 0, 0.2, 1)", "source": "theme.js:46"},
"ease-in-out": {"value": "cubic-bezier(0.4, 0, 0.2, 1)", "source": "theme.js:47"}
},
"transitions": {
"color": {
"property": "color",
"duration": "var(--duration-fast)",
"easing": "var(--ease-out)",
"source": "transitions.css:30"
},
"transform": {
"property": "transform",
"duration": "var(--duration-base)",
"easing": "var(--ease-in-out)",
"source": "transitions.css:35"
},
"opacity": {
"property": "opacity",
"duration": "var(--duration-fast)",
"easing": "var(--ease-out)",
"source": "transitions.css:40"
}
},
"keyframes": {
"fadeIn": {
"name": "fadeIn",
"keyframes": {
"0%": {"opacity": "0"},
"100%": {"opacity": "1"}
},
"source": "styles.css:67"
},
"slideInUp": {
"name": "slideInUp",
"keyframes": {
"0%": {"transform": "translateY(20px)", "opacity": "0"},
"100%": {"transform": "translateY(0)", "opacity": "1"}
},
"source": "styles.css:75"
}
},
"interactions": {
"button-hover": {
"trigger": "hover",
"properties": ["background-color", "transform"],
"duration": "var(--duration-fast)",
"easing": "var(--ease-out)",
"source": "button.css:45"
}
},
"_metadata": {
"extraction_source": "code_import",
"framework_detected": "css-animations | framer-motion | gsap | none",
"files_analyzed": {
"css": ["list of CSS/SCSS files read"],
"js": ["list of JS/TS files read"],
"html": ["list of HTML files read"]
},
"completeness": {
"durations": "complete | partial | minimal",
"easing": "complete | partial | minimal",
"keyframes": "complete | partial | minimal",
"missing_items": ["bounce easing", "slide animations"],
"recommendations": [
"Add slow duration for complex animations",
"Define spring/bounce easing for interactive feedback"
]
}
}
}
**Code Snippet Recording**:
- Record actual animation/transition code in `_metadata.code_snippets`
- Context types: \"css-keyframes\" | \"css-transition\" | \"js-animation\" | \"framer-motion\" | \"gsap\"
- Record complete blocks: @keyframes animations (10-30 lines), transition configs (5-15 lines), JS animation objects (15-50 lines)
- Include all animation steps, timing functions, and related comments
- Preserve original formatting and framework-specific syntax
### animation-guide.md Structure:
# Animation System Guide
## Overview
Extracted from code files: [list of source files]
Framework detected: [css-animations | framer-motion | gsap | none]
## Durations
- **Instant**: 0ms
- **Fast**: 150ms (UI feedback)
- **Base**: 250ms (standard transitions)
- **Slow**: 500ms (complex animations)
## Easing Functions
- **Linear**: Constant speed
- **Ease-out**: Fast start, slow end (entering elements)
- **Ease-in-out**: Smooth acceleration and deceleration
## Keyframe Animations
- **fadeIn**: Opacity 0 → 1
- **slideInUp**: Slide from bottom with fade
## Missing Elements
- Bounce/spring easing for playful interactions
- Slide-out animations
## Usage
All animation tokens use CSS variables and can be referenced in transitions.
## Completeness Criteria
- **durations**: ≥3 (fast, medium, slow)
- **easing**: ≥3 functions (ease-in, ease-out, ease-in-out)
- **keyframes**: ≥3 animation types (fade, scale, slide)
- **transitions**: ≥5 properties defined
## Critical Requirements
- ✅ Can read ANY file type (CSS/SCSS/JS/TS/HTML)
- ✅ Use Read() tool for each file you want to analyze (files are in SOURCE: ${source})
- ✅ Detect animation framework if used
- ✅ Extract all animation-related tokens
- ✅ Create animation-extraction/ directory first: Bash(mkdir -p "${base_path}/animation-extraction")
- ✅ Use Write() to save both files:
- ${base_path}/animation-extraction/animation-tokens.json
- ${base_path}/animation-extraction/animation-guide.md
- ✅ Include _metadata.completeness field to track missing content
- ❌ NO external research or MCP calls
`
## Code Import Specific Requirements
- ✅ Read discovered-files.json FIRST to get file paths
- ✅ Detect animation framework if present
- ✅ Track extraction source for each token (file:line)
- ✅ Record complete code snippets in _metadata.code_snippets (complete animation blocks with all steps/timing)
- ✅ Normalize framework-specific syntax into standard tokens
- ❌ NO external research or web searches (code-only extraction)
")
```
#### Layout Agent Task
#### Layout Agent Task (layout-templates.json, layout-guide.md)
**Agent Task**:
```javascript
Task(ui-design-agent): `
[LAYOUT_PATTERNS_EXTRACTION]
Extract layout patterns and component structures from ALL file types
Task(subagent_type="ui-design-agent",
prompt="[LAYOUT_TEMPLATE_GENERATION_TASK]
Extract layout patterns from code files using code import extraction pattern.
MODE: layout-extraction | SOURCE: ${source} | BASE_PATH: ${base_path}
## Input Files (Can reference ANY file type)
## Input Files
**CSS/SCSS files (${css_count})**:
$(cat "${intermediates_dir}/css-files.txt" 2>/dev/null | head -20)
**Discovered Files**: ${intermediates_dir}/discovered-files.json
$(cat \"${intermediates_dir}/discovered-files.json\" 2>/dev/null | grep -E '(count|files)' | head -30)
**JavaScript/TypeScript files (${js_count})**:
$(cat "${intermediates_dir}/js-files.txt" 2>/dev/null | head -20)
## Code Import Extraction Strategy
**HTML files (${html_count})**:
$(cat "${intermediates_dir}/html-files.txt" 2>/dev/null | head -20)
**Step 1: Load file list**
- Read(${intermediates_dir}/discovered-files.json)
- Extract: file_types.css.files, file_types.js.files, file_types.html.files
## Extraction Strategy
**Step 2: Cross-source layout extraction**
- CSS/SCSS: Grid systems, flexbox utilities, layout classes, media queries
- JavaScript/TypeScript: Layout components (React/Vue), grid configs
- HTML: Semantic structure, component hierarchies
**You can read ALL file types** - Find layout patterns anywhere:
1. **CSS/SCSS**: Grid systems, flexbox utilities, layout classes, media queries
2. **JavaScript/TypeScript**: Layout components (React/Vue), grid configurations, responsive logic
3. **HTML**: Layout structures, semantic patterns, component hierarchies
**Component Classification** (MUST annotate in extraction):
- **Universal Components**: Reusable multi-component templates (buttons, inputs, cards, modals, etc.)
- **Specialized Components**: Module-specific components from code (feature-specific layouts, custom widgets, domain components)
**Cross-reference**:
- HTML structure + CSS classes → layout system
- JS components + CSS styles → component patterns
- Responsive classes across all file types
**Step 3: System identification**
- Detect naming convention (BEM | SMACSS | utility-first | css-modules)
- Identify layout system (12-column | flexbox | css-grid | custom)
- Extract responsive strategy and breakpoints
## Output Requirements
## Output Files
Generate 1 file: ${base_path}/layout-extraction/layout-templates.json
**Target Directory**: ${base_path}/layout-extraction/
### layout-templates.json Structure:
{
"extraction_metadata": {
"extraction_source": "code_import",
"analysis_time": "ISO8601 timestamp",
"files_analyzed": {
"css": ["list of CSS/SCSS files read"],
"js": ["list of JS/TS files read"],
"html": ["list of HTML files read"]
},
"naming_convention": "BEM | SMACSS | utility-first | css-modules | custom",
"layout_system": {
"type": "12-column | flexbox | css-grid | custom",
"confidence": "high | medium | low",
"container_classes": ["container", "wrapper"],
"row_classes": ["row"],
"column_classes": ["col-1", "col-md-6"],
"source_files": ["grid.css", "Layout.jsx"]
},
"responsive": {
"breakpoint_prefixes": ["sm:", "md:", "lg:", "xl:"],
"mobile_first": true,
"breakpoints": {
"sm": "640px",
"md": "768px",
"lg": "1024px",
"xl": "1280px"
},
"source": "responsive.scss:5"
},
"completeness": {
"layout_system": "complete | partial | minimal",
"components": "complete | partial | minimal",
"responsive": "complete | partial | minimal",
"missing_items": ["gap utilities", "modal", "dropdown"],
"recommendations": [
"Add gap utilities for consistent spacing in grid layouts",
"Define modal/dropdown/tabs component patterns"
]
}
},
"layout_templates": [
{
"target": "button",
"variant_id": "layout-1",
"device_type": "responsive",
"component_type": "component",
"dom_structure": {
"tag": "button",
"classes": ["btn", "btn-primary"],
"children": [
{"tag": "span", "classes": ["btn-text"], "content": "{{text}}"}
],
"variants": {
"primary": {"classes": ["btn", "btn-primary"]},
"secondary": {"classes": ["btn", "btn-secondary"]}
},
"sizes": {
"sm": {"classes": ["btn-sm"]},
"base": {"classes": []},
"lg": {"classes": ["btn-lg"]}
},
"states": ["hover", "active", "disabled"]
},
"css_layout_rules": "display: inline-flex; align-items: center; justify-content: center; padding: var(--spacing-2) var(--spacing-4); border-radius: var(--radius-base);",
"source": "button.css:12"
},
{
"target": "card",
"variant_id": "layout-1",
"device_type": "responsive",
"component_type": "component",
"dom_structure": {
"tag": "div",
"classes": ["card"],
"children": [
{"tag": "div", "classes": ["card-header"], "content": "{{title}}"},
{"tag": "div", "classes": ["card-body"], "content": "{{content}}"},
{"tag": "div", "classes": ["card-footer"], "content": "{{footer}}"}
]
},
"css_layout_rules": "display: flex; flex-direction: column; border: 1px solid var(--color-border); border-radius: var(--radius-lg); padding: var(--spacing-4); background: var(--color-surface-card);",
"source": "card.css:25"
}
]
}
**Files to Generate**:
## Completeness Criteria
- **layout_system**: Clear grid/flexbox system identified
- **components**: ≥5 component patterns (button, card, input, modal, dropdown)
- **responsive**: ≥3 breakpoints, clear mobile-first strategy
- **naming_convention**: Consistent pattern identified
1. **layout-templates.json**
- Follow [LAYOUT_TEMPLATE_GENERATION_TASK] standard structure
- Add \"extraction_metadata\" section:
* extraction_source: \"code_import\"
* naming_convention: detected convention
* layout_system: {type, confidence, source_files}
* responsive: {breakpoints, mobile_first, source}
* completeness: {status, missing_items, recommendations}
* code_snippets: Map of code snippets (same format as Style Agent)
- For each component in \"layout_templates\":
* Include \"source\" field (file:line)
* **Include \"component_type\" field: \"universal\" | \"specialized\"**
* dom_structure with semantic HTML5
* css_layout_rules using var() placeholders
* Add \"description\" field explaining component purpose and classification rationale
## Critical Requirements
- ✅ Can read ANY file type (CSS/SCSS/JS/TS/HTML)
- ✅ Use Read() tool for each file you want to analyze (files are in SOURCE: ${source})
- ✅ Identify naming conventions and layout systems
- ✅ Extract component patterns with variants and states
- ✅ Create layout-extraction/ directory first: Bash(mkdir -p "${base_path}/layout-extraction")
- ✅ Use Write() to save: ${base_path}/layout-extraction/layout-templates.json
- ✅ Include extraction_metadata.completeness field to track missing content
- ❌ NO external research or MCP calls
`
**Code Snippet Recording**:
- Record actual layout/component code in `extraction_metadata.code_snippets`
- Context types: \"css-grid\" | \"css-flexbox\" | \"css-utility\" | \"html-structure\" | \"react-component\"
- Record complete blocks: Utility classes (5-15 lines), HTML structures (10-30 lines), React components (20-100 lines)
- For components: include HTML structure + associated CSS rules + component logic
- Preserve original formatting and framework-specific syntax
## Code Import Specific Requirements
- ✅ Read discovered-files.json FIRST to get file paths
- ✅ Detect and document naming conventions
- ✅ Identify layout system with confidence level
- ✅ Extract component variants and states from usage patterns
- ✅ **Classify each component as \"universal\" or \"specialized\"** based on:
* Universal: Reusable across multiple features (buttons, inputs, cards, modals)
* Specialized: Feature-specific or domain-specific (checkout form, dashboard widget)
- ✅ Record complete code snippets in extraction_metadata.code_snippets (complete components/structures)
- ✅ **Document classification rationale** in component description
- ❌ NO external research or web searches (code-only extraction)
")
```
**Wait for All Agents**:
@@ -696,15 +358,7 @@ Task(ui-design-agent): `
echo "[Phase 1] Parallel agent analysis complete"
```
<!-- TodoWrite: Mark all complete -->
**TodoWrite**:
```json
[
{"content": "Phase 0: 发现和分类代码文件", "status": "completed", "activeForm": "发现代码文件"},
{"content": "Phase 1: 并行Agent分析并生成completeness-report.json", "status": "completed", "activeForm": "生成design system"}
]
```
<!-- TodoWrite: Update Phase 1.1-1.3 → completed (all 3 agents complete together) -->
---
@@ -719,49 +373,37 @@ echo "[Phase 1] Parallel agent analysis complete"
${base_path}/
├── style-extraction/
│ └── style-1/
── design-tokens.json # Production-ready design tokens
│ └── style-guide.md # Design philosophy and usage
── design-tokens.json # Production-ready design tokens with code snippets
├── animation-extraction/
── animation-tokens.json # Animation/transition tokens
│ └── animation-guide.md # Animation usage guide
── animation-tokens.json # Animation/transition tokens with code snippets
├── layout-extraction/
│ └── layout-templates.json # Layout patterns and component structures
│ └── layout-templates.json # Layout patterns with code snippets
└── .intermediates/
└── import-analysis/
── css-files.txt # Discovered CSS/SCSS files
├── js-files.txt # Discovered JS/TS files
└── html-files.txt # Discovered HTML files
── discovered-files.json # All discovered files (JSON format)
```
**Files**:
1. **style-extraction/style-1/design-tokens.json**
- Production-ready design tokens
- Categories: colors, typography, spacing, opacity, border_radius, shadows, breakpoints
- Metadata: extraction_source, files_analyzed, completeness assessment
- Metadata: extraction_source, files_analyzed, completeness assessment, **code_snippets**
- **Code snippets**: Complete code blocks from source files (CSS variables, theme configs, inline styles)
2. **style-extraction/style-1/style-guide.md**
- Design system overview
- Token categories and usage
- Missing elements and recommendations
3. **animation-extraction/animation-tokens.json**
2. **animation-extraction/animation-tokens.json**
- Animation tokens: duration, easing, transitions, keyframes, interactions
- Framework detection: css-animations, framer-motion, gsap, etc.
- Metadata: extraction_source, completeness assessment
- Metadata: extraction_source, completeness assessment, **code_snippets**
- **Code snippets**: Complete animation blocks (@keyframes, transition configs, JS animations)
4. **animation-extraction/animation-guide.md**
- Animation system overview
- Usage guidelines and examples
5. **layout-extraction/layout-templates.json**
3. **layout-extraction/layout-templates.json**
- Layout templates for each discovered component
- Extraction metadata: naming_convention, layout_system, responsive strategy
- Extraction metadata: naming_convention, layout_system, responsive strategy, **code_snippets**
- Component patterns with DOM structure and CSS rules
- **Code snippets**: Complete component/structure code (HTML, CSS utilities, React components)
**Intermediate Files**: `.intermediates/import-analysis/`
- `css-files.txt` - Discovered CSS/SCSS files
- `js-files.txt` - Discovered JS/TS files
- `html-files.txt` - Discovered HTML files
- `discovered-files.json` - All discovered files in JSON format with counts and metadata
---
@@ -771,18 +413,18 @@ ${base_path}/
| Error | Cause | Resolution |
|-------|-------|------------|
| No files discovered | Glob patterns too restrictive or wrong --source path | Check glob patterns and --source parameter, verify file locations |
| No files discovered | Wrong --source path or no style files in directory | Verify --source parameter points to correct directory with style files |
| Agent reports "failed" status | No tokens found in any file | Review file content, check if files contain design tokens |
| Empty completeness reports | Files exist but contain no extractable tokens | Manually verify token definitions in source files |
| Missing file type | Specific file type not discovered | Use explicit glob flags (--css, --js, --html, --scss) |
| Missing file type | File extensions not recognized | Check that files use standard extensions (.css, .scss, .js, .ts, .html) |
---
## Best Practices
1. **Use auto-discovery for full projects**: Omit glob flags to discover all files automatically
2. **Target specific directories for speed**: Use `--source` to specify source code location and `--base-path` for extracted tokens output, combined with specific globs for focused analysis
3. **Separate source and output**: When analyzing external codebases, use `--source` to point to source code and `--base-path` for design tokens output directory (default: --source uses --base-path if not specified)
4. **Cross-reference agent reports**: Compare all three completeness reports to identify gaps
5. **Review missing content**: Check `missing` field in reports for actionable improvements
6. **Verify file discovery**: Check `${base_path}/.intermediates/import-analysis/*-files.txt` if agents report no data
1. **Point to the right directory**: Use `--source` to specify the directory containing your style files (e.g., `./src`, `./app`, `./styles`)
2. **Let automatic discovery work**: The command will find all relevant files - no need to specify patterns
3. **Specify target design run**: Use `--design-id` for existing design run or `--session` to use session's latest design run (one of these is required)
4. **Cross-reference agent reports**: Compare all three completeness reports (style, animation, layout) to identify gaps
5. **Review missing content**: Check `_metadata.completeness` field in reports for actionable improvements
6. **Verify file discovery**: Check `${base_path}/.intermediates/import-analysis/discovered-files.json` if agents report no data

View File

@@ -1,7 +1,7 @@
---
name: layout-extract
description: Extract structural layout information from reference images, URLs, or text prompts using Claude analysis
argument-hint: [--base-path <path>] [--session <id>] [--images "<glob>"] [--urls "<list>"] [--prompt "<desc>"] [--targets "<list>"] [--variants <count>] [--device-type <desktop|mobile|tablet|responsive>] [--interactive]
description: Extract structural layout information from reference images, URLs, or text prompts using Claude analysis with variant generation or refinement mode
argument-hint: [--design-id <id>] [--session <id>] [--images "<glob>"] [--urls "<list>"] [--prompt "<desc>"] [--targets "<list>"] [--variants <count>] [--device-type <desktop|mobile|tablet|responsive>] [--interactive] [--refine]
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestion(*), Task(ui-design-agent), mcp__exa__web_search_exa(*)
---
@@ -9,12 +9,16 @@ allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestio
## Overview
Extract structural layout information from reference images, URLs, or text prompts using AI analysis. This command separates the "scaffolding" (HTML structure and CSS layout) from the "paint" (visual tokens handled by `style-extract`).
Extract structural layout information from reference images, URLs, or text prompts using AI analysis. Supports two modes:
1. **Exploration Mode** (default): Generate multiple contrasting layout variants
2. **Refinement Mode** (`--refine`): Refine a single existing layout through detailed adjustments
This command separates the "scaffolding" (HTML structure and CSS layout) from the "paint" (visual tokens handled by `style-extract`).
**Strategy**: AI-Driven Structural Analysis
- **Agent-Powered**: Uses `ui-design-agent` for deep structural analysis
- **Behavior**: Generate N layout concepts → User multi-select → Generate selected templates
- **Dual Mode**: Exploration (multiple contrasting variants) or Refinement (single layout fine-tuning)
- **Output**: `layout-templates.json` with DOM structure, component hierarchy, and CSS layout rules
- **Device-Aware**: Optimized for specific device types (desktop, mobile, tablet, responsive)
- **Token-Based**: CSS uses `var()` placeholders for spacing and breakpoints
@@ -43,10 +47,19 @@ ELSE:
has_urls = false
url_list = []
# Set variants count (default: 3, range: 1-5)
# Behavior: Generate N layout concepts per target → User multi-select → Generate selected templates
variants_count = --variants OR 3
VALIDATE: 1 <= variants_count <= 5
# Detect refinement mode
refine_mode = --refine OR false
# Set variants count
# Refinement mode: Force variants_count = 1 (ignore user-provided --variants)
# Exploration mode: Use --variants or default to 3 (range: 1-5)
IF refine_mode:
variants_count = 1
REPORT: "🔧 Refinement mode enabled: Will generate 1 refined layout per target"
ELSE:
variants_count = --variants OR 3
VALIDATE: 1 <= variants_count <= 5
REPORT: "🔍 Exploration mode: Will generate {variants_count} contrasting layout concepts per target"
# Resolve targets
# Priority: --targets → url_list targets → prompt analysis → default ["page"]
@@ -65,11 +78,27 @@ ELSE:
# Resolve device type
device_type = --device-type OR "responsive" # desktop|mobile|tablet|responsive
# Determine base path (auto-detect and convert to absolute)
relative_path=$(find .workflow -type d -name "design-run-*" -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2)
# Determine base path with priority: --design-id > --session > auto-detect
if [ -n "$DESIGN_ID" ]; then
# Exact match by design ID
relative_path=$(find .workflow -name "${DESIGN_ID}" -type d -print -quit)
elif [ -n "$SESSION_ID" ]; then
# Latest in session
relative_path=$(find .workflow/WFS-$SESSION_ID -name "design-run-*" -type d -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2)
else
# Latest globally
relative_path=$(find .workflow -name "design-run-*" -type d -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2)
fi
# Validate and convert to absolute path
if [ -z "$relative_path" ] || [ ! -d "$relative_path" ]; then
echo "❌ ERROR: Design run not found"
echo "💡 HINT: Run '/workflow:ui-design:list' to see available design runs"
exit 1
fi
base_path=$(cd "$relative_path" && pwd)
bash(test -d "$base_path" && echo "✓ Base path: $base_path" || echo "✗ Path not found")
# OR use --base-path / --session parameters
bash(echo "✓ Base path: $base_path")
```
### Step 2: Load Inputs & Create Directories
@@ -194,30 +223,46 @@ IF exists: SKIP to completion
**Phase 0 Output**: `input_mode`, `base_path`, `variants_count`, `targets[]`, `device_type`, loaded inputs
## Phase 1: Layout Concept Generation
## Phase 1: Layout Concept or Refinement Options Generation
### Step 1: Generate Layout Concept Options (Agent Task 1)
### Step 0.5: Load Existing Layout (Refinement Mode)
```bash
IF refine_mode:
# Load existing layout for refinement
existing_layouts = {}
FOR target IN targets:
layout_files = bash(find {base_path}/layout-extraction -name "layout-{target}-*.json" -print)
IF layout_files:
# Use first/latest layout file for this target
existing_layouts[target] = Read(first_layout_file)
```
### Step 1: Generate Options (Agent Task 1 - Mode-Specific)
**Executor**: `Task(ui-design-agent)`
Launch agent to generate `variants_count` layout concept options for each target:
**Exploration Mode** (default): Generate contrasting layout concepts
**Refinement Mode** (`--refine`): Generate refinement options for existing layouts
```javascript
Task(ui-design-agent): `
[LAYOUT_CONCEPT_GENERATION_TASK]
Generate {variants_count} structurally distinct layout concepts for each target
// Conditional agent task based on refine_mode
IF NOT refine_mode:
// EXPLORATION MODE
Task(ui-design-agent): `
[LAYOUT_CONCEPT_GENERATION_TASK]
Generate {variants_count} structurally distinct layout concepts for each target
SESSION: {session_id} | MODE: explore | BASE_PATH: {base_path}
TARGETS: {targets} | DEVICE_TYPE: {device_type}
SESSION: {session_id} | MODE: explore | BASE_PATH: {base_path}
TARGETS: {targets} | DEVICE_TYPE: {device_type}
## Input Analysis
- Targets: {targets.join(", ")}
- Device type: {device_type}
- Visual references: {loaded_images if available}
${dom_structure_available ? "- DOM Structure: Read from .intermediates/layout-analysis/dom-structure-*.json" : ""}
## Input Analysis
- Targets: {targets.join(", ")}
- Device type: {device_type}
- Visual references: {loaded_images if available}
${dom_structure_available ? "- DOM Structure: Read from .intermediates/layout-analysis/dom-structure-*.json" : ""}
## Analysis Rules
- For EACH target, generate {variants_count} structurally DIFFERENT layout concepts
- Concepts must differ in: grid structure, component arrangement, visual hierarchy
## Analysis Rules
- For EACH target, generate {variants_count} structurally DIFFERENT layout concepts
- Concepts must differ in: grid structure, component arrangement, visual hierarchy
- Each concept should have distinct navigation pattern, content flow, and responsive behavior
## Generate for EACH Target
@@ -245,7 +290,71 @@ Task(ui-design-agent): `
Use schema from INTERACTIVE-DATA-SPEC.md (Layout Extract: analysis-options.json)
CRITICAL: Use Write() tool immediately after generating complete JSON
`
`
ELSE:
// REFINEMENT MODE
Task(ui-design-agent): `
[LAYOUT_REFINEMENT_OPTIONS_TASK]
Generate refinement options for existing layout(s)
SESSION: {session_id} | MODE: refine | BASE_PATH: {base_path}
TARGETS: {targets} | DEVICE_TYPE: {device_type}
## Existing Layouts
${FOR target IN targets: "- {target}: {existing_layouts[target]}"}
## Input Guidance
- User prompt: {prompt_guidance if available}
- Visual references: {loaded_images if available}
## Refinement Categories
Generate 8-12 refinement options per target across these categories:
1. **Density Adjustments** (2-3 options per target):
- More compact: Tighter spacing, reduced whitespace
- More spacious: Increased margins, breathing room
- Balanced: Moderate adjustments
2. **Responsiveness Tuning** (2-3 options per target):
- Breakpoint behavior: Earlier/later column stacking
- Mobile layout: Different navigation/content priority
- Tablet optimization: Hybrid desktop/mobile approach
3. **Grid/Flex Specifics** (2-3 options per target):
- Column counts: 2-col ↔ 3-col ↔ 4-col
- Gap sizes: Tighter ↔ wider gutters
- Alignment: Different flex/grid justification
4. **Component Arrangement** (1-2 options per target):
- Navigation placement: Top ↔ side ↔ bottom
- Sidebar position: Left ↔ right ↔ none
- Content hierarchy: Different section ordering
## Output Format
Each option (per target):
- target: Which target this refinement applies to
- category: "density|responsiveness|grid|arrangement"
- option_id: unique identifier
- label: Short descriptive name (e.g., "More Compact Spacing")
- description: What changes (2-3 sentences)
- preview_changes: Key structural adjustments
- impact_scope: Which layout regions affected
## Output
Write single JSON file: {base_path}/.intermediates/layout-analysis/analysis-options.json
Use refinement schema:
{
"mode": "refinement",
"device_type": "{device_type}",
"refinement_options": {
"{target1}": [array of refinement options],
"{target2}": [array of refinement options]
}
}
CRITICAL: Use Write() tool immediately after generating complete JSON
`
```
### Step 2: Verify Options File Created
@@ -262,7 +371,9 @@ bash(cat {base_path}/.intermediates/layout-analysis/analysis-options.json | grep
## Phase 1.5: User Confirmation (Optional - Triggered by --interactive)
**Purpose**: Allow user to select preferred layout concept(s) for each target before generating detailed templates
**Purpose**:
- **Exploration Mode**: Allow user to select preferred layout concept(s) per target
- **Refinement Mode**: Allow user to select refinement options to apply per target
**Trigger Condition**: Execute this phase ONLY if `--interactive` flag is present
@@ -271,18 +382,27 @@ bash(cat {base_path}/.intermediates/layout-analysis/analysis-options.json | grep
# Skip this entire phase if --interactive flag is not present
IF NOT --interactive:
SKIP to Phase 2
IF refine_mode:
REPORT: " Non-interactive refinement mode: Will apply all suggested refinements"
ELSE:
REPORT: " Non-interactive mode: Will generate all {variants_count} variants per target"
# Interactive mode enabled
REPORT: "🎯 Interactive mode: User selection required for {targets.length} target(s)"
```
### Step 2: Load and Present Options
### Step 2: Load and Present Options (Mode-Specific)
```bash
# Read options file
options = Read({base_path}/.intermediates/layout-analysis/analysis-options.json)
# Parse layout concepts
layout_concepts = options.layout_concepts
# Branch based on mode
IF NOT refine_mode:
# EXPLORATION MODE
layout_concepts = options.layout_concepts
ELSE:
# REFINEMENT MODE
refinement_options = options.refinement_options
```
### Step 2: Present Options to User (Per Target)
@@ -320,6 +440,25 @@ Please select your preferred concept for this target.
```
### Step 3: Capture User Selection and Update Options File (Per Target)
**Interaction Strategy**: If total concepts > 4 OR any target has > 3 concepts, use batch text format:
```
【目标[N] - [target]】选择布局方案
[key]) Concept [index]: [concept_name]
[design_philosophy]
[key]) Concept [index]: [concept_name]
[design_philosophy]
...
请回答 (格式: 1a 2b 或 1a,b 2c 多选)
User input:
"[N][key] [N][key] ..." → Single selection per target
"[N][key1,key2] [N][key3] ..." → Multi-selection per target
```
Otherwise, use `AskUserQuestion` below.
```javascript
// Use AskUserQuestion tool for each target (multi-select enabled)
FOR each target:
@@ -505,22 +644,27 @@ FOR each task in task_list:
- Device-specific styles (mobile-first @media for responsive)
- NO colors, NO fonts, NO shadows - layout structure only
## Output Format
Write single-template JSON object with:
- target: "{task.target}"
- variant_id: "layout-{task.variant_id}"
- source_image_path (string): Reference image path
- device_type: "{device_type}"
- design_philosophy (string from selected concept)
- dom_structure (JSON object)
- component_hierarchy (array of strings)
- css_layout_rules (string)
## Output Files
Generate 2 files:
1. **layout-templates.json** - {task.output_file}
Write single-template JSON object with:
- target: "{task.target}"
- variant_id: "layout-{task.variant_id}"
- source_image_path (string): Reference image path
- device_type: "{device_type}"
- design_philosophy (string from selected concept)
- dom_structure (JSON object)
- component_hierarchy (array of strings)
- css_layout_rules (string)
## Critical Requirements
- ✅ Use Write() tool for {task.output_file}
- ✅ Use Write() tool to generate JSON file
- ✅ Single template for {task.target} variant {task.variant_id}
- ✅ Structure only, no visual styling
- ✅ Token-based CSS (var())
- ✅ Can use Exa MCP to research modern layout patterns and obtain code examples (Explore/Text mode)
- ✅ Maintain consistency with selected concept
`
```
@@ -584,7 +728,7 @@ Generated Templates:
{base_path}/layout-extraction/
{FOR each target in targets:
{FOR each variant_id in range(1, selections_per_target[target].selected_indices.length + 1):
── layout-{target}-{variant_id}.json
── layout-{target}-{variant_id}.json
}
}
@@ -640,7 +784,7 @@ bash(echo '{json}' > {base_path}/layout-extraction/layout-templates.json)
│ ├── analysis-options.json # Generated layout concepts + user selections (embedded)
│ └── dom-structure-{target}.json # Extracted DOM structure (URL mode only)
└── layout-extraction/ # Final layout templates
└── layout-{target}-{variant}.json # Structural layout templates (one per selected concept)
└── layout-{target}-{variant}.json # Structural layout template JSON
```
## Layout Template File Format
@@ -735,22 +879,4 @@ ERROR: MCP search failed
- **Foundation for Assembly** - Provides structural blueprint for prototype generation
- **Agent-Powered** - Deep structural analysis with AI
## Integration
**Workflow Position**: Between style extraction and prototype generation
**New Workflow**:
1. `/workflow:ui-design:style-extract` → Multiple `style-N/design-tokens.json` files (Complete design systems)
2. `/workflow:ui-design:layout-extract` → Multiple `layout-{target}-{variant}.json` files (Structural templates)
3. `/workflow:ui-design:generate` (Assembler):
- **Reads**: All `design-tokens.json` files + all `layout-{target}-{variant}.json` files
- **Action**: For each style × layout combination:
1. Build HTML from `dom_structure`
2. Create layout CSS from `css_layout_rules`
3. Apply design tokens to CSS
4. Generate complete prototypes
- **Output**: Complete token-driven HTML/CSS prototypes
**Input**: Reference images, URLs, or text prompts
**Output**: `layout-{target}-{variant}.json` files for downstream generation commands
**Next**: `/workflow:ui-design:generate`

View File

@@ -0,0 +1,174 @@
---
name: list
description: List all available design runs with metadata (session, created time, prototype count)
argument-hint: [--session <id>]
allowed-tools: Bash(*), Read(*)
---
# List Design Runs (/workflow:ui-design:list)
## Overview
List all available UI design runs across sessions or within a specific session. Displays design IDs with metadata for easy reference.
**Output**: Formatted list with design-id, session, created time, and prototype count
## Implementation
### Step 1: Determine Search Scope
```bash
# Priority: --session > all sessions
search_path=$(if [ -n "$SESSION_ID" ]; then
echo ".workflow/WFS-$SESSION_ID"
else
echo ".workflow"
fi)
```
### Step 2: Find and Display Design Runs
```bash
echo "Available design runs:"
echo ""
# Find all design-run directories
found_count=0
while IFS= read -r line; do
timestamp=$(echo "$line" | cut -d' ' -f1)
path=$(echo "$line" | cut -d' ' -f2-)
# Extract design_id from path
design_id=$(basename "$path")
# Extract session from path
session_id=$(echo "$path" | grep -oP 'WFS-\K[^/]+' || echo "standalone")
# Format created date
created_at=$(date -d "@${timestamp%.*}" '+%Y-%m-%d %H:%M' 2>/dev/null || echo "unknown")
# Count prototypes
prototype_count=$(find "$path/prototypes" -name "*.html" 2>/dev/null | wc -l)
# Display formatted output
echo " - $design_id"
echo " Session: $session_id"
echo " Created: $created_at"
echo " Prototypes: $prototype_count"
echo ""
found_count=$((found_count + 1))
done < <(find "$search_path" -name "design-run-*" -type d -printf "%T@ %p\n" 2>/dev/null | sort -nr)
# Summary
if [ $found_count -eq 0 ]; then
echo " No design runs found."
echo ""
if [ -n "$SESSION_ID" ]; then
echo "💡 HINT: Try running '/workflow:ui-design:explore-auto' to create a design run"
else
echo "💡 HINT: Try running '/workflow:ui-design:explore-auto --session <id>' to create a design run"
fi
else
echo "Total: $found_count design run(s)"
echo ""
echo "💡 USE: /workflow:ui-design:generate --design-id \"<id>\""
echo " OR: /workflow:ui-design:generate --session \"<session>\""
fi
```
### Step 3: Execute List Command
```bash
Bash(
description: "List all UI design runs with metadata",
command: "
search_path=\"${search_path}\"
SESSION_ID=\"${SESSION_ID:-}\"
echo 'Available design runs:'
echo ''
found_count=0
while IFS= read -r line; do
timestamp=\$(echo \"\$line\" | cut -d' ' -f1)
path=\$(echo \"\$line\" | cut -d' ' -f2-)
design_id=\$(basename \"\$path\")
session_id=\$(echo \"\$path\" | grep -oP 'WFS-\\K[^/]+' || echo 'standalone')
created_at=\$(date -d \"@\${timestamp%.*}\" '+%Y-%m-%d %H:%M' 2>/dev/null || echo 'unknown')
prototype_count=\$(find \"\$path/prototypes\" -name '*.html' 2>/dev/null | wc -l)
echo \" - \$design_id\"
echo \" Session: \$session_id\"
echo \" Created: \$created_at\"
echo \" Prototypes: \$prototype_count\"
echo ''
found_count=\$((found_count + 1))
done < <(find \"\$search_path\" -name 'design-run-*' -type d -printf '%T@ %p\\n' 2>/dev/null | sort -nr)
if [ \$found_count -eq 0 ]; then
echo ' No design runs found.'
echo ''
if [ -n \"\$SESSION_ID\" ]; then
echo '💡 HINT: Try running \\'/workflow:ui-design:explore-auto\\' to create a design run'
else
echo '💡 HINT: Try running \\'/workflow:ui-design:explore-auto --session <id>\\' to create a design run'
fi
else
echo \"Total: \$found_count design run(s)\"
echo ''
echo '💡 USE: /workflow:ui-design:generate --design-id \"<id>\"'
echo ' OR: /workflow:ui-design:generate --session \"<session>\"'
fi
"
)
```
## Example Output
### With Session Filter
```
$ /workflow:ui-design:list --session ui-redesign
Available design runs:
- design-run-20250109-143052
Session: ui-redesign
Created: 2025-01-09 14:30
Prototypes: 12
- design-run-20250109-101534
Session: ui-redesign
Created: 2025-01-09 10:15
Prototypes: 6
Total: 2 design run(s)
💡 USE: /workflow:ui-design:generate --design-id "<id>"
OR: /workflow:ui-design:generate --session "<session>"
```
### All Sessions
```
$ /workflow:ui-design:list
Available design runs:
- design-run-20250109-143052
Session: ui-redesign
Created: 2025-01-09 14:30
Prototypes: 12
- design-run-20250108-092314
Session: landing-page
Created: 2025-01-08 09:23
Prototypes: 3
- design-run-20250107-155623
Session: standalone
Created: 2025-01-07 15:56
Prototypes: 8
Total: 3 design run(s)
💡 USE: /workflow:ui-design:generate --design-id "<id>"
OR: /workflow:ui-design:generate --session "<session>"
```

View File

@@ -0,0 +1,327 @@
---
name: workflow:ui-design:reference-page-generator
description: Generate multi-component reference pages and documentation from design run extraction
argument-hint: "[--design-run <path>] [--package-name <name>] [--output-dir <path>]"
allowed-tools: Read,Write,Bash,Task,TodoWrite
auto-continue: true
---
# UI Design: Reference Page Generator
## Overview
Converts design run extraction results into shareable reference package with:
- Interactive multi-component preview (preview.html + preview.css)
- Component layout templates (layout-templates.json)
**Role**: Takes existing design run (from `import-from-code` or other extraction commands) and generates preview pages for easy reference.
## Usage
### Command Syntax
```bash
/workflow:ui-design:reference-page-generator [FLAGS]
# Flags
--design-run <path> Design run directory path (required)
--package-name <name> Package name for reference (required)
--output-dir <path> Output directory (default: .workflow/reference_style)
```
### Usage Examples
```bash
# Basic usage
/workflow:ui-design:reference-page-generator --design-run .workflow/WFS-123/design-run-456 --package-name main-app-style-v1
# Custom output directory
/workflow:ui-design:reference-page-generator --design-run .workflow/WFS-123/design-run-456 --package-name main-app-style-v1 --output-dir ./style-references
```
---
## Execution Process
### Phase 0: Setup & Validation
**Purpose**: Validate inputs, prepare output directory
**Operations**:
```bash
# 1. Validate required parameters
if [ -z "$design_run" ] || [ -z "$package_name" ]; then
echo "ERROR: --design-run and --package-name are required"
echo "USAGE: /workflow:ui-design:reference-page-generator --design-run <path> --package-name <name>"
exit 1
fi
# 2. Validate package name format (lowercase, alphanumeric, hyphens only)
if ! [[ "$package_name" =~ ^[a-z0-9][a-z0-9-]*$ ]]; then
echo "ERROR: Invalid package name. Use lowercase, alphanumeric, and hyphens only."
echo "EXAMPLE: main-app-style-v1"
exit 1
fi
# 3. Validate design run exists
if [ ! -d "$design_run" ]; then
echo "ERROR: Design run not found: $design_run"
echo "HINT: Run '/workflow:ui-design:import-from-code' first to create design run"
exit 1
fi
# 4. Check required extraction files exist
required_files=(
"$design_run/style-extraction/style-1/design-tokens.json"
"$design_run/layout-extraction/layout-templates.json"
)
for file in "${required_files[@]}"; do
if [ ! -f "$file" ]; then
echo "ERROR: Required file not found: $file"
echo "HINT: Ensure design run has style and layout extraction results"
exit 1
fi
done
# 5. Setup output directory and validate
output_dir="${output_dir:-.workflow/reference_style}"
package_dir="${output_dir}/${package_name}"
# Check if package directory exists and is not empty
if [ -d "$package_dir" ] && [ "$(ls -A $package_dir 2>/dev/null)" ]; then
# Directory exists - check if it's a valid package or just a directory
if [ -f "$package_dir/metadata.json" ]; then
# Valid package - safe to overwrite
existing_version=$(jq -r '.version // "unknown"' "$package_dir/metadata.json" 2>/dev/null || echo "unknown")
echo "INFO: Overwriting existing package '$package_name' (version: $existing_version)"
else
# Directory exists but not a valid package
echo "ERROR: Directory '$package_dir' exists but is not a valid package"
echo "Use a different package name or remove the directory manually"
exit 1
fi
fi
mkdir -p "$package_dir"
echo "[Phase 0] Setup Complete"
echo " Design Run: $design_run"
echo " Package: $package_name"
echo " Output: $package_dir"
```
<!-- TodoWrite: Initialize todo list -->
**TodoWrite**:
```json
[
{"content": "Phase 0: 验证和准备", "status": "completed", "activeForm": "验证参数"},
{"content": "Phase 1: 准备组件数据", "status": "in_progress", "activeForm": "复制布局模板"},
{"content": "Phase 2: 生成预览页面", "status": "pending", "activeForm": "生成预览"}
]
```
---
### Phase 1: Prepare Component Data
**Purpose**: Copy required files from design run to package directory
**Operations**:
```bash
echo "[Phase 1] Preparing component data from design run"
# 1. Copy layout templates as component patterns
cp "${design_run}/layout-extraction/layout-templates.json" "${package_dir}/layout-templates.json"
if [ ! -f "${package_dir}/layout-templates.json" ]; then
echo "ERROR: Failed to copy layout templates"
exit 1
fi
# Count components from layout templates
component_count=$(jq -r '.layout_templates | length // 0' "${package_dir}/layout-templates.json" 2>/dev/null || echo 0)
echo " ✓ Layout templates copied (${component_count} components)"
# 2. Copy design tokens (required for preview generation)
cp "${design_run}/style-extraction/style-1/design-tokens.json" "${package_dir}/design-tokens.json"
if [ ! -f "${package_dir}/design-tokens.json" ]; then
echo "ERROR: Failed to copy design tokens"
exit 1
fi
echo " ✓ Design tokens copied"
# 3. Copy animation tokens if exists (optional)
if [ -f "${design_run}/animation-extraction/animation-tokens.json" ]; then
cp "${design_run}/animation-extraction/animation-tokens.json" "${package_dir}/animation-tokens.json"
echo " ✓ Animation tokens copied"
else
echo " ○ Animation tokens not found (optional)"
fi
echo "[Phase 1] Component data preparation complete"
```
<!-- TodoWrite: Mark Phase 1 complete, start Phase 2 -->
**TodoWrite**:
```json
[
{"content": "Phase 1: 准备组件数据", "status": "completed", "activeForm": "复制布局模板"},
{"content": "Phase 2: 生成预览页面", "status": "in_progress", "activeForm": "生成预览"}
]
```
---
### Phase 2: Preview Generation (Final Phase)
**Purpose**: Generate interactive multi-component preview (preview.html + preview.css)
**Agent Task**:
```javascript
Task(ui-design-agent): `
[PREVIEW_SHOWCASE_GENERATION]
Generate interactive multi-component showcase panel for reference package
PACKAGE_DIR: ${package_dir} | PACKAGE_NAME: ${package_name}
## Input Files (MUST READ ALL)
1. ${package_dir}/layout-templates.json (component layout patterns - REQUIRED)
2. ${package_dir}/design-tokens.json (design tokens - REQUIRED)
3. ${package_dir}/animation-tokens.json (optional, if exists)
## Generation Task
Create interactive showcase with these sections:
### Section 1: Colors
- Display all color categories as color swatches
- Show hex/rgb values
- Group by: brand, semantic, surface, text, border
### Section 2: Typography
- Display typography scale (font sizes, weights)
- Show typography combinations if available
- Include font family examples
### Section 3: Components
- Render all components from layout-templates.json (use layout_templates field)
- **Universal Components**: Display reusable multi-component showcases (buttons, inputs, cards, etc.)
- **Specialized Components**: Display module-specific components from code (feature-specific layouts, custom widgets)
- Display all variants side-by-side
- Show DOM structure with proper styling
- Include usage code snippets in <details> tags
- Clearly label component types (universal vs specialized)
### Section 4: Spacing & Layout
- Visual spacing scale
- Border radius examples
- Shadow depth examples
### Section 5: Animations (if available)
- Animation duration examples
- Easing function demonstrations
## Output Requirements
Generate 2 files:
1. ${package_dir}/preview.html
2. ${package_dir}/preview.css
### preview.html Structure:
- Complete standalone HTML file
- Responsive design with mobile-first approach
- Sticky navigation for sections
- Interactive component demonstrations
- Code snippets in collapsible <details> elements
- Footer with package metadata
### preview.css Structure:
- CSS Custom Properties from design-tokens.json
- Typography combination classes
- Component classes from layout-templates.json
- Preview page layout styles
- Interactive demo styles
## Critical Requirements
- ✅ Read ALL input files (layout-templates.json, design-tokens.json, animation-tokens.json if exists)
- ✅ Generate complete, interactive showcase HTML
- ✅ All CSS uses var() references to design tokens
- ✅ Display ALL components from layout-templates.json
- ✅ **Separate universal components from specialized components** in the showcase
- ✅ Display component DOM structures with proper styling
- ✅ Include usage code snippets
- ✅ Label each component type clearly (Universal / Specialized)
- ✅ Use Write() to save both files:
- ${package_dir}/preview.html
- ${package_dir}/preview.css
- ❌ NO external research or MCP calls
`
```
<!-- TodoWrite: Mark all complete -->
**TodoWrite**:
```json
[
{"content": "Phase 0: 验证和准备", "status": "completed", "activeForm": "验证参数"},
{"content": "Phase 1: 准备组件数据", "status": "completed", "activeForm": "复制布局模板"},
{"content": "Phase 2: 生成预览页面", "status": "completed", "activeForm": "生成预览"}
]
```
---
## Output Structure
```
${output_dir}/
└── ${package_name}/
├── layout-templates.json # Layout templates (copied from design run)
├── design-tokens.json # Design tokens (copied from design run)
├── animation-tokens.json # Animation tokens (copied from design run, optional)
├── preview.html # Interactive showcase (NEW)
└── preview.css # Showcase styling (NEW)
```
## Completion Message
```
✅ Preview package generated!
Package: {package_name}
Location: {package_dir}
Files:
✓ layout-templates.json {component_count} components
✓ design-tokens.json Design tokens
✓ animation-tokens.json Animation tokens {if exists: "✓" else: "○ (not found)"}
✓ preview.html Interactive showcase
✓ preview.css Showcase styling
Open preview:
file://{absolute_path_to_package_dir}/preview.html
```
## Error Handling
### Common Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Missing --design-run or --package-name | Required parameters not provided | Provide both flags |
| Invalid package name | Contains uppercase, special chars | Use lowercase, alphanumeric, hyphens only |
| Design run not found | Incorrect path or design run doesn't exist | Verify design run path, run import-from-code first |
| Missing extraction files | Design run incomplete | Ensure design run has style-extraction and layout-extraction results |
| Layout templates copy failed | layout-templates.json not found | Run import-from-code with Layout Agent first |
| Preview generation failed | Invalid design tokens | Check design-tokens.json format |
---

View File

@@ -1,20 +1,22 @@
---
name: style-extract
description: Extract design style from reference images or text prompts using Claude analysis with variant generation
argument-hint: "[--base-path <path>] [--session <id>] [--images "<glob>"] [--urls "<list>"] [--prompt "<desc>"] [--variants <count>] [--interactive]"
description: Extract design style from reference images or text prompts using Claude analysis with variant generation or refinement mode
argument-hint: "[--design-id <id>] [--session <id>] [--images "<glob>"] [--urls "<list>"] [--prompt "<desc>"] [--variants <count>] [--interactive] [--refine]"
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), AskUserQuestion(*), mcp__chrome-devtools__navigate_page(*), mcp__chrome-devtools__evaluate_script(*)
---
# Style Extraction Command
## Overview
Extract design style from reference images or text prompts using Claude's built-in analysis. Directly generates production-ready design systems with complete `design-tokens.json` and `style-guide.md` for each variant.
Extract design style from reference images or text prompts using Claude's built-in analysis. Supports two modes:
1. **Exploration Mode** (default): Generate multiple contrasting design variants
2. **Refinement Mode** (`--refine`): Refine a single existing design through detailed adjustments
**Strategy**: AI-Driven Design Space Exploration
- **Claude-Native**: 100% Claude analysis, no external tools
- **Direct Output**: Complete design systems (design-tokens.json + style-guide.md)
- **Direct Output**: Complete design systems (design-tokens.json)
- **Flexible Input**: Images, text prompts, or both (hybrid mode)
- **Maximum Contrast**: AI generates maximally divergent design directions
- **Dual Mode**: Exploration (multiple contrasting variants) or Refinement (single design fine-tuning)
- **Production-Ready**: WCAG AA compliant, OKLCH colors, semantic naming
## Phase 0: Setup & Input Validation
@@ -40,16 +42,41 @@ IF --urls:
ELSE:
has_urls = false
# Set variants count (default: 3, range: 1-5)
# Behavior: Generate N design directions → User multi-select → Generate selected variants
variants_count = --variants OR 3
VALIDATE: 1 <= variants_count <= 5
# Detect refinement mode
refine_mode = --refine OR false
# Set variants count
# Refinement mode: Force variants_count = 1 (ignore user-provided --variants)
# Exploration mode: Use --variants or default to 3 (range: 1-5)
IF refine_mode:
variants_count = 1
REPORT: "🔧 Refinement mode enabled: Will generate 1 refined design system"
ELSE:
variants_count = --variants OR 3
VALIDATE: 1 <= variants_count <= 5
REPORT: "🔍 Exploration mode: Will generate {variants_count} contrasting design directions"
# Determine base path with priority: --design-id > --session > auto-detect
if [ -n "$DESIGN_ID" ]; then
# Exact match by design ID
relative_path=$(find .workflow -name "${DESIGN_ID}" -type d -print -quit)
elif [ -n "$SESSION_ID" ]; then
# Latest in session
relative_path=$(find .workflow/WFS-$SESSION_ID -name "design-run-*" -type d -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2)
else
# Latest globally
relative_path=$(find .workflow -name "design-run-*" -type d -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2)
fi
# Validate and convert to absolute path
if [ -z "$relative_path" ] || [ ! -d "$relative_path" ]; then
echo "❌ ERROR: Design run not found"
echo "💡 HINT: Run '/workflow:ui-design:list' to see available design runs"
exit 1
fi
# Determine base path (auto-detect and convert to absolute)
relative_path=$(find .workflow -type d -name "design-run-*" -printf "%T@ %p\n" 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2)
base_path=$(cd "$relative_path" && pwd)
bash(test -d "$base_path" && echo "✓ Base path: $base_path" || echo "✗ Path not found")
# OR use --base-path / --session parameters
bash(echo "✓ Base path: $base_path")
```
### Step 2: Extract Computed Styles (URL Mode - Auto-Trigger)
@@ -136,60 +163,128 @@ IF exists: SKIP to completion
**Phase 0 Output**: `input_mode`, `base_path`, `extraction_mode`, `variants_count`, `loaded_images[]` or `prompt_guidance`, `has_urls`, `url_list[]`, `computed_styles_available`
## Phase 1: Design Direction Generation
## Phase 1: Design Direction or Refinement Options Generation
### Step 1: Load Project Context
```bash
# Load brainstorming context if available
bash(test -f {base_path}/.brainstorming/role analysis documents && cat it)
# Load existing design system if refinement mode
IF refine_mode:
existing_tokens = Read({base_path}/style-extraction/style-1/design-tokens.json)
```
### Step 2: Generate Design Direction Options (Agent Task 1)
### Step 2: Generate Options (Agent Task 1 - Mode-Specific)
**Executor**: `Task(ui-design-agent)`
Launch agent to generate `variants_count` design direction options with previews:
**Exploration Mode** (default): Generate contrasting design directions
**Refinement Mode** (`--refine`): Generate refinement options for existing design
```javascript
Task(ui-design-agent): `
[DESIGN_DIRECTION_GENERATION_TASK]
Generate {variants_count} maximally contrasting design directions with visual previews
// Conditional agent task based on refine_mode
IF NOT refine_mode:
// EXPLORATION MODE
Task(ui-design-agent): `
[DESIGN_DIRECTION_GENERATION_TASK]
Generate {variants_count} maximally contrasting design directions with visual previews
SESSION: {session_id} | MODE: explore | BASE_PATH: {base_path}
SESSION: {session_id} | MODE: explore | BASE_PATH: {base_path}
## Input Analysis
- User prompt: {prompt_guidance}
- Visual references: {loaded_images if available}
- Project context: {brainstorming_context if available}
## Input Analysis
- User prompt: {prompt_guidance}
- Visual references: {loaded_images if available}
- Project context: {brainstorming_context if available}
## Analysis Rules
- Analyze 6D attribute space: color saturation, visual weight, formality, organic/geometric, innovation, density
- Generate {variants_count} directions with MAXIMUM contrast
- Each direction must be distinctly different (min distance score: 0.7)
## Analysis Rules
- Analyze 6D attribute space: color saturation, visual weight, formality, organic/geometric, innovation, density
- Generate {variants_count} directions with MAXIMUM contrast
- Each direction must be distinctly different (min distance score: 0.7)
## Generate for EACH Direction
1. **Core Philosophy**:
- philosophy_name (2-3 words, e.g., "Minimalist & Airy")
- design_attributes (6D scores 0-1)
- search_keywords (3-5 keywords)
- anti_keywords (2-3 keywords to avoid)
- rationale (why this is distinct from others)
## Generate for EACH Direction
1. **Core Philosophy**:
- philosophy_name (2-3 words, e.g., "Minimalist & Airy")
- design_attributes (6D scores 0-1)
- search_keywords (3-5 keywords)
- anti_keywords (2-3 keywords to avoid)
- rationale (why this is distinct from others)
2. **Visual Preview Elements**:
- primary_color (OKLCH format)
- secondary_color (OKLCH format)
- accent_color (OKLCH format)
- font_family_heading (specific font name)
- font_family_body (specific font name)
- border_radius_base (e.g., "0.5rem")
- mood_description (1-2 sentences describing the feel)
2. **Visual Preview Elements**:
- primary_color (OKLCH format)
- secondary_color (OKLCH format)
- accent_color (OKLCH format)
- font_family_heading (specific font name)
- font_family_body (specific font name)
- border_radius_base (e.g., "0.5rem")
- mood_description (1-2 sentences describing the feel)
## Output
Write single JSON file: {base_path}/.intermediates/style-analysis/analysis-options.json
## Output
Write single JSON file: {base_path}/.intermediates/style-analysis/analysis-options.json
Use schema from INTERACTIVE-DATA-SPEC.md (Style Extract: analysis-options.json)
Use schema from INTERACTIVE-DATA-SPEC.md (Style Extract: analysis-options.json)
CRITICAL: Use Write() tool immediately after generating complete JSON
`
CRITICAL: Use Write() tool immediately after generating complete JSON
`
ELSE:
// REFINEMENT MODE
Task(ui-design-agent): `
[DESIGN_REFINEMENT_OPTIONS_TASK]
Generate refinement options for existing design system
SESSION: {session_id} | MODE: refine | BASE_PATH: {base_path}
## Existing Design System
- design-tokens.json: {existing_tokens}
## Input Guidance
- User prompt: {prompt_guidance}
- Visual references: {loaded_images if available}
## Refinement Categories
Generate 8-12 refinement options across these categories:
1. **Intensity/Degree Adjustments** (2-3 options):
- Color intensity: more vibrant ↔ more muted
- Visual weight: bolder ↔ lighter
- Density: more compact ↔ more spacious
2. **Specific Attribute Tuning** (3-4 options):
- Border radius: sharper corners ↔ rounder edges
- Shadow depth: subtler shadows ↔ deeper elevation
- Typography scale: tighter scale ↔ more contrast
- Spacing scale: tighter rhythm ↔ more breathing room
3. **Context-Specific Variations** (2-3 options):
- Dark mode optimization
- Mobile-specific adjustments
- High-contrast accessibility mode
4. **Component-Level Customization** (1-2 options):
- Button styling emphasis
- Card/container treatment
- Form input refinements
## Output Format
Each option:
- category: "intensity|attribute|context|component"
- option_id: unique identifier
- label: Short descriptive name (e.g., "More Vibrant Colors")
- description: What changes (2-3 sentences)
- preview_changes: Key token adjustments preview
- impact_scope: Which tokens affected
## Output
Write single JSON file: {base_path}/.intermediates/style-analysis/analysis-options.json
Use refinement schema:
{
"mode": "refinement",
"base_design": "style-1",
"refinement_options": [array of refinement options]
}
CRITICAL: Use Write() tool immediately after generating complete JSON
`
```
### Step 3: Verify Options File Created
@@ -206,7 +301,9 @@ bash(cat {base_path}/.intermediates/style-analysis/analysis-options.json | grep
## Phase 1.5: User Confirmation (Optional - Triggered by --interactive)
**Purpose**: Allow user to select preferred design direction(s) before generating full design systems
**Purpose**:
- **Exploration Mode**: Allow user to select preferred design direction(s)
- **Refinement Mode**: Allow user to select refinement options to apply
**Trigger Condition**: Execute this phase ONLY if `--interactive` flag is present
@@ -215,21 +312,31 @@ bash(cat {base_path}/.intermediates/style-analysis/analysis-options.json | grep
# Skip this entire phase if --interactive flag is not present
IF NOT --interactive:
SKIP to Phase 2
REPORT: " Non-interactive mode: Will generate all {variants_count} variants"
IF refine_mode:
REPORT: " Non-interactive refinement mode: Will apply all suggested refinements"
ELSE:
REPORT: " Non-interactive mode: Will generate all {variants_count} variants"
REPORT: "🎯 Interactive mode enabled: User selection required"
```
### Step 2: Load and Present Options
### Step 2: Load and Present Options (Mode-Specific)
```bash
# Read options file
options = Read({base_path}/.intermediates/style-analysis/analysis-options.json)
# Parse design directions
design_directions = options.design_directions
# Branch based on mode
IF NOT refine_mode:
# EXPLORATION MODE
design_directions = options.design_directions
ELSE:
# REFINEMENT MODE
refinement_options = options.refinement_options
```
### Step 2: Present Options to User
### Step 3: Present Options to User (Mode-Specific)
**Exploration Mode**:
```
📋 Design Direction Options
@@ -262,14 +369,39 @@ Please select the direction(s) you'd like to develop into complete design system
═══════════════════════════════════════════════════
```
### Step 3: Capture User Selection and Update Analysis JSON
**Refinement Mode**:
```
📋 Design Refinement Options
We've analyzed your existing design system and generated refinement options.
Please select the refinement(s) you'd like to apply.
Base Design: style-1
{FOR each option in refinement_options grouped by category:
━━━ {category_name} ━━━
{FOR each refinement in category_options:
[{refinement.option_id}] {refinement.label}
{refinement.description}
Preview: {refinement.preview_changes}
Affects: {refinement.impact_scope}
}
}
═══════════════════════════════════════════════════
```
### Step 4: Capture User Selection and Update Analysis JSON
**Exploration Mode Interaction**:
```javascript
// Use AskUserQuestion tool for multi-selection
AskUserQuestion({
questions: [{
question: "Which design direction(s) would you like to develop into complete design systems?",
header: "Style Choice",
multiSelect: true, // Multi-selection enabled (default behavior)
multiSelect: true, // Multi-selection enabled
options: [
{FOR each direction:
label: "Option {direction.index}: {direction.philosophy_name}",
@@ -279,7 +411,7 @@ AskUserQuestion({
}]
})
// Parse user response (array of selections, e.g., ["Option 1: ...", "Option 3: ..."])
// Parse user response (array of selections)
selected_options = user_answer
// Check for user cancellation
@@ -287,33 +419,73 @@ IF selected_options == null OR selected_options.length == 0:
REPORT: "⚠️ User canceled selection. Workflow terminated."
EXIT workflow
// Extract option indices from array
// Extract option indices
selected_indices = []
FOR each selected_option_text IN selected_options:
match = selected_option_text.match(/Option (\d+):/)
IF match:
selected_indices.push(parseInt(match[1]))
ELSE:
ERROR: "Invalid selection format. Expected 'Option N: ...' format"
EXIT workflow
REPORT: "✅ Selected {selected_indices.length} design direction(s)"
// Update analysis-options.json with user selection
// Update analysis-options.json
options_file = Read({base_path}/.intermediates/style-analysis/analysis-options.json)
options_file.user_selection = {
"selected_at": NOW(),
"selected_indices": selected_indices,
"selection_count": selected_indices.length
}
// Write updated file back
Write({base_path}/.intermediates/style-analysis/analysis-options.json, JSON.stringify(options_file, indent=2))
REPORT: "✅ Updated analysis-options.json with user selection"
```
### Step 4: Confirmation Message
**Refinement Mode Interaction**:
```javascript
// Use AskUserQuestion tool for multi-selection of refinements
AskUserQuestion({
questions: [{
question: "Which refinement(s) would you like to apply to your design system?",
header: "Refinements",
multiSelect: true, // Multi-selection enabled
options: [
{FOR each refinement:
label: "{refinement.label}",
description: "{refinement.description} (Affects: {refinement.impact_scope})"
}
]
}]
})
// Parse user response
selected_refinements = user_answer
// Check for user cancellation
IF selected_refinements == null OR selected_refinements.length == 0:
REPORT: "⚠️ User canceled selection. Workflow terminated."
EXIT workflow
// Extract refinement option_ids
selected_option_ids = []
FOR each selected_text IN selected_refinements:
# Match against refinement labels to find option_ids
FOR each refinement IN refinement_options:
IF refinement.label IN selected_text:
selected_option_ids.push(refinement.option_id)
REPORT: "✅ Selected {selected_option_ids.length} refinement(s)"
// Update analysis-options.json
options_file = Read({base_path}/.intermediates/style-analysis/analysis-options.json)
options_file.user_selection = {
"selected_at": NOW(),
"selected_option_ids": selected_option_ids,
"selection_count": selected_option_ids.length
}
Write({base_path}/.intermediates/style-analysis/analysis-options.json, JSON.stringify(options_file, indent=2))
```
### Step 5: Confirmation Message (Mode-Specific)
**Exploration Mode**:
```
✅ Selection recorded!
@@ -325,7 +497,19 @@ You selected {selected_indices.length} design direction(s):
Proceeding to generate {selected_indices.length} complete design system(s)...
```
**Output**: Updated `analysis-options.json` with user's multi-selection embedded
**Refinement Mode**:
```
✅ Selection recorded!
You selected {selected_option_ids.length} refinement(s):
{FOR each id IN selected_option_ids:
• {refinement_by_id[id].label} ({refinement_by_id[id].category})
}
Proceeding to apply refinements and generate updated design system...
```
**Output**: Updated `analysis-options.json` with user's selection embedded
## Phase 2: Design System Generation (Agent Task 2)
@@ -425,28 +609,15 @@ FOR variant_index IN 1..actual_variants_count:
${extraction_mode == "explore" && refinements.enabled ? "- Apply user refinements where specified" : ""}
- Common Tailwind CSS usage patterns in project (if extracting from existing project)
2. **style-guide.md**:
- Design philosophy (${extraction_mode == "explore" ? "expand on: " + selected_direction.philosophy_name : "describe the reference design"})
- Complete color system documentation with accessibility notes
- Typography scale and usage guidelines
- Typography Combinations section: Document each preset (heading-primary, heading-secondary, body-regular, body-emphasis, caption, label) with usage context and code examples
- Spacing system explanation
- Opacity & Transparency section: Opacity scale usage, common use cases (disabled states, overlays, hover effects), accessibility considerations
- Shadows & Elevation section: Shadow hierarchy and semantic usage
- Component Styles section: Document button, card, and input variants with code examples and visual descriptions
- Border Radius system and semantic usage
- Component examples and usage patterns
- Common Tailwind CSS patterns (if applicable)
## Critical Requirements
- ✅ Use Write() tool immediately for each file
- ✅ Write to style-{variant_index}/ directory
- ❌ NO external research or MCP calls (pure AI generation)
- ✅ Can use Exa MCP to research modern design patterns and obtain code examples (Explore/Text mode)
- ✅ Maintain consistency with user-selected direction
`
```
**Output**: {actual_variants_count} parallel agent tasks generate 2 files each (design-tokens.json, style-guide.md)
**Output**: {actual_variants_count} parallel agent tasks generate design-tokens.json for each variant
## Phase 3: Verify Output
@@ -504,7 +675,7 @@ Design Direction Selection:
Generated Files:
{base_path}/style-extraction/
└── style-1/ (design-tokens.json, style-guide.md)
└── style-1/design-tokens.json
{IF computed_styles_available:
Intermediate Analysis:
@@ -569,8 +740,7 @@ bash(test -f {base_path}/.intermediates/style-analysis/analysis-options.json &&
│ └── analysis-options.json # Design direction options + user selection (explore mode only)
└── style-extraction/ # Final design system
└── style-1/
── design-tokens.json # Production-ready design tokens
└── style-guide.md # Design philosophy and usage guide
── design-tokens.json # Production-ready design tokens
```
## design-tokens.json Format
@@ -653,10 +823,4 @@ ERROR: Claude JSON parsing error
- **Production-Ready** - OKLCH colors, WCAG AA compliance, semantic naming
- **Agent-Driven** - Autonomous multi-file generation with ui-design-agent
## Integration
**Input**: Reference images or text prompts
**Output**: `style-extraction/style-{N}/` with design-tokens.json + style-guide.md
**Next**: `/workflow:ui-design:layout-extract --session {session_id}` OR `/workflow:ui-design:generate --session {session_id}`
**Note**: This command extracts visual style (colors, typography, spacing) and generates production-ready design systems. For layout structure extraction, use `/workflow:ui-design:layout-extract`.

View File

@@ -89,8 +89,8 @@ Update `.brainstorming/role analysis documents` with design system references.
## UI/UX Guidelines
### Design System Reference
**Finalized Design Tokens**: @../design-{run_id}/{design_tokens_path}
**Style Guide**: @../design-{run_id}/{style_guide_path}
**Finalized Design Tokens**: @../{design_id}/{design_tokens_path}
**Style Guide**: @../{design_id}/{style_guide_path}
**Design System Mode**: {design_system_mode}
### Implementation Requirements
@@ -101,12 +101,12 @@ Update `.brainstorming/role analysis documents` with design system references.
### Reference Prototypes
{FOR each selected_prototype:
- **{page_name}**: @../design-{run_id}/prototypes/{prototype}.html | Layout: {layout_strategy from notes}
- **{page_name}**: @../{design_id}/prototypes/{prototype}.html | Layout: {layout_strategy from notes}
}
### Design System Assets
```json
{"design_tokens": "design-{run_id}/{design_tokens_path}", "style_guide": "design-{run_id}/{style_guide_path}", "design_system_mode": "{design_system_mode}", "prototypes": [{FOR each: "design-{run_id}/prototypes/{prototype}.html"}]}
{"design_tokens": "{design_id}/{design_tokens_path}", "style_guide": "{design_id}/{style_guide_path}", "design_system_mode": "{design_system_mode}", "prototypes": [{FOR each: "{design_id}/prototypes/{prototype}.html"}]}
```
```
@@ -145,9 +145,9 @@ IF selected_list: pm_files = Glob(".workflow/WFS-{session}/.brainstorming/produc
```markdown
## Design System Implementation Reference
**Design Tokens**: @../../design-{run_id}/{design_tokens_path}
**Style Guide**: @../../design-{run_id}/{style_guide_path}
**Prototypes**: {FOR each: @../../design-{run_id}/prototypes/{prototype}.html}
**Design Tokens**: @../../{design_id}/{design_tokens_path}
**Style Guide**: @../../{design_id}/{style_guide_path}
**Prototypes**: {FOR each: @../../{design_id}/prototypes/{prototype}.html}
*Reference added by /workflow:ui-design:update*
```
@@ -156,8 +156,8 @@ IF selected_list: pm_files = Glob(".workflow/WFS-{session}/.brainstorming/produc
```markdown
## Animation & Interaction Reference
**Animations**: @../../design-{run_id}/animation-extraction/animation-tokens.json
**Prototypes**: {FOR each: @../../design-{run_id}/prototypes/{prototype}.html}
**Animations**: @../../{design_id}/animation-extraction/animation-tokens.json
**Prototypes**: {FOR each: @../../{design_id}/prototypes/{prototype}.html}
*Reference added by /workflow:ui-design:update*
```
@@ -166,7 +166,7 @@ IF selected_list: pm_files = Glob(".workflow/WFS-{session}/.brainstorming/produc
```markdown
## Layout Structure Reference
**Layout Templates**: @../../design-{run_id}/layout-extraction/layout-templates.json
**Layout Templates**: @../../{design_id}/layout-extraction/layout-templates.json
*Reference added by /workflow:ui-design:update*
```
@@ -175,7 +175,7 @@ IF selected_list: pm_files = Glob(".workflow/WFS-{session}/.brainstorming/produc
```markdown
## Prototype Validation Reference
**Prototypes**: {FOR each: @../../design-{run_id}/prototypes/{prototype}.html}
**Prototypes**: {FOR each: @../../{design_id}/prototypes/{prototype}.html}
*Reference added by /workflow:ui-design:update*
```
@@ -197,8 +197,8 @@ Create or update `.brainstorming/ui-designer/design-system-reference.md`:
## Design System Integration
This style guide references the finalized design system from the design refinement phase.
**Design Tokens**: @../../design-{run_id}/{design_tokens_path}
**Style Guide**: @../../design-{run_id}/{style_guide_path}
**Design Tokens**: @../../{design_id}/{design_tokens_path}
**Style Guide**: @../../{design_id}/{style_guide_path}
**Design System Mode**: {design_system_mode}
## Implementation Guidelines
@@ -209,13 +209,13 @@ This style guide references the finalized design system from the design refineme
## Reference Prototypes
{FOR each selected_prototype:
- **{page_name}**: @../../design-{run_id}/prototypes/{prototype}.html
- **{page_name}**: @../../{design_id}/prototypes/{prototype}.html
}
## Token System
For complete token definitions and usage examples, see:
- Design Tokens: @../../design-{run_id}/{design_tokens_path}
- Style Guide: @../../design-{run_id}/{style_guide_path}
- Design Tokens: @../../{design_id}/{design_tokens_path}
- Style Guide: @../../{design_id}/{style_guide_path}
---
*Auto-generated by /workflow:ui-design:update | Last updated: {timestamp}*
@@ -271,24 +271,24 @@ Next: /workflow:plan [--agent] "<task description>"
**@ Reference Format** (role analysis documents):
```
@../design-{run_id}/style-extraction/style-1/design-tokens.json
@../design-{run_id}/style-extraction/style-1/style-guide.md
@../design-{run_id}/prototypes/{prototype}.html
@../{design_id}/style-extraction/style-1/design-tokens.json
@../{design_id}/style-extraction/style-1/style-guide.md
@../{design_id}/prototypes/{prototype}.html
```
**@ Reference Format** (ui-designer/design-system-reference.md):
```
@../../design-{run_id}/style-extraction/style-1/design-tokens.json
@../../design-{run_id}/style-extraction/style-1/style-guide.md
@../../design-{run_id}/prototypes/{prototype}.html
@../../{design_id}/style-extraction/style-1/design-tokens.json
@../../{design_id}/style-extraction/style-1/style-guide.md
@../../{design_id}/prototypes/{prototype}.html
```
**@ Reference Format** (role analysis.md files):
```
@../../design-{run_id}/style-extraction/style-1/design-tokens.json
@../../design-{run_id}/animation-extraction/animation-tokens.json
@../../design-{run_id}/layout-extraction/layout-templates.json
@../../design-{run_id}/prototypes/{prototype}.html
@../../{design_id}/style-extraction/style-1/design-tokens.json
@../../{design_id}/animation-extraction/animation-tokens.json
@../../{design_id}/layout-extraction/layout-templates.json
@../../{design_id}/prototypes/{prototype}.html
```
## Integration with /workflow:plan
@@ -307,9 +307,9 @@ After this update, `/workflow:plan` will discover design assets through:
"task_id": "IMPL-001",
"context": {
"design_system": {
"tokens": "design-{run_id}/style-extraction/style-1/design-tokens.json",
"style_guide": "design-{run_id}/style-extraction/style-1/style-guide.md",
"prototypes": ["design-{run_id}/prototypes/dashboard-variant-1.html"]
"tokens": "{design_id}/style-extraction/style-1/design-tokens.json",
"style_guide": "{design_id}/style-extraction/style-1/style-guide.md",
"prototypes": ["{design_id}/prototypes/dashboard-variant-1.html"]
}
}
}

View File

@@ -686,8 +686,8 @@ All workflows use the same file structure definition regardless of complexity. *
│ ├── execute-*-[timestamp].md # Ad-hoc implementation logs
│ └── codex-execute-*-[timestamp].md # Multi-stage execution logs
├── [.design/] # Standalone UI design outputs (created when needed)
│ └── run-[timestamp]/ # Timestamped design runs without session
├── [design-run-*/] # Standalone UI design outputs (created when needed)
│ └── (timestamped)/ # Timestamped design runs without session
│ ├── .intermediates/ # Intermediate analysis files
│ │ ├── style-analysis/ # Style analysis data
│ │ │ ├── computed-styles.json # Extracted CSS values
@@ -749,7 +749,7 @@ All workflows use the same file structure definition regardless of complexity. *
- **On-Demand Creation**: Other directories created when first needed
- **Dynamic Files**: Subtask JSON files created during task decomposition
- **Scratchpad Usage**: `.scratchpad/` created when CLI commands run without active session
- **Design Usage**: `design-{timestamp}/` created by UI design workflows, `.design/` for standalone design runs
- **Design Usage**: `design-{timestamp}/` created by UI design workflows in `.workflow/` directly for standalone design runs
- **Intermediate Files**: `.intermediates/` contains analysis data (style/layout) separate from final deliverables
- **Layout Templates**: `layout-extraction/layout-templates.json` contains structural templates for UI assembly