From 836bf4cd1c5b2b49873c002eb212811be9b81228 Mon Sep 17 00:00:00 2001 From: catlog22 Date: Tue, 11 Nov 2025 20:53:42 +0800 Subject: [PATCH] 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. --- .../commands/workflow/ui-design/capture.md | 4 +- .../workflow/ui-design/explore-auto.md | 2 +- .../workflow/ui-design/explore-layers.md | 2 +- .../workflow/ui-design/imitate-auto.md | 6 +- .claude/scripts/ui-instantiate-prototypes.sh | 6 +- .../command-guide/index/all-commands.json | 90 +- .../command-guide/index/by-category.json | 90 +- .../command-guide/index/by-use-case.json | 90 +- .../index/essential-commands.json | 4 +- .../reference/agents/cli-planning-agent.md | 553 ++++++++ .../reference/agents/test-fix-agent.md | 160 ++- .../reference/agents/ui-design-agent.md | 873 +++++++------ .../reference/commands/cli/analyze.md | 103 +- .../reference/commands/cli/chat.md | 85 +- .../reference/commands/cli/execute.md | 135 +- .../commands/cli/mode/bug-diagnosis.md | 100 +- .../commands/cli/mode/code-analysis.md | 107 +- .../reference/commands/cli/mode/plan.md | 102 +- .../commands/memory/style-skill-memory.md | 534 ++++++++ .../workflow/brainstorm/auto-parallel.md | 207 ++- .../reference/commands/workflow/plan.md | 216 +++- .../reference/commands/workflow/tdd-plan.md | 243 +++- .../commands/workflow/test-cycle-execute.md | 362 ++++-- .../commands/workflow/test-fix-gen.md | 247 +++- .../reference/commands/workflow/test-gen.md | 214 ++- .../workflow/ui-design/animation-extract.md | 1151 +++++++++++------ .../commands/workflow/ui-design/capture.md | 37 +- .../workflow/ui-design/codify-style.md | 678 ++++++++++ .../workflow/ui-design/explore-auto.md | 412 +++--- .../workflow/ui-design/explore-layers.md | 32 +- .../commands/workflow/ui-design/generate.md | 253 ++-- .../workflow/ui-design/imitate-auto.md | 625 +++++---- .../workflow/ui-design/import-from-code.md | 818 ++++-------- .../workflow/ui-design/layout-extract.md | 254 +++- .../commands/workflow/ui-design/list.md | 174 +++ .../ui-design/reference-page-generator.md | 327 +++++ .../workflow/ui-design/style-extract.md | 348 +++-- .../commands/workflow/ui-design/update.md | 58 +- .claude/workflows/workflow-architecture.md | 6 +- 39 files changed, 6646 insertions(+), 3062 deletions(-) create mode 100644 .claude/skills/command-guide/reference/agents/cli-planning-agent.md create mode 100644 .claude/skills/command-guide/reference/commands/memory/style-skill-memory.md create mode 100644 .claude/skills/command-guide/reference/commands/workflow/ui-design/codify-style.md create mode 100644 .claude/skills/command-guide/reference/commands/workflow/ui-design/list.md create mode 100644 .claude/skills/command-guide/reference/commands/workflow/ui-design/reference-page-generator.md diff --git a/.claude/commands/workflow/ui-design/capture.md b/.claude/commands/workflow/ui-design/capture.md index 2dc6f4db..c080ee09 100644 --- a/.claude/commands/workflow/ui-design/capture.md +++ b/.claude/commands/workflow/ui-design/capture.md @@ -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 diff --git a/.claude/commands/workflow/ui-design/explore-auto.md b/.claude/commands/workflow/ui-design/explore-auto.md index 45fab5e2..c49f2f88 100644 --- a/.claude/commands/workflow/ui-design/explore-auto.md +++ b/.claude/commands/workflow/ui-design/explore-auto.md @@ -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") diff --git a/.claude/commands/workflow/ui-design/explore-layers.md b/.claude/commands/workflow/ui-design/explore-layers.md index ebf78e0d..c0f157ce 100644 --- a/.claude/commands/workflow/ui-design/explore-layers.md +++ b/.claude/commands/workflow/ui-design/explore-layers.md @@ -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 diff --git a/.claude/commands/workflow/ui-design/imitate-auto.md b/.claude/commands/workflow/ui-design/imitate-auto.md index 0b00186a..8bcc4472 100644 --- a/.claude/commands/workflow/ui-design/imitate-auto.md +++ b/.claude/commands/workflow/ui-design/imitate-auto.md @@ -69,7 +69,7 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*) - `--session `: 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 diff --git a/.claude/scripts/ui-instantiate-prototypes.sh b/.claude/scripts/ui-instantiate-prototypes.sh index 89245009..21fadd22 100644 --- a/.claude/scripts/ui-instantiate-prototypes.sh +++ b/.claude/scripts/ui-instantiate-prototypes.sh @@ -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 } diff --git a/.claude/skills/command-guide/index/all-commands.json b/.claude/skills/command-guide/index/all-commands.json index a0cc41d9..57d45e75 100644 --- a/.claude/skills/command-guide/index/all-commands.json +++ b/.claude/skills/command-guide/index/all-commands.json @@ -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 ] [--session ] [--urls \"\"] [--mode ] [--focus \"\"]", + "description": "Extract animation and transition patterns from prompt inference and image references for design system documentation", + "arguments": "[--design-id ] [--session ] [--images \"\"] [--focus \"\"] [--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 ] [--session ]", "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": " [--package-name ] [--output-dir ] [--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 \"\"] [--images \"\"] [--targets \"\"] [--target-type \"page|component\"] [--session ] [--style-variants ] [--layout-variants ] [--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 \"\"] [--targets \"\"] [--target-type \"page|component\"] [--session ] [--style-variants ] [--layout-variants ] [--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 --depth <1-5> [--session id] [--base-path path]", + "arguments": "--url --depth <1-5> [--design-id ] [--session ]", "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 ] [--session ]", + "description": "Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation", + "arguments": "[--design-id ] [--session ]", "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 \"\" [--capture-mode ] [--depth <1-5>] [--session ] [--prompt \"\"]", + "description": "UI design workflow with direct code/image input for design token extraction and prototype generation", + "arguments": "[--input \"\"] [--session ]", "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 ] [--source ] [--css \\\"\\\"] [--js \\\"\\\"] [--scss \\\"\\\"] [--html \\\"\\\"] [--style-files \\\"\\\"] [--session ]", + "description": "Import design system from code files (CSS/JS/HTML/SCSS) with automatic file discovery and parallel agent analysis", + "arguments": "[--design-id ] [--session ] [--source ]", "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 ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--targets \"\"] [--variants ] [--device-type ] [--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 ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--targets \"\"] [--variants ] [--device-type ] [--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 ]", + "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 ] [--package-name ] [--output-dir ]", + "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 ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--variants ] [--interactive]", + "description": "Extract design style from reference images or text prompts using Claude analysis with variant generation or refinement mode", + "arguments": "[--design-id ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--variants ] [--interactive] [--refine]", "category": "workflow", "subcategory": "ui-design", "usage_scenario": "general", diff --git a/.claude/skills/command-guide/index/by-category.json b/.claude/skills/command-guide/index/by-category.json index 4809e4ec..6f6383de 100644 --- a/.claude/skills/command-guide/index/by-category.json +++ b/.claude/skills/command-guide/index/by-category.json @@ -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 ] [--session ] [--urls \"\"] [--mode ] [--focus \"\"]", + "description": "Extract animation and transition patterns from prompt inference and image references for design system documentation", + "arguments": "[--design-id ] [--session ] [--images \"\"] [--focus \"\"] [--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 ] [--session ]", "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": " [--package-name ] [--output-dir ] [--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 \"\"] [--images \"\"] [--targets \"\"] [--target-type \"page|component\"] [--session ] [--style-variants ] [--layout-variants ] [--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 \"\"] [--targets \"\"] [--target-type \"page|component\"] [--session ] [--style-variants ] [--layout-variants ] [--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 --depth <1-5> [--session id] [--base-path path]", + "arguments": "--url --depth <1-5> [--design-id ] [--session ]", "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 ] [--session ]", + "description": "Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation", + "arguments": "[--design-id ] [--session ]", "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 \"\" [--capture-mode ] [--depth <1-5>] [--session ] [--prompt \"\"]", + "description": "UI design workflow with direct code/image input for design token extraction and prototype generation", + "arguments": "[--input \"\"] [--session ]", "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 ] [--source ] [--css \\\"\\\"] [--js \\\"\\\"] [--scss \\\"\\\"] [--html \\\"\\\"] [--style-files \\\"\\\"] [--session ]", + "description": "Import design system from code files (CSS/JS/HTML/SCSS) with automatic file discovery and parallel agent analysis", + "arguments": "[--design-id ] [--session ] [--source ]", "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 ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--targets \"\"] [--variants ] [--device-type ] [--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 ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--targets \"\"] [--variants ] [--device-type ] [--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 ]", + "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 ] [--package-name ] [--output-dir ]", + "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 ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--variants ] [--interactive]", + "description": "Extract design style from reference images or text prompts using Claude analysis with variant generation or refinement mode", + "arguments": "[--design-id ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--variants ] [--interactive] [--refine]", "category": "workflow", "subcategory": "ui-design", "usage_scenario": "general", diff --git a/.claude/skills/command-guide/index/by-use-case.json b/.claude/skills/command-guide/index/by-use-case.json index 48fe0729..450d3f0b 100644 --- a/.claude/skills/command-guide/index/by-use-case.json +++ b/.claude/skills/command-guide/index/by-use-case.json @@ -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 ] [--session ] [--urls \"\"] [--mode ] [--focus \"\"]", + "description": "Extract animation and transition patterns from prompt inference and image references for design system documentation", + "arguments": "[--design-id ] [--session ] [--images \"\"] [--focus \"\"] [--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 ] [--session ]", "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 \"\"] [--images \"\"] [--targets \"\"] [--target-type \"page|component\"] [--session ] [--style-variants ] [--layout-variants ] [--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 \"\"] [--targets \"\"] [--target-type \"page|component\"] [--session ] [--style-variants ] [--layout-variants ] [--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 --depth <1-5> [--session id] [--base-path path]", + "arguments": "--url --depth <1-5> [--design-id ] [--session ]", "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 \"\" [--capture-mode ] [--depth <1-5>] [--session ] [--prompt \"\"]", + "description": "UI design workflow with direct code/image input for design token extraction and prototype generation", + "arguments": "[--input \"\"] [--session ]", "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 ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--targets \"\"] [--variants ] [--device-type ] [--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 ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--targets \"\"] [--variants ] [--device-type ] [--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 ]", + "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 ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--variants ] [--interactive]", + "description": "Extract design style from reference images or text prompts using Claude analysis with variant generation or refinement mode", + "arguments": "[--design-id ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--variants ] [--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 ] [--session ]", + "description": "Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation", + "arguments": "[--design-id ] [--session ]", "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": " [--package-name ] [--output-dir ] [--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 ] [--source ] [--css \\\"\\\"] [--js \\\"\\\"] [--scss \\\"\\\"] [--html \\\"\\\"] [--style-files \\\"\\\"] [--session ]", + "description": "Import design system from code files (CSS/JS/HTML/SCSS) with automatic file discovery and parallel agent analysis", + "arguments": "[--design-id ] [--session ] [--source ]", "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 ] [--package-name ] [--output-dir ]", + "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", diff --git a/.claude/skills/command-guide/index/essential-commands.json b/.claude/skills/command-guide/index/essential-commands.json index 00238d4b..e1fe7b39 100644 --- a/.claude/skills/command-guide/index/essential-commands.json +++ b/.claude/skills/command-guide/index/essential-commands.json @@ -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", diff --git a/.claude/skills/command-guide/reference/agents/cli-planning-agent.md b/.claude/skills/command-guide/reference/agents/cli-planning-agent.md new file mode 100644 index 00000000..646e88f4 --- /dev/null +++ b/.claude/skills/command-guide/reference/agents/cli-planning-agent.md @@ -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" diff --git a/.claude/skills/command-guide/reference/agents/test-fix-agent.md b/.claude/skills/command-guide/reference/agents/test-fix-agent.md index 13f42731..6f77c7dd 100644 --- a/.claude/skills/command-guide/reference/agents/test-fix-agent.md +++ b/.claude/skills/command-guide/reference/agents/test-fix-agent.md @@ -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:** diff --git a/.claude/skills/command-guide/reference/agents/ui-design-agent.md b/.claude/skills/command-guide/reference/agents/ui-design-agent.md index faf6fce0..01af1d9a 100644 --- a/.claude/skills/command-guide/reference/agents/ui-design-agent.md +++ b/.claude/skills/command-guide/reference/agents/ui-design-agent.md @@ -11,7 +11,7 @@ description: | - Cross-platform responsive design (mobile, tablet, desktop) Integration points: - - Exa MCP: Design trend research, modern UI patterns, implementation best practices + - Exa MCP: Design trend research (web search), code implementation examples (code search), accessibility patterns color: orange --- @@ -30,149 +30,83 @@ You execute 6 distinct task types organized into 3 patterns. Each task includes - `[DESIGN_DIRECTION_GENERATION_TASK]` - Generate design direction options - `[LAYOUT_CONCEPT_GENERATION_TASK]` - Generate layout concept options -**Common Process**: -1. **Analyze Input**: User prompt, visual references, project context -2. **Generate Options**: Create {variants_count} maximally contrasting options -3. **Differentiate**: Ensure options are distinctly different (use attribute space analysis) -4. **Write File**: Single JSON file `analysis-options.json` with all options +**Process**: +1. Analyze Input: User prompt, visual references, project context +2. Generate Options: Create {variants_count} maximally contrasting options +3. Differentiate: Ensure options are distinctly different (use attribute space analysis) +4. Write File: Single JSON file `analysis-options.json` with all options -**Design Direction Generation**: -- **Input**: Prompt guidance, visual references (images/URLs), project context -- **Output**: `{base_path}/.intermediates/style-analysis/analysis-options.json` -- **Content**: Design philosophies with 6D attributes (color saturation, visual weight, formality, organic/geometric, innovation, density), search keywords, visual previews (colors, fonts, border radius) -- **Goal**: Maximum contrast between options for clear user choice +**Design Direction**: 6D attributes (color saturation, visual weight, formality, organic/geometric, innovation, density), search keywords, visual previews → `{base_path}/.intermediates/style-analysis/analysis-options.json` -**Layout Concept Generation**: -- **Input**: Target specifications, device type, layout inspirations, visual references, DOM structure (if available) -- **Output**: `{base_path}/.intermediates/layout-analysis/analysis-options.json` -- **Content**: Layout concepts with structural patterns (grid-3col, flex-row, etc.), component arrangements, ASCII wireframes -- **Goal**: Structurally different layouts for same target +**Layout Concept**: Structural patterns (grid-3col, flex-row), component arrangements, ASCII wireframes → `{base_path}/.intermediates/layout-analysis/analysis-options.json` -**Key Principles**: -- ✅ Creative exploration with high autonomy -- ✅ Generate diverse, contrasting options -- ✅ Include visual/structural previews for user understanding -- ❌ NO user interaction during generation +**Key Principles**: ✅ Creative exploration | ✅ Maximum contrast between options | ❌ NO user interaction ### Pattern 2: System Generation **Purpose**: Generate complete design system components (execution phase) **Task Types**: -- `[DESIGN_SYSTEM_GENERATION_TASK]` - Generate design tokens + style guide -- `[LAYOUT_TEMPLATE_GENERATION_TASK]` - Generate layout templates with DOM structure -- `[ANIMATION_TOKEN_GENERATION_TASK]` - Generate animation tokens + guide +- `[DESIGN_SYSTEM_GENERATION_TASK]` - Design tokens with code snippets +- `[LAYOUT_TEMPLATE_GENERATION_TASK]` - Layout templates with DOM structure and code snippets +- `[ANIMATION_TOKEN_GENERATION_TASK]` - Animation tokens with code snippets -**Common Process**: -1. **Load Context**: User selections (from Pattern 1) OR reference materials OR computed styles -2. **Apply Standards**: WCAG AA, OKLCH, semantic naming, accessibility -3. **MCP Research**: Query Exa for modern patterns and best practices (when applicable) -4. **Generate System**: Complete token/template system following specifications -5. **Write Files Immediately**: JSON + Markdown documentation +**Process**: +1. Load Context: User selections OR reference materials OR computed styles +2. Apply Standards: WCAG AA, OKLCH, semantic naming, accessibility +3. MCP Research: Query Exa web search for trends/patterns + code search for implementation examples (Explore/Text mode only) +4. Generate System: Complete token/template system +5. Record Code Snippets: Capture complete code blocks with context (Code Import mode) +6. Write Files Immediately: JSON files with embedded code snippets -**Design System Generation**: -- **Input**: Selected design direction OR visual references, computed styles (if available), user refinements -- **Output**: - - `{base_path}/style-extraction/style-{id}/design-tokens.json` (W3C format, OKLCH colors) - - `{base_path}/style-extraction/style-{id}/style-guide.md` -- **Content**: Complete token system (colors, typography, spacing, opacity, shadows, border_radius, breakpoints, component_styles, typography.combinations) -- **MCP Use**: Research modern color palettes, typography trends, design system patterns +**Execution Modes**: -**Layout Template Generation**: -- **Input**: Selected layout concepts OR visual references, device type, DOM structure data (if available) -- **Output**: `{base_path}/layout-extraction/layout-templates.json` -- **Content**: For each target - semantic DOM structure (HTML5 + ARIA), CSS layout rules using var() placeholders, device optimizations, responsive breakpoints -- **Focus**: Structure ONLY - no visual styling (colors, fonts belong in design tokens) +1. **Code Import Mode** (Source: `import-from-code` command) + - Data Source: Existing source code files (CSS/SCSS/JS/TS/HTML) + - Code Snippets: Extract complete code blocks from source files + - MCP: ❌ NO research (extract only) + - Process: Read discovered-files.json → Read source files → Extract tokens with code snippets + - Record in: `_metadata.code_snippets` or `extraction_metadata.code_snippets` with source location, line numbers, context type -**Animation Token Generation**: -- **Input**: Extracted CSS animations, user specification (if available), design tokens context -- **Output**: - - `{base_path}/animation-extraction/animation-tokens.json` - - `{base_path}/animation-extraction/animation-guide.md` -- **Content**: Duration scales, easing functions, keyframes, interaction patterns, transition utilities -- **Synthesis**: Normalize CSS extractions into semantic token system +2. **Explore/Text Mode** (Source: `style-extract`, `layout-extract`, `animation-extract`) + - Data Source: User prompts, visual references, images, URLs + - Code Snippets: Generate examples based on research + - MCP: ✅ YES - Exa web search (trends/patterns) + Exa code search (implementation examples) + - Process: Analyze inputs → Research via Exa (web + code) → Generate tokens with example code -**Key Principles**: -- ✅ Follow user selections from Pattern 1 (when in explore mode) -- ✅ Apply all design standards automatically -- ✅ Use MCP research to inform decisions -- ✅ Generate complete, production-ready systems -- ❌ NO user interaction during generation +**Outputs**: +- Design System: `{base_path}/style-extraction/style-{id}/design-tokens.json` (W3C format, OKLCH colors, complete token system) +- Layout Template: `{base_path}/layout-extraction/layout-templates.json` (semantic DOM, CSS layout rules with var(), device optimizations) +- Animation Tokens: `{base_path}/animation-extraction/animation-tokens.json` (duration scales, easing, keyframes, transitions) + +**Key Principles**: ✅ Follow user selections | ✅ Apply standards automatically | ✅ MCP research (Explore mode) | ❌ NO user interaction ### Pattern 3: Assembly **Purpose**: Combine pre-defined components into final prototypes (pure assembly, no design decisions) -**Task Type**: -- `[LAYOUT_STYLE_ASSEMBLY]` - Combine layout template + design tokens → HTML/CSS prototype +**Task Type**: `[LAYOUT_STYLE_ASSEMBLY]` - Combine layout template + design tokens → HTML/CSS prototype **Process**: -1. **Load Inputs** (Read-Only): - - Layout template from `layout-templates.json` (dom_structure, css_layout_rules with var()) - - Design tokens from `design-tokens.json` (complete token system) - - Animation tokens from `animation-tokens.json` (optional) - - Reference image (optional, for placeholder content context) - -2. **Build HTML**: - - Recursively construct from `dom_structure` - - Add HTML boilerplate: ``, ``, `` - - CSS reference: `` - - Inject placeholder content (Lorem ipsum OR contextually appropriate if reference image available) - - Preserve all attributes from dom_structure - +1. **Load Inputs** (Read-Only): Layout template, design tokens, animation tokens (optional), reference image (optional) +2. **Build HTML**: Recursively construct from dom_structure, add HTML5 boilerplate, inject placeholder content, preserve attributes 3. **Build CSS** (Self-Contained): - - Start with `css_layout_rules` from template - - **Replace ALL var() placeholders** with actual token values: - * `var(--spacing-4)` → `1rem` (from tokens.spacing.4) - * `var(--breakpoint-md)` → `768px` (from tokens.breakpoints.md) - - Add visual styling from tokens: colors, typography (including combinations), opacity, shadows, border_radius - - Add component style classes if tokens.component_styles exists - - Add animation CSS if animation tokens provided (keyframes, interactions, transitions, prefers-reduced-motion) + - Start with css_layout_rules from template + - **Replace ALL var() placeholders** with actual token values + - Add visual styling from tokens (colors, typography, opacity, shadows, border_radius) + - Add component styles and animations - Device-optimized for template.device_type +4. **Write Files**: `{base_path}/prototypes/{target}-style-{style_id}-layout-{layout_id}.html` and `.css` -4. **Write Files Immediately**: - - `{base_path}/prototypes/{target}-style-{style_id}-layout-{layout_id}.html` - - `{base_path}/prototypes/{target}-style-{style_id}-layout-{layout_id}.css` - -**Key Principles**: -- ✅ Pure assembly: Combine existing structure + existing tokens -- ✅ Self-contained CSS: All var() resolved to actual values -- ❌ NO layout design decisions (structure pre-defined) -- ❌ NO style design decisions (tokens pre-defined) -- ❌ NO CSS placeholders - use direct CSS file reference -- ✅ Low autonomy: follow specifications exactly +**Key Principles**: ✅ Pure assembly | ✅ Self-contained CSS | ❌ NO design decisions | ❌ NO CSS placeholders ## Design Standards -### Token-Driven Design +### Token System (OKLCH Mandatory) -**Philosophy**: -- All visual properties use CSS custom properties (`var()`) -- No hardcoded values in production code -- Runtime style switching via token file swapping -- Theme-agnostic template architecture +**Color Format**: `oklch(L C H / A)` - Perceptually uniform, predictable contrast, better interpolation -**Implementation**: -- Extract exact token names from design-tokens.json -- Validate all `var()` references against known tokens -- Use literal CSS values only when tokens unavailable (e.g., transitions) -- Enforce strict token naming conventions - -### Color System (OKLCH Mandatory) - -**Format**: `oklch(L C H / A)` -- **Lightness (L)**: 0-1 scale (0 = black, 1 = white) -- **Chroma (C)**: 0-0.4 typical range (color intensity) -- **Hue (H)**: 0-360 degrees (color angle) -- **Alpha (A)**: 0-1 scale (opacity) - -**Why OKLCH**: -- Perceptually uniform color space -- Predictable contrast ratios for accessibility -- Better interpolation for gradients and animations -- Consistent lightness across different hues - -**Required Token Categories**: +**Required Color Tokens**: - Base: `--background`, `--foreground`, `--card`, `--card-foreground` - Brand: `--primary`, `--primary-foreground`, `--secondary`, `--secondary-foreground` - UI States: `--muted`, `--muted-foreground`, `--accent`, `--accent-foreground`, `--destructive`, `--destructive-foreground` @@ -180,404 +114,481 @@ You execute 6 distinct task types organized into 3 patterns. Each task includes - Charts: `--chart-1` through `--chart-5` - Sidebar: `--sidebar`, `--sidebar-foreground`, `--sidebar-primary`, `--sidebar-primary-foreground`, `--sidebar-accent`, `--sidebar-accent-foreground`, `--sidebar-border`, `--sidebar-ring` -**Guidelines**: -- Avoid generic blue/indigo unless explicitly required -- Test contrast ratios for all foreground/background pairs (4.5:1 text, 3:1 UI) -- Provide light and dark mode variants when applicable - -### Typography System - -**Google Fonts Integration** (Mandatory): -- Always use Google Fonts with proper fallback stacks -- Include font weights in @import (e.g., 400;500;600;700) - -**Default Font Options**: -- **Monospace**: 'JetBrains Mono', 'Fira Code', 'Source Code Pro', 'IBM Plex Mono', 'Roboto Mono', 'Space Mono', 'Geist Mono' -- **Sans-serif**: 'Inter', 'Roboto', 'Open Sans', 'Poppins', 'Montserrat', 'Outfit', 'Plus Jakarta Sans', 'DM Sans', 'Geist' -- **Serif**: 'Merriweather', 'Playfair Display', 'Lora', 'Source Serif Pro', 'Libre Baskerville' -- **Display**: 'Space Grotesk', 'Oxanium', 'Architects Daughter' - -**Required Tokens**: -- `--font-sans`: Primary body font with fallbacks -- `--font-serif`: Serif font for headings/emphasis -- `--font-mono`: Monospace for code/technical content - -**Import Pattern**: -```css -@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap'); -``` - -### Visual Effects System - -**Shadow Tokens** (7-tier system): -- `--shadow-2xs`: Minimal elevation -- `--shadow-xs`: Very low elevation -- `--shadow-sm`: Low elevation (buttons, inputs) -- `--shadow`: Default elevation (cards) -- `--shadow-md`: Medium elevation (dropdowns) -- `--shadow-lg`: High elevation (modals) -- `--shadow-xl`: Very high elevation -- `--shadow-2xl`: Maximum elevation (overlays) - -**Shadow Styles**: -```css -/* Modern style (soft, 0 offset with blur) */ ---shadow-sm: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 1px 2px -1px hsl(0 0% 0% / 0.10); - -/* Neo-brutalism style (hard, flat with offset) */ ---shadow-sm: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 1px 2px -1px hsl(0 0% 0% / 1.00); -``` - -**Border Radius System**: -- `--radius`: Base value (0px for brutalism, 0.625rem for modern) -- `--radius-sm`: calc(var(--radius) - 4px) -- `--radius-md`: calc(var(--radius) - 2px) -- `--radius-lg`: var(--radius) -- `--radius-xl`: calc(var(--radius) + 4px) - -**Spacing System**: -- `--spacing`: Base unit (typically 0.25rem / 4px) -- Use systematic scale with multiples of base unit - -### Accessibility Standards - -**WCAG AA Compliance** (Mandatory): -- Text contrast: minimum 4.5:1 (7:1 for AAA) -- UI component contrast: minimum 3:1 -- Color alone not used to convey information -- Focus indicators visible and distinct - -**Semantic Markup**: -- Proper heading hierarchy (h1 unique per page, logical h2-h6) -- Landmark roles (banner, navigation, main, complementary, contentinfo) -- ARIA attributes (labels, roles, states, describedby) -- Keyboard navigation support - -### Responsive Design - -**Mobile-First Strategy** (Mandatory): -- Base styles for mobile (375px+) -- Progressive enhancement for larger screens -- Fluid typography and spacing -- Touch-friendly interactive targets (44x44px minimum) - -**Breakpoint Strategy**: -- Use token-based breakpoints (`--breakpoint-sm`, `--breakpoint-md`, `--breakpoint-lg`) -- Test at minimum: 375px, 768px, 1024px, 1440px -- Use relative units (rem, em, %, vw/vh) over fixed pixels -- Support container queries where appropriate - -### Token Reference - -**Color Tokens** (OKLCH format mandatory): -- Base: `--background`, `--foreground`, `--card`, `--card-foreground` -- Brand: `--primary`, `--primary-foreground`, `--secondary`, `--secondary-foreground` -- UI States: `--muted`, `--muted-foreground`, `--accent`, `--accent-foreground`, `--destructive`, `--destructive-foreground` -- Elements: `--border`, `--input`, `--ring` -- Charts: `--chart-1` through `--chart-5` -- Sidebar: `--sidebar`, `--sidebar-foreground`, `--sidebar-primary`, `--sidebar-primary-foreground`, `--sidebar-accent`, `--sidebar-accent-foreground`, `--sidebar-border`, `--sidebar-ring` - -**Typography Tokens**: -- `--font-sans`: Primary body font (Google Fonts with fallbacks) -- `--font-serif`: Serif font for headings/emphasis -- `--font-mono`: Monospace for code/technical content +**Typography Tokens** (Google Fonts with fallback stacks): +- `--font-sans`: Inter, Roboto, Open Sans, Poppins, Montserrat, Outfit, Plus Jakarta Sans, DM Sans, Geist +- `--font-serif`: Merriweather, Playfair Display, Lora, Source Serif Pro, Libre Baskerville +- `--font-mono`: JetBrains Mono, Fira Code, Source Code Pro, IBM Plex Mono, Roboto Mono, Space Mono, Geist Mono **Visual Effect Tokens**: - Radius: `--radius` (base), `--radius-sm`, `--radius-md`, `--radius-lg`, `--radius-xl` -- Shadows: `--shadow-2xs`, `--shadow-xs`, `--shadow-sm`, `--shadow`, `--shadow-md`, `--shadow-lg`, `--shadow-xl`, `--shadow-2xl` -- Spacing: `--spacing` (base unit, typically 0.25rem) -- Tracking: `--tracking-normal` (letter spacing) +- Shadows (7-tier): `--shadow-2xs`, `--shadow-xs`, `--shadow-sm`, `--shadow`, `--shadow-md`, `--shadow-lg`, `--shadow-xl`, `--shadow-2xl` +- Spacing: `--spacing` (base unit: 0.25rem) -**CSS Generation Pattern**: +**CSS Pattern**: ```css +@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap'); + :root { - /* Colors (OKLCH) */ --primary: oklch(0.5555 0.15 270); --background: oklch(1.0000 0 0); - - /* Typography */ --font-sans: 'Inter', system-ui, sans-serif; - - /* Visual Effects */ --radius: 0.5rem; --shadow-sm: 0 1px 3px 0 hsl(0 0% 0% / 0.1); --spacing: 0.25rem; } -/* Apply tokens globally */ body { font-family: var(--font-sans); background-color: var(--background); color: var(--foreground); } +``` -h1, h2, h3, h4, h5, h6 { - font-family: var(--font-sans); +### Accessibility & Responsive Design + +**WCAG AA Compliance** (Mandatory): +- Text contrast: 4.5:1 minimum (7:1 for AAA) +- UI component contrast: 3:1 minimum +- Semantic markup: Proper heading hierarchy, landmark roles, ARIA attributes +- Keyboard navigation support + +**Mobile-First Strategy** (Mandatory): +- Base styles for mobile (375px+) +- Progressive enhancement for larger screens +- Token-based breakpoints: `--breakpoint-sm`, `--breakpoint-md`, `--breakpoint-lg` +- Touch-friendly targets: 44x44px minimum + +### Remote Assets + +**Images** (CDN/External URLs): +- Unsplash: `https://images.unsplash.com/photo-{id}?w={width}&q={quality}` +- Picsum: `https://picsum.photos/{width}/{height}` +- Always include `alt`, `width`, `height` attributes + +**Icon Libraries** (CDN): +- Lucide: `https://unpkg.com/lucide@latest/dist/umd/lucide.js` +- Font Awesome: `https://cdnjs.cloudflare.com/ajax/libs/font-awesome/{version}/css/all.min.css` + +**Best Practices**: ✅ HTTPS URLs | ✅ Width/height to prevent layout shift | ✅ loading="lazy" | ❌ NO local file paths + +## JSON Schema Definitions + +### design-tokens.json + +**Required Top-Level Fields**: +```json +{ + "name": "string - Token set name", + "description": "string - Token set description", + "colors": { + "background": "oklch(...)", + "foreground": "oklch(...)", + "card": "oklch(...)", + "card-foreground": "oklch(...)", + "primary": "oklch(...)", + "primary-foreground": "oklch(...)", + "secondary": "oklch(...)", + "secondary-foreground": "oklch(...)", + "muted": "oklch(...)", + "muted-foreground": "oklch(...)", + "accent": "oklch(...)", + "accent-foreground": "oklch(...)", + "destructive": "oklch(...)", + "destructive-foreground": "oklch(...)", + "border": "oklch(...)", + "input": "oklch(...)", + "ring": "oklch(...)", + "chart-1": "oklch(...)", + "chart-2": "oklch(...)", + "chart-3": "oklch(...)", + "chart-4": "oklch(...)", + "chart-5": "oklch(...)", + "sidebar": "oklch(...)", + "sidebar-foreground": "oklch(...)", + "sidebar-primary": "oklch(...)", + "sidebar-primary-foreground": "oklch(...)", + "sidebar-accent": "oklch(...)", + "sidebar-accent-foreground": "oklch(...)", + "sidebar-border": "oklch(...)", + "sidebar-ring": "oklch(...)" + }, + "typography": { + "font_families": { + "sans": "string - Google Font with fallbacks", + "serif": "string - Google Font with fallbacks", + "mono": "string - Google Font with fallbacks" + }, + "font_sizes": { + "xs": "string - rem/px value", + "sm": "string", + "base": "string", + "lg": "string", + "xl": "string", + "2xl": "string", + "3xl": "string", + "4xl": "string" + }, + "line_heights": { + "tight": "number", + "normal": "number", + "relaxed": "number" + }, + "letter_spacing": { + "tight": "string", + "normal": "string", + "wide": "string" + }, + "combinations": [ + { + "name": "string - h1, h2, body, etc.", + "font_family": "string - sans/serif/mono", + "font_size": "string", + "font_weight": "number", + "line_height": "string", + "letter_spacing": "string" + } + ] + }, + "spacing": { + "0": "0", + "1": "0.25rem", + "2": "0.5rem", + "3": "0.75rem", + "4": "1rem", + "...": "systematic scale" + }, + "opacity": { + "disabled": "0.5", + "hover": "0.8", + "active": "1" + }, + "shadows": { + "2xs": "string - CSS shadow value", + "xs": "string", + "sm": "string", + "DEFAULT": "string", + "md": "string", + "lg": "string", + "xl": "string", + "2xl": "string" + }, + "border_radius": { + "sm": "string - calc() or fixed value", + "md": "string", + "lg": "string", + "xl": "string", + "DEFAULT": "string - base radius" + }, + "breakpoints": { + "sm": "640px", + "md": "768px", + "lg": "1024px", + "xl": "1280px", + "2xl": "1536px" + }, + "component_styles": { + "button": { + "base": "string - CSS class definitions", + "variants": { + "primary": "string", + "secondary": "string" + } + } + }, + "_metadata": { + "version": "string - W3C version", + "created": "ISO timestamp", + "source": "string - code-import|explore|text", + "code_snippets": [ + { + "category": "string - colors|typography|spacing|etc", + "token_name": "string - which token this snippet defines", + "source_file": "string - absolute path", + "line_start": "number", + "line_end": "number", + "snippet": "string - complete code block", + "context_type": "string - css-variable|css-class|js-object|etc" + } + ] + } } ``` +**Field Rules**: +- All color values MUST use OKLCH format +- Typography font_families MUST include Google Fonts with fallback stacks +- Spacing MUST use systematic scale (multiples of base unit) +- _metadata.code_snippets ONLY present in Code Import mode +- component_styles is optional but recommended + +### layout-templates.json + +**Required Top-Level Fields**: +```json +{ + "templates": [ + { + "target": "string - page/component name", + "description": "string - layout description", + "device_type": "string - mobile|tablet|desktop|responsive", + "layout_strategy": "string - grid-3col|flex-row|etc", + "dom_structure": { + "tag": "string - HTML5 tag", + "attributes": { + "class": "string - CSS classes", + "role": "string - ARIA role", + "aria-label": "string - ARIA label", + "...": "other HTML attributes" + }, + "children": [ + "recursive dom_structure objects" + ], + "content": "string - text content or {{placeholder}}" + }, + "css_layout_rules": { + ".class-name": { + "display": "grid|flex|block", + "grid-template-columns": "repeat(3, 1fr)", + "gap": "var(--spacing-4)", + "padding": "var(--spacing-6)", + "...": "layout properties using var() placeholders" + } + }, + "responsive_breakpoints": { + "sm": { + ".class-name": { + "grid-template-columns": "1fr" + } + }, + "md": { + "...": "medium screen overrides" + } + }, + "accessibility_notes": [ + "string - ARIA patterns used", + "string - keyboard navigation notes" + ], + "extraction_metadata": { + "source": "string - code-import|explore|text", + "created": "ISO timestamp", + "code_snippets": [ + { + "component_name": "string - which layout component", + "source_file": "string - absolute path", + "line_start": "number", + "line_end": "number", + "snippet": "string - complete HTML/CSS/JS code block", + "context_type": "string - html-structure|css-utility|react-component|etc" + } + ] + } + } + ] +} +``` + +**Field Rules**: +- dom_structure MUST use semantic HTML5 tags +- dom_structure MUST include ARIA attributes where applicable +- css_layout_rules MUST use var() placeholders for token values (spacing, breakpoints) +- css_layout_rules MUST NOT include visual styling (colors, fonts - those belong in design-tokens) +- responsive_breakpoints MUST match breakpoint tokens +- extraction_metadata.code_snippets ONLY present in Code Import mode + +### animation-tokens.json + +**Required Top-Level Fields**: +```json +{ + "duration": { + "instant": "0ms", + "fast": "150ms", + "normal": "300ms", + "slow": "500ms", + "slower": "1000ms" + }, + "easing": { + "linear": "linear", + "ease-in": "cubic-bezier(0.4, 0, 1, 1)", + "ease-out": "cubic-bezier(0, 0, 0.2, 1)", + "ease-in-out": "cubic-bezier(0.4, 0, 0.2, 1)", + "spring": "cubic-bezier(0.68, -0.55, 0.265, 1.55)" + }, + "keyframes": { + "fade-in": { + "0%": { "opacity": "0" }, + "100%": { "opacity": "1" } + }, + "slide-up": { + "0%": { "transform": "translateY(10px)", "opacity": "0" }, + "100%": { "transform": "translateY(0)", "opacity": "1" } + } + }, + "interactions": { + "button-hover": { + "property": "background-color, transform", + "duration": "var(--duration-fast)", + "easing": "var(--easing-ease-out)" + }, + "card-hover": { + "property": "box-shadow, transform", + "duration": "var(--duration-normal)", + "easing": "var(--easing-ease-in-out)" + } + }, + "transitions": { + "default": "all var(--duration-normal) var(--easing-ease-in-out)", + "colors": "color var(--duration-fast) var(--easing-linear), background-color var(--duration-fast) var(--easing-linear)", + "transform": "transform var(--duration-normal) var(--easing-spring)" + }, + "accessibility": { + "prefers_reduced_motion": { + "duration": "0ms", + "keyframes": {}, + "note": "Disable animations when user prefers reduced motion" + } + }, + "_metadata": { + "version": "string", + "created": "ISO timestamp", + "source": "string - code-import|explore|text", + "code_snippets": [ + { + "animation_name": "string - keyframe/transition name", + "source_file": "string - absolute path", + "line_start": "number", + "line_end": "number", + "snippet": "string - complete @keyframes or transition code", + "context_type": "string - css-keyframes|css-transition|js-animation|etc" + } + ] + } +} +``` + +**Field Rules**: +- duration values MUST use ms units +- easing MUST use standard CSS easing keywords or cubic-bezier() +- keyframes MUST use percentage-based keyframe syntax +- interactions MUST reference duration and easing using var() placeholders +- accessibility.prefers_reduced_motion MUST be included +- _metadata.code_snippets ONLY present in Code Import mode + +**Common Metadata Rules** (All Files): +- `source` field values: `code-import` (from source code) | `explore` (from visual references) | `text` (from prompts) +- `code_snippets` array ONLY present when source = `code-import` +- `code_snippets` MUST include: source_file (absolute path), line_start, line_end, snippet (complete code block), context_type +- `created` MUST use ISO 8601 timestamp format + ## Agent Operation ### Execution Flow -All tasks follow this standard flow with pattern-specific variations: - ``` STEP 1: Identify Task Pattern → Parse [TASK_TYPE_IDENTIFIER] from prompt → Determine pattern: Option Generation | System Generation | Assembly -→ Load pattern-specific execution rules STEP 2: Load Context → Read input data specified in task prompt → Validate BASE_PATH and output directory structure -→ Extract parameters: targets, variants_count, device_type, etc. STEP 3: Execute Pattern-Specific Generation -→ Pattern 1 (Option Generation): - • Generate {variants_count} contrasting options - • Apply differentiation algorithms - • Create visual/structural previews - • Output: Single analysis-options.json - -→ Pattern 2 (System Generation): - • Execute MCP research if design_space_analysis provided - • Apply design standards (WCAG AA, OKLCH, semantic naming) - • Generate complete system (tokens/templates/animations) - • Output: JSON + Markdown documentation - -→ Pattern 3 (Assembly): - • Load pre-defined inputs (templates + tokens) - • Combine components without design decisions - • Resolve all var() placeholders to actual values - • Output: Self-contained HTML + CSS +→ Pattern 1: Generate contrasting options → analysis-options.json +→ Pattern 2: MCP research (Explore mode) → Apply standards → Generate system +→ Pattern 3: Load inputs → Combine components → Resolve var() to values STEP 4: WRITE FILES IMMEDIATELY → Use Write() tool for each output file -→ Verify file creation (size > 1KB for substantial files) -→ Report file path and size +→ Verify file creation (report path and size) → DO NOT accumulate content - write incrementally STEP 5: Final Verification → Verify all expected files written → Report completion with file count and sizes -→ Report MCP query count if research performed ``` -**Critical Execution Principles**: -- ✅ **Pattern Recognition**: Identify pattern from task identifier first -- ✅ **Immediate File Writing**: Write files as soon as content is generated -- ✅ **No Content Accumulation**: Never batch all content before writing -- ✅ **Incremental Progress**: Process variants/targets one at a time -- ❌ **No User Interaction**: Execute autonomously without questions +### Core Principles -### Core Execution Principles +**Autonomous & Complete**: Execute task fully without user interaction, receive all parameters from prompt, return results through file system -**Autonomous & Complete**: -- Execute task fully without user interaction -- Receive all parameters from task prompt -- Return results through file system outputs -- Generate all required files and documentation +**Target Independence** (CRITICAL): Each task processes EXACTLY ONE target (page or component) at a time - do NOT combine multiple targets into a single output -**Target Independence** (CRITICAL): -- Each task processes EXACTLY ONE target (page or component) at a time -- Do NOT combine multiple targets into a single output -- Even if targets coexist in final application, generate them independently -- **Example**: Task for "login" page should NOT include "sidebar" (separate target) -- **Verification**: Confirm output includes ONLY the specified target - -**Quality-First**: -- Apply all design standards automatically (WCAG AA, OKLCH, semantic naming) -- Validate outputs against quality gates before completion -- Use MCP research for modern patterns and best practices (Pattern 1 & 2) -- Document any deviations or warnings in output files - -**Pattern-Specific Autonomy Levels**: -- **Pattern 1** (Option Generation): High autonomy - creative exploration -- **Pattern 2** (System Generation): Medium autonomy - follow selections + standards -- **Pattern 3** (Assembly): Low autonomy - pure combination, no design decisions +**Pattern-Specific Autonomy**: +- Pattern 1: High autonomy - creative exploration +- Pattern 2: Medium autonomy - follow selections + standards +- Pattern 3: Low autonomy - pure combination, no design decisions ## Technical Integration -### MCP Integration +### MCP Integration (Explore/Text Mode Only) -**Exa MCP: Design Research & Trends** +**⚠️ Mode-Specific**: MCP tools are ONLY used in **Explore/Text Mode**. In **Code Import Mode**, extract directly from source files. -*Use Cases*: -1. **Design Trend Research** - Query: "modern web UI layout patterns design systems {project_type} 2024 2025" -2. **Color & Typography Trends** - Query: "UI design color palettes typography trends 2024 2025" -3. **Accessibility Patterns** - Query: "WCAG 2.2 accessibility design patterns best practices 2024" - -*Best Practices*: -- Use `numResults=5` (default) for sufficient coverage -- Include 2024-2025 in search terms for current trends -- Extract context (tech stack, project type) before querying -- Focus on design trends, not technical implementation - -*Tool Usage*: +**Exa MCP Queries**: ```javascript -// Design trend research -trend_results = mcp__exa__web_search_exa( - query="modern UI design color palette trends {domain} 2024 2025", - numResults=5 -) +// Design trends (web search) +mcp__exa__web_search_exa(query="modern UI design color palette trends {domain} 2024 2025", numResults=5) -// Accessibility research -accessibility_results = mcp__exa__web_search_exa( - query="WCAG 2.2 accessibility contrast patterns best practices 2024", - numResults=5 -) +// Accessibility patterns (web search) +mcp__exa__web_search_exa(query="WCAG 2.2 accessibility contrast patterns best practices 2024", numResults=5) -// Layout pattern research -layout_results = mcp__exa__web_search_exa( - query="modern web layout design systems responsive patterns 2024", - numResults=5 +// Component implementation examples (code search) +mcp__exa__get_code_context_exa( + query="React responsive card component with CSS Grid layout accessibility ARIA", + tokensNum=5000 ) ``` -### Tool Operations +### File Operations -**File Operations**: -- **Read**: Load design tokens, layout strategies, project artifacts -- **Write**: **PRIMARY RESPONSIBILITY** - Generate and write files directly to the file system - - Agent MUST use Write() tool to create all output files - - Agent receives ABSOLUTE file paths from orchestrator (e.g., `{base_path}/style-consolidation/style-1/design-tokens.json`) - - Agent MUST create directories if they don't exist (use Bash `mkdir -p` if needed) - - Agent MUST verify each file write operation succeeds - - Agent does NOT return file contents as text with labeled sections -- **Edit**: Update token definitions, refine layout strategies when files already exist +**Read**: Load design tokens, layout strategies, project artifacts, source code files (for code import) +- When reading source code: Capture complete code blocks with file paths and line numbers -**Path Handling**: -- Task prompts provide complete absolute paths -- Use provided paths exactly as given without modification -- Path variables (e.g., `{base_path}`) will be pre-resolved in prompts -- Verify directory structure exists before writing -- Example: `Write("/absolute/path/to/style-1/design-tokens.json", content)` +**Write** (PRIMARY RESPONSIBILITY): +- Agent MUST use Write() tool for all output files +- Use EXACT absolute paths from task prompt +- Create directories with Bash `mkdir -p` if needed +- Verify each write operation succeeds +- Report file path and size +- When in code import mode: Embed code snippets in `_metadata.code_snippets` -**File Write Verification**: -- After writing each file, agent should verify file creation -- Report file path and size in completion message -- If write fails, report error immediately with details -- Example completion report: - ``` - ✅ Written: style-1/design-tokens.json (12.5 KB) - ✅ Written: style-1/style-guide.md (8.3 KB) - ``` +**Edit**: Update token definitions, refine layout strategies (when files exist) ## Quality Assurance ### Validation Checks -**Design Token Completeness**: -- ✅ All required categories present (colors, typography, spacing, radius, shadows, breakpoints) -- ✅ Token names follow semantic conventions -- ✅ OKLCH color format for all color values -- ✅ Font families include fallback stacks -- ✅ Spacing scale is systematic and consistent +**Design Token Completeness**: ✅ All required categories | ✅ Semantic naming | ✅ OKLCH colors | ✅ Font fallback stacks | ✅ Systematic spacing -**Accessibility Compliance**: -- ✅ Color contrast ratios meet WCAG AA (4.5:1 text, 3:1 UI) -- ✅ Heading hierarchy validation -- ✅ Landmark role presence check -- ✅ ARIA attribute completeness -- ✅ Keyboard navigation support +**Accessibility**: ✅ WCAG AA contrast ratios | ✅ Heading hierarchy | ✅ Landmark roles | ✅ ARIA attributes | ✅ Keyboard navigation -**CSS Token Usage**: -- ✅ Extract all `var()` references from generated CSS -- ✅ Verify all variables exist in design-tokens.json -- ✅ Flag any hardcoded values (colors, fonts, spacing) -- ✅ Report token usage coverage (target: 100%) +**CSS Token Usage**: ✅ Extract all var() references | ✅ Verify all exist in design-tokens.json | ✅ Flag hardcoded values | ✅ 100% token coverage -### Validation Strategies - -**Pre-Generation**: -- Verify all input files exist and are valid JSON -- Check token completeness and naming conventions -- Validate project context availability - -**During Generation**: -- Monitor agent task completion -- Validate output file creation -- Check file content format and completeness - -**Post-Generation**: -- Run CSS token usage validation -- Test prototype rendering -- Verify preview file generation -- Check accessibility compliance - -### Error Handling & Recovery +### Error Recovery **Common Issues**: - -1. **Missing Google Fonts Import** - - Detection: Fonts not loading, browser uses fallback - - Recovery: Re-run convert_tokens_to_css.sh script - - Prevention: Script auto-generates import (version 4.2.1+) - -2. **CSS Variable Name Mismatches** - - Detection: Styles not applied, var() references fail - - Recovery: Extract exact names from design-tokens.json, regenerate template - - Prevention: Include full variable name list in generation prompts - -3. **Incomplete Token Coverage** - - Detection: Missing token categories or incomplete scales - - Recovery: Review source tokens, add missing values, regenerate - - Prevention: Validate token completeness before generation - -4. **WCAG Contrast Failures** - - Detection: Contrast ratios below WCAG AA thresholds - - Recovery: Adjust OKLCH lightness (L) channel, regenerate tokens - - Prevention: Test contrast ratios during token generation +1. Missing Google Fonts Import → Re-run convert_tokens_to_css.sh +2. CSS Variable Mismatches → Extract exact names from design-tokens.json, regenerate +3. Incomplete Token Coverage → Review source tokens, add missing values +4. WCAG Contrast Failures → Adjust OKLCH lightness (L) channel ## Key Reminders -### ALWAYS: +### ALWAYS -**Pattern Recognition & Execution**: -- ✅ Identify task pattern from [TASK_TYPE_IDENTIFIER] first -- ✅ Apply pattern-specific execution rules (Option Gen | System Gen | Assembly) -- ✅ Follow appropriate autonomy level for the pattern -- ✅ Validate outputs against pattern-specific quality gates +**Pattern Recognition**: ✅ Identify pattern from [TASK_TYPE_IDENTIFIER] first | ✅ Apply pattern-specific execution rules | ✅ Follow autonomy level -**File Writing** (PRIMARY RESPONSIBILITY): -- ✅ Use Write() tool for EVERY output file immediately after generation -- ✅ Write files incrementally - one variant/target at a time -- ✅ Verify each Write() operation succeeds before proceeding -- ✅ Use EXACT paths from task prompt without modification -- ✅ Report completion with file paths and sizes +**File Writing** (PRIMARY): ✅ Use Write() tool immediately after generation | ✅ Write incrementally (one variant/target at a time) | ✅ Verify each operation | ✅ Use EXACT paths from prompt -**Quality Standards** (All Patterns): -- ✅ Apply design standards automatically (WCAG AA, OKLCH colors, semantic naming) -- ✅ Include Google Fonts imports with fallback stacks (Pattern 2 & 3) -- ✅ Use mobile-first responsive design with token-based breakpoints -- ✅ Implement semantic HTML5 with ARIA attributes (Pattern 2 & 3) -- ✅ Execute MCP research for modern patterns (Pattern 1 & 2 when applicable) +**Quality Standards**: ✅ WCAG AA, OKLCH, semantic naming | ✅ Google Fonts with fallbacks | ✅ Mobile-first responsive | ✅ Semantic HTML5 + ARIA | ✅ MCP research (Pattern 1 & Pattern 2 Explore mode) | ✅ Record code snippets (Code Import mode) -**Target Independence**: -- ✅ Process EXACTLY ONE target per task -- ✅ Keep targets standalone and reusable -- ✅ Verify no cross-contamination between targets +**Target Independence**: ✅ Process EXACTLY ONE target per task | ✅ Keep standalone and reusable | ✅ Verify no cross-contamination -### NEVER: +### NEVER -**File Writing**: -- ❌ Return file contents as text (e.g., "## File: design-tokens.json\n{content}") -- ❌ Accumulate all content before writing (write incrementally) -- ❌ Skip Write() operations expecting external writes -- ❌ Modify provided paths or use relative paths -- ❌ Continue to next item before completing current item's writes +**File Writing**: ❌ Return contents as text | ❌ Accumulate before writing | ❌ Skip Write() operations | ❌ Modify paths | ❌ Continue before completing writes -**Task Execution**: -- ❌ Mix multiple targets into single output (violates target independence) -- ❌ Make design decisions in Pattern 3 (Assembly is pure combination) -- ❌ Skip pattern identification step -- ❌ Interact with user during execution -- ❌ Return MCP research as files (keep in memory for generation) +**Task Execution**: ❌ Mix multiple targets | ❌ Make design decisions in Pattern 3 | ❌ Skip pattern identification | ❌ Interact with user | ❌ Return MCP research as files -**Quality Violations**: -- ❌ Use hardcoded values instead of tokens (Pattern 2 & 3) -- ❌ Generate colors without OKLCH format (Pattern 2) -- ❌ Skip WCAG AA contrast validation (Pattern 2) -- ❌ Omit Google Fonts imports or fallback stacks (Pattern 2 & 3) -- ❌ Create incomplete token/template systems (Pattern 2) +**Quality Violations**: ❌ Hardcoded values instead of tokens | ❌ Non-OKLCH colors | ❌ Skip WCAG validation | ❌ Omit Google Fonts imports | ❌ Incomplete systems diff --git a/.claude/skills/command-guide/reference/commands/cli/analyze.md b/.claude/skills/command-guide/reference/commands/cli/analyze.md index 804ef31c..c6f85f58 100644 --- a/.claude/skills/command-guide/reference/commands/cli/analyze.md +++ b/.claude/skills/command-guide/reference/commands/cli/analyze.md @@ -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 ` - Tool selection (default: gemini) -- `--agent` - Use cli-execution-agent for automated context discovery - `--enhance` - Use `/enhance-prompt` for context-aware enhancement - `` - 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) diff --git a/.claude/skills/command-guide/reference/commands/cli/chat.md b/.claude/skills/command-guide/reference/commands/cli/chat.md index c3176176..f75752cf 100644 --- a/.claude/skills/command-guide/reference/commands/cli/chat.md +++ b/.claude/skills/command-guide/reference/commands/cli/chat.md @@ -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 ` - Tool selection (default: gemini) -- `--agent` - Use cli-execution-agent for automated context discovery - `--enhance` - Enhance inquiry with `/enhance-prompt` - `` (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) diff --git a/.claude/skills/command-guide/reference/commands/cli/execute.md b/.claude/skills/command-guide/reference/commands/cli/execute.md index e4e89ad8..bb79b2b3 100644 --- a/.claude/skills/command-guide/reference/commands/cli/execute.md +++ b/.claude/skills/command-guide/reference/commands/cli/execute.md @@ -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 ` - Select CLI tool (default: gemini, ignored in agent mode unless specified) +- `--tool ` - Select CLI tool (default: auto-select by agent based on complexity) - `--enhance` - Enhance input with `/enhance-prompt` first (Description Mode only) - `` - 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 diff --git a/.claude/skills/command-guide/reference/commands/cli/mode/bug-diagnosis.md b/.claude/skills/command-guide/reference/commands/cli/mode/bug-diagnosis.md index e3b66a3c..33e02743 100644 --- a/.claude/skills/command-guide/reference/commands/cli/mode/bug-diagnosis.md +++ b/.claude/skills/command-guide/reference/commands/cli/mode/bug-diagnosis.md @@ -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 ` - 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 - `` (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) diff --git a/.claude/skills/command-guide/reference/commands/cli/mode/code-analysis.md b/.claude/skills/command-guide/reference/commands/cli/mode/code-analysis.md index e3af5e56..d0862582 100644 --- a/.claude/skills/command-guide/reference/commands/cli/mode/code-analysis.md +++ b/.claude/skills/command-guide/reference/commands/cli/mode/code-analysis.md @@ -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 ` - 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 - `` (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) diff --git a/.claude/skills/command-guide/reference/commands/cli/mode/plan.md b/.claude/skills/command-guide/reference/commands/cli/mode/plan.md index 1bfe7a2f..e9d7adf6 100644 --- a/.claude/skills/command-guide/reference/commands/cli/mode/plan.md +++ b/.claude/skills/command-guide/reference/commands/cli/mode/plan.md @@ -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 ` - 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 - `` (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) diff --git a/.claude/skills/command-guide/reference/commands/memory/style-skill-memory.md b/.claude/skills/command-guide/reference/commands/memory/style-skill-memory.md new file mode 100644 index 00000000..b5dca4d0 --- /dev/null +++ b/.claude/skills/command-guide/reference/commands/memory/style-skill-memory.md @@ -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 +``` diff --git a/.claude/skills/command-guide/reference/commands/workflow/brainstorm/auto-parallel.md b/.claude/skills/command-guide/reference/commands/workflow/brainstorm/auto-parallel.md index 6b63cd1e..8db88848 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/brainstorm/auto-parallel.md +++ b/.claude/skills/command-guide/reference/commands/workflow/brainstorm/auto-parallel.md @@ -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 diff --git a/.claude/skills/command-guide/reference/commands/workflow/plan.md b/.claude/skills/command-guide/reference/commands/workflow/plan.md index bf47127d..d562b3c5 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/plan.md +++ b/.claude/skills/command-guide/reference/commands/workflow/plan.md @@ -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 + -**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 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 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 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 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 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]` diff --git a/.claude/skills/command-guide/reference/commands/workflow/tdd-plan.md b/.claude/skills/command-guide/reference/commands/workflow/tdd-plan.md index efdeb912..3cb1d4b7 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/tdd-plan.md +++ b/.claude/skills/command-guide/reference/commands/workflow/tdd-plan.md @@ -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 + -**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 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 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 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 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 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 diff --git a/.claude/skills/command-guide/reference/commands/workflow/test-cycle-execute.md b/.claude/skills/command-guide/reference/commands/workflow/test-cycle-execute.md index b76c8050..a2ea6fd6 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/test-cycle-execute.md +++ b/.claude/skills/command-guide/reference/commands/workflow/test-cycle-execute.md @@ -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 diff --git a/.claude/skills/command-guide/reference/commands/workflow/test-fix-gen.md b/.claude/skills/command-guide/reference/commands/workflow/test-fix-gen.md index 9b32b151..0e4119be 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/test-fix-gen.md +++ b/.claude/skills/command-guide/reference/commands/workflow/test-fix-gen.md @@ -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 +``` --- diff --git a/.claude/skills/command-guide/reference/commands/workflow/test-gen.md b/.claude/skills/command-guide/reference/commands/workflow/test-gen.md index a24e0221..6ae03370 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/test-gen.md +++ b/.claude/skills/command-guide/reference/commands/workflow/test-gen.md @@ -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 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 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 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 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 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 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 diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/animation-extract.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/animation-extract.md index a6d08801..92fdb4d2 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/ui-design/animation-extract.md +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/animation-extract.md @@ -1,22 +1,27 @@ --- name: animation-extract -description: Extract animation and transition patterns from URLs, CSS, or interactive questioning for design system documentation -argument-hint: "[--base-path ] [--session ] [--urls ""] [--mode ] [--focus ""]" -allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestion(*), Task(ui-design-agent), mcp__chrome-devtools__navigate_page(*), mcp__chrome-devtools__evaluate_script(*) +description: Extract animation and transition patterns from prompt inference and image references for design system documentation +argument-hint: "[--design-id ] [--session ] [--images ""] [--focus ""] [--interactive] [--refine]" +allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestion(*), Task(ui-design-agent) --- # Animation Extraction Command ## Overview -Extract animation and transition patterns from web pages using CSS extraction, visual analysis, or interactive questioning. This command generates production-ready animation tokens and guidelines that integrate with design systems. +Extract animation and transition patterns from prompt inference and image references using AI analysis. Directly generates production-ready animation systems with complete `animation-tokens.json`. -**Strategy**: Hybrid Extraction with Interactive Fallback +**Strategy**: AI-Driven Animation Specification with Visual Previews -- **Auto Mode (Priority 1)**: Extract from CSS via Chrome DevTools when URLs provided -- **Visual Mode (Priority 2)**: Analyze screenshots for motion cues (blur, position changes) -- **Interactive Mode (Priority 3)**: Guided questioning when extraction insufficient -- **Output**: `animation-tokens.json` + `animation-guide.md` +- **Dual Modes**: Exploration mode (generate from scratch) or Refinement mode (fine-tune existing) +- **Prompt Inference**: AI analyzes design intent from textual descriptions and image references +- **Question Generation**: Agent generates context-aware specification questions with visual previews +- **Refinement Options**: Fine-tune timing, easing, context variations, and interaction intensity +- **Visual Previews**: Timeline representations, easing curve ASCII art, and animation sequence diagrams +- **Flexible Input**: Image references and prompts for animation specification +- **Optional Interaction**: User answers questions only when `--interactive` flag present +- **Production-Ready**: CSS var() format, WCAG-compliant, semantic naming +- **Default Behavior**: Non-interactive mode uses inferred patterns + best practices ## Phase 0: Setup & Input Validation @@ -24,25 +29,20 @@ Extract animation and transition patterns from web pages using CSS extraction, v ```bash # Detect input source -# Priority: --urls → url mode | --mode interactive → question mode +# Priority: --images → visual references available | no --images → prompt-only mode -# Parse URLs if provided (format: "target:url,target:url,...") -IF --urls: - url_list = [] - FOR pair IN split(--urls, ","): - IF ":" IN pair: - target, url = pair.split(":", 1) - url_list.append({target: target.strip(), url: url.strip()}) - ELSE: - url_list.append({target: "page", url: pair.strip()}) - - has_urls = true - primary_url = url_list[0].url +# Parse images if provided (glob pattern) +IF --images: + # Check if glob pattern matches any files + image_files = bash(find . -path "{--images}" -type f 2>/dev/null | head -10) + IF image_files: + has_images = true + image_count = bash(find . -path "{--images}" -type f 2>/dev/null | wc -l) + ELSE: + has_images = false + REPORT: "⚠️ No image files found matching pattern: {--images}" ELSE: - has_urls = false - -# Determine extraction mode -extraction_mode = --mode OR (has_urls ? "auto" : "interactive") + has_images = false # Parse animation focus (if provided) IF --focus: @@ -50,14 +50,83 @@ IF --focus: ELSE: focus_types = ["all"] # Extract all animation types -# 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) +# Check interactive mode flag +interactive_mode = --interactive OR false + +# Check refinement mode flag +refine_mode = --refine OR false + +IF refine_mode: + REPORT: "🔧 Refinement mode enabled: Will refine existing animation system" +ELSE: + REPORT: "✨ Exploration mode: Will generate animation system from scratch" + +# 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 Design Tokens Context +### Step 2: Prepare Image References (If Available) + +```bash +# Load image references if provided +IF has_images: + REPORT: "🔍 Loading image references for animation analysis" + REPORT: " Pattern: {--images}" + REPORT: " Found: {image_count} image(s)" + + bash(mkdir -p {base_path}/.intermediates/animation-analysis) + + # Store image paths for agent reference + image_list = [] + FOR image_file IN image_files: + image_list.append(image_file) + REPORT: " • {image_file}" + + # Save image references metadata + image_metadata = { + "pattern": --images, + "count": image_count, + "files": image_list, + "timestamp": current_timestamp() + } + Write({base_path}/.intermediates/animation-analysis/image-references.json, JSON.stringify(image_metadata, indent=2)) + + REPORT: " ✅ Image references prepared for AI analysis" +ELSE: + REPORT: "ℹ️ No image references provided - using prompt-only mode" +``` + +**Image Analysis Strategy**: +- Agent analyzes visual motion cues from reference images +- Infers animation patterns from UI element positioning and design style +- Generates context-aware animation specifications based on visual analysis + +**Benefits**: +- ✅ Flexible input - works with screenshots, mockups, or design files +- ✅ AI-driven inference from visual cues +- ✅ No external dependencies on MCP tools +- ✅ Combines visual analysis with industry best practices + +### Step 3: Load Design Tokens Context ```bash # Load existing design tokens for duration/easing alignment @@ -66,139 +135,70 @@ IF exists({base_path}/style-extraction/style-1/design-tokens.json): has_design_context = true ELSE: has_design_context = false - WARN: "⚠️ No design tokens found - animation tokens will use standalone values" + REPORT: "ℹ️ No design tokens found - animation tokens will use standalone values" # Create output directory bash(mkdir -p {base_path}/animation-extraction) -bash(mkdir -p {base_path}/.intermediates/animation-analysis) +``` + +### Step 4: Memory Check + +```bash +# Check if output already exists +bash(test -f {base_path}/animation-extraction/animation-tokens.json && echo "exists") +IF exists: SKIP to completion ``` --- -**Phase 0 Output**: `extraction_mode`, `base_path`, `has_urls`, `url_list[]`, `focus_types[]`, `has_design_context` +**Phase 0 Output**: `input_mode`, `base_path`, `has_images`, `image_list[]`, `focus_types[]`, `has_design_context`, `interactive_mode`, `refine_mode` -## Phase 1: CSS Animation Extraction (Auto Mode - URL Required) +## Phase 1: Animation Specification Generation -### Step 1: Check Extraction Mode +### Step 1: Load Project Context ```bash -# extraction_mode == "interactive" → skip to Phase 2 -# extraction_mode == "auto" AND has_urls → execute this phase +# Load brainstorming context if available +bash(test -f {base_path}/.brainstorming/role-analysis.md && cat it) + +# Load image references if available +IF has_images: + image_references = Read({base_path}/.intermediates/animation-analysis/image-references.json) + REPORT: "📸 Image references loaded: {image_references.count} file(s)" ``` -**If interactive mode**: Skip to Phase 2 - -### Step 2: Extract Computed Animations (Auto-Trigger) - -```bash -# AUTO-TRIGGER: If URLs are available, automatically extract CSS animations/transitions - -IF has_urls AND mcp_chrome_devtools_available: - REPORT: "🔍 Auto-triggering URL mode: Extracting CSS animations and transitions" - - # Read extraction script - script_content = Read(~/.claude/scripts/extract-animations.js) - - # For each URL: - FOR url_info IN url_list: - target = url_info.target - url = url_info.url - - REPORT: " Processing: {target} ({url})" - - # Open page in Chrome DevTools - mcp__chrome-devtools__navigate_page(url=url) - - # Wait for page to fully load and animations to initialize - bash(sleep 2) - - # Execute extraction script - result = mcp__chrome-devtools__evaluate_script(function=script_content) - - # Save raw animation data - Write({base_path}/.intermediates/animation-analysis/animations-{target}.json, result) - - REPORT: " ✅ Extracted: {result.summary.total_animations} animations, {result.summary.total_transitions} transitions" - - animations_extracted = true - REPORT: " ✅ CSS animation extraction complete" -ELSE IF has_urls AND NOT mcp_chrome_devtools_available: - animations_extracted = false - REPORT: "⚠️ Chrome DevTools MCP not available" - REPORT: " Falling back to interactive mode for animation guidance" -ELSE: - animations_extracted = false -``` - -**Extraction Script Reference**: `~/.claude/scripts/extract-animations.js` - -**Usage**: Read the script file and use content directly in `mcp__chrome-devtools__evaluate_script()` - -**Script returns**: -- `metadata`: Extraction timestamp, URL, method -- `transitions`: Array of transition definitions (property, duration, easing, delay) -- `animations`: Array of keyframe animations (name, duration, easing, keyframes) -- `transforms`: Common transform patterns -- `summary`: Statistics (total_animations, total_transitions, unique_easings) - -**Benefits**: -- ✅ Real animation values from production sites -- ✅ Captures all CSS transitions and @keyframes rules -- ✅ Identifies common easing functions and durations -- ✅ Maps animations to element selectors - ---- - -**Phase 1 Output**: `animations-{target}.json` (intermediate files) - -## Phase 2: Animation Question Generation (Agent Task 1) - -### Step 1: Check if Extraction Sufficient - -```bash -# If animations extracted from CSS, check coverage -IF animations_extracted: - total_animations = sum([data.summary.total_animations for data in all_extracted]) - total_transitions = sum([data.summary.total_transitions for data in all_extracted]) - - # If sufficient data found, skip interactive mode - IF total_animations >= 3 OR total_transitions >= 5: - REPORT: "✅ Sufficient animation data extracted from CSS" - SKIP to Phase 4 - ELSE: - REPORT: "⚠️ Limited animation data found - launching interactive mode" - extraction_insufficient = true -ELSE: - extraction_insufficient = true -``` - -### Step 2: Generate Animation Questions Using Agent +### Step 2: Generate Animation Specification Options (Agent Task 1) **Executor**: `Task(ui-design-agent)` -Launch agent to generate context-aware animation questions based on project needs: +**Conditional Logic**: Branch based on `refine_mode` flag ```javascript -Task(ui-design-agent): ` - [ANIMATION_QUESTION_GENERATION_TASK] - Generate contextual animation questions based on project context and focus types +IF NOT refine_mode: + // EXPLORATION MODE (default) + Task(ui-design-agent): ` + [ANIMATION_SPECIFICATION_GENERATION_TASK] + Generate context-aware animation specification questions - SESSION: {session_id} | MODE: interactive | BASE_PATH: {base_path} + SESSION: {session_id} | MODE: explore | BASE_PATH: {base_path} - ## Context Analysis - - Focus types: {focus_types} - - Design context: {has_design_context} - - Extracted animations: {animations_extracted ? "Available" : "None"} + ## Input Analysis + - Focus types: {focus_types.join(", ")} + - Design context: {has_design_context ? "Available" : "None"} + - Image references: {has_images ? "Available (" + image_count + " files)" : "None"} + ${has_images ? "- Image Data: Read from .intermediates/animation-analysis/image-references.json" : ""} - ## Question Categories to Consider - Based on focus_types, include relevant categories: - - "all" or "transitions": timing_scale, easing_philosophy - - "all" or "interactions" or "hover": button_interactions, card_interactions, input_interactions - - "all" or "page": page_transitions - - "all" or "loading": loading_states - - "all" or "scroll": scroll_animations + ## Analysis Rules + - Analyze image references (if available) to infer animation patterns from visual cues + - Generate questions covering timing, easing, interactions, and motion patterns + - Based on focus_types, include relevant categories: + * "all" or "transitions": timing_scale, easing_philosophy + * "all" or "interactions" or "hover": button_interactions, card_interactions, input_interactions + * "all" or "page": page_transitions + * "all" or "loading": loading_states + * "all" or "scroll": scroll_animations - ## Generate Question Structure + ## Generate Questions For each applicable category, create question with: 1. **Category ID** (e.g., "timing_scale", "button_interactions") 2. **Question text** (in Chinese, clear and concise) @@ -206,19 +206,21 @@ Task(ui-design-agent): ` - Option key (a, b, c, d, e) - Option label (brief description) - Option details (detailed explanation with technical specs) - - Recommended scenarios (when to use this option) + - Technical specs (duration values, easing curves, transform values) + - Visual preview (timeline representation or easing curve ASCII art) ## Output - Write single JSON file: {base_path}/.intermediates/animation-analysis/question-options.json + Write single JSON file: {base_path}/.intermediates/animation-analysis/analysis-options.json Use schema: { "metadata": { "generated_at": "", - "focus_types": ["..."], - "total_questions": + "focus_types": [...], + "total_questions": , + "has_css_data": }, - "questions": [ + "specification_options": [ { "id": 1, "category": "timing_scale", @@ -228,7 +230,33 @@ Task(ui-design-agent): ` "key": "a", "label": "快速敏捷", "details": "100-200ms 过渡,适合工具型应用和即时反馈场景", - "duration_range": "100-200ms" + "duration_values": {"fast": "100ms", "normal": "150ms", "slow": "200ms"}, + "visual_preview": { + "timeline": "0ms ━━━━━━━━━━ 150ms", + "description": "快速完成,几乎瞬时反馈" + } + }, + ... + ] + }, + { + "id": 2, + "category": "easing_philosophy", + "question": "您偏好什么样的动画缓动曲线?", + "options": [ + { + "key": "a", + "label": "自然缓动", + "details": "标准 ease-out,模拟自然减速", + "easing_curves": { + "ease-in": "cubic-bezier(0.4, 0, 1, 1)", + "ease-out": "cubic-bezier(0, 0, 0.2, 1)", + "ease-in-out": "cubic-bezier(0.4, 0, 0.2, 1)" + }, + "visual_preview": { + "curve_art": "│ ╱─\n│ ╱\n│ ╱\n│╱\n└─────", + "description": "快速启动,平滑减速" + } }, ... ] @@ -238,201 +266,472 @@ Task(ui-design-agent): ` } CRITICAL: Use Write() tool immediately after generating complete JSON -` -``` + ` -### Step 3: Verify Question File Created - -```bash -bash(test -f {base_path}/.intermediates/animation-analysis/question-options.json && echo "created") - -# Quick validation -bash(cat {base_path}/.intermediates/animation-analysis/question-options.json | grep -q "questions" && echo "valid") -``` - -**Output**: `question-options.json` with context-aware questions - ---- - -## Phase 3: Interactive Animation Specification (User Interaction) - -### Step 1: Load Generated Questions - -```bash -# Read generated questions from JSON file -question_data = Read({base_path}/.intermediates/animation-analysis/question-options.json) - -REPORT: "🤔 Interactive animation specification mode" -REPORT: " Context: {has_design_context ? 'Aligning with design tokens' : 'Standalone animation system'}" -REPORT: " Questions: {question_data.metadata.total_questions} questions loaded" -REPORT: " Focus: {question_data.metadata.focus_types}" -``` - -### Step 2: Present Questions to User - -```markdown -# Display questions from loaded JSON -REPORT: "" -REPORT: "===== 动画规格交互式配置 =====" -REPORT: "" - -FOR each question IN question_data.questions: - REPORT: "【问题{question.id} - {question.category}】{question.question}" - - FOR each option IN question.options: - REPORT: "{option.key}) {option.label}" - REPORT: " 说明:{option.details}" - - REPORT: "" - -REPORT: "支持格式:" -REPORT: "- 空格分隔:1a 2b 3c" -REPORT: "- 逗号分隔:1a,2b,3c" -REPORT: "- 自由组合:1a 2b,3c" -REPORT: "" -REPORT: "请输入您的选择:" -``` - -### Step 3: Wait for User Input (Main Flow) - -```javascript -# Wait for user input -user_raw_input = WAIT_FOR_USER_INPUT() - -# Store raw input for debugging -REPORT: "收到输入: {user_raw_input}" -``` - -### Step 4: Parse User Answers and Update JSON - -```javascript -# Intelligent input parsing (support multiple formats) -answers = {} - -# Parse input using intelligent matching -# Support formats: "1a 2b 3c", "1a,2b,3c", "1a 2b,3c" -parsed_responses = PARSE_USER_INPUT(user_raw_input, question_data.questions) - -# Validate parsing -IF parsed_responses.is_valid: - # Map question numbers to categories - FOR response IN parsed_responses.answers: - question_id = response.question_id - selected_option = response.option - - # Find category for this question - FOR question IN question_data.questions: - IF question.id == question_id: - category = question.category - answers[category] = selected_option - REPORT: "✅ 问题{question_id} ({category}): 选择 {selected_option}" - break ELSE: - REPORT: "❌ 输入格式无法识别,请参考格式示例重新输入:" - REPORT: " 示例:1a 2b 3c 4d" - # Return to Step 2 for re-input - GOTO Step 2 + // REFINEMENT MODE + Task(ui-design-agent): ` + [ANIMATION_REFINEMENT_OPTIONS_TASK] + Generate refinement options for existing animation system -// Update question-options.json with user selection -question_data.user_selection = { - "selected_at": NOW(), - "answers": answers -} + SESSION: {session_id} | MODE: refine | BASE_PATH: {base_path} -// Write updated file back -Write({base_path}/.intermediates/animation-analysis/question-options.json, JSON.stringify(question_data, indent=2)) + ## Load Existing Animation System + - Existing tokens: Read from {base_path}/animation-extraction/animation-tokens.json + - Focus types: {focus_types.join(", ")} + - Design context: {has_design_context ? "Available" : "None"} + ${has_images ? "- Image Data: Read from .intermediates/animation-analysis/image-references.json" : ""} -REPORT: "✅ Updated question-options.json with user selection" + ## Refinement Categories + Generate 8-12 refinement options across these categories: + + 1. **Timing Adjustments** (2-3 options): + - Duration scale: Faster timing across the board ↔ Slower, more deliberate timing + - Specific categories: Accelerate interactions only ↔ Extend page transitions + - Micro-timing: Adjust stagger delays ↔ Sequential animation gaps + + 2. **Easing Fine-Tuning** (2-3 options): + - Curve intensity: Sharper, snappier curves ↔ Softer, smoother curves + - Category-specific: Bouncier interactions ↔ Linear state changes + - Spring physics: Adjust bounce/damping parameters + + 3. **Context-Specific Variations** (2-3 options): + - Reduced motion: Adjust reduced-motion fallbacks + - Mobile optimization: Shorter durations for touch interactions + - Component-specific: Different hover styles for buttons vs cards + + 4. **Interaction Intensity** (1-2 options): + - Transform magnitude: Subtle movements (2-4px) ↔ Dramatic movements (8-12px) + - Scale adjustments: Minimal scale changes ↔ Bold scale emphasis + - Opacity ranges: Partial fades ↔ Full visibility transitions + + ## Generate Refinement Options + For each category, create option with: + 1. **Option ID** (sequential number) + 2. **Category** (timing_adjustments, easing_tuning, context_variations, interaction_intensity) + 3. **Label** (brief Chinese description, e.g., "加快整体节奏") + 4. **Description** (detailed explanation of changes) + 5. **Impact Scope** (which tokens will be modified) + 6. **Technical Changes** (specific value adjustments) + 7. **Before/After Preview** (show current vs proposed values) + + ## Output + Write single JSON file: {base_path}/.intermediates/animation-analysis/refinement-options.json + + Use schema: + { + "metadata": { + "generated_at": "", + "mode": "refinement", + "existing_tokens_loaded": true, + "total_refinements": + }, + "current_animation_system": { + // Copy from animation-tokens.json for reference + }, + "refinement_options": [ + { + "id": 1, + "category": "timing_adjustments", + "label": "加快整体动画节奏", + "description": "将所有 duration 值减少 30%,使界面响应更快速", + "impact_scope": "duration.fast, duration.normal, duration.slow", + "technical_changes": { + "duration.fast": {"from": "150ms", "to": "105ms"}, + "duration.normal": {"from": "300ms", "to": "210ms"}, + "duration.slow": {"from": "500ms", "to": "350ms"} + }, + "preview": { + "before": "Normal button hover: 150ms", + "after": "Faster button hover: 105ms" + } + }, + ... + ] + } + + CRITICAL: Use Write() tool immediately after generating complete JSON + ` ``` +### Step 3: Verify Options File Created + +```bash +IF NOT refine_mode: + # Exploration mode: Check for analysis-options.json + bash(test -f {base_path}/.intermediates/animation-analysis/analysis-options.json && echo "created") + bash(cat {base_path}/.intermediates/animation-analysis/analysis-options.json | grep -q "specification_options" && echo "valid") +ELSE: + # Refinement mode: Check for refinement-options.json + bash(test -f {base_path}/.intermediates/animation-analysis/refinement-options.json && echo "created") + bash(cat {base_path}/.intermediates/animation-analysis/refinement-options.json | grep -q "refinement_options" && echo "valid") +``` + +**Output**: +- Exploration mode: `analysis-options.json` with animation specification questions +- Refinement mode: `refinement-options.json` with refinement options + --- -**Phase 3 Output**: Updated `question-options.json` with user answers embedded +**Phase 1 Output**: +- Exploration mode: `analysis-options.json` with generated specification questions +- Refinement mode: `refinement-options.json` with refinement options -## Phase 4: Animation Token Synthesis (Agent - No User Interaction) +## Phase 1.5: User Confirmation (Optional - Triggered by --interactive) -**Executor**: `Task(ui-design-agent)` for token generation +**Purpose**: Allow user to answer animation specification questions (exploration) or select refinement options (refinement) before generating tokens -**⚠️ CRITICAL**: This phase has NO user interaction. Agent only reads existing data and generates tokens. +**Trigger Condition**: Execute this phase ONLY if `--interactive` flag is present -### Step 1: Load All Input Sources +### Step 1: Check Interactive Flag ```bash -# Gather all available animation data -extracted_animations = [] -IF animations_extracted: - FOR target IN target_list: - IF exists({base_path}/.intermediates/animation-analysis/animations-{target}.json): - extracted_animations.append(Read(file)) +# Skip this entire phase if --interactive flag is not present +IF NOT --interactive: + SKIP to Phase 2 + REPORT: "ℹ️ Non-interactive mode: Using CSS extraction + default animation preferences" -# Read user answers from question-options.json -question_data = null -IF exists({base_path}/.intermediates/animation-analysis/question-options.json): - question_data = Read({base_path}/.intermediates/animation-analysis/question-options.json) - IF question_data.user_selection: - REPORT: "✅ Loaded user answers from question-options.json" +REPORT: "🎯 Interactive mode enabled: User answers required" +``` + +### Step 2: Load and Present Options + +```bash +# Read options file based on mode +IF NOT refine_mode: + # Exploration mode + options = Read({base_path}/.intermediates/animation-analysis/analysis-options.json) + specification_options = options.specification_options +ELSE: + # Refinement mode + options = Read({base_path}/.intermediates/animation-analysis/refinement-options.json) + refinement_options = options.refinement_options +``` + +### Step 3: Present Options to User + +**Conditional Display**: Branch based on `refine_mode` flag + +``` +IF NOT refine_mode: + // EXPLORATION MODE + 📋 Animation Specification Questions + + We've generated {options.metadata.total_questions} questions to define your animation system. + Please answer each question to customize the animation behavior. + + {FOR each question in specification_options: + ═══════════════════════════════════════════════════ + Question {question.id}: {question.question} + Category: {question.category} + ═══════════════════════════════════════════════════ + + {FOR each option in question.options: + {option.key}) {option.label} + {option.details} + + ${option.visual_preview ? "Preview:\n " + option.visual_preview.timeline || option.visual_preview.curve_art || option.visual_preview.animation_sequence : ""} + ${option.visual_preview ? " " + option.visual_preview.description : ""} + + ${option.duration_values ? "Durations: " + JSON.stringify(option.duration_values) : ""} + ${option.easing_curves ? "Easing: " + JSON.stringify(option.easing_curves) : ""} + ${option.transform_value ? "Transform: " + option.transform_value : ""} + } + + ═══════════════════════════════════════════════════ + } + +ELSE: + // REFINEMENT MODE + 🔧 Animation System Refinement Options + + We've generated {options.metadata.total_refinements} refinement options to fine-tune your animation system. + Select which refinements to apply (can select multiple). + + {FOR each refinement in refinement_options: + ═══════════════════════════════════════════════════ + Option {refinement.id}: {refinement.label} + Category: {refinement.category} + ═══════════════════════════════════════════════════ + + Description: {refinement.description} + Impact Scope: {refinement.impact_scope} + + Technical Changes: + {FOR each token, changes IN refinement.technical_changes: + • {token}: + Before: {changes.from} + After: {changes.to} + } + + Preview: + {refinement.preview.before} → {refinement.preview.after} + + ═══════════════════════════════════════════════════ + } +``` + +### Step 4: Capture User Selection + +**Conditional Interaction**: Branch based on `refine_mode` flag + +```javascript +IF NOT refine_mode: + // EXPLORATION MODE - Single selection per question + user_answers = {} + + FOR each question IN specification_options: + AskUserQuestion({ + questions: [{ + question: question.question, + header: question.category, + multiSelect: false, // Single selection per question + options: [ + {FOR each option IN question.options: + label: "{option.key}) {option.label}", + description: option.details + } + ] + }] + }) + + // Parse user response (single selection, e.g., "a) Fast & Snappy") + selected_option_text = user_answer + + // Check for user cancellation + IF selected_option_text == null: + REPORT: "⚠️ User canceled selection. Using default animation preferences." + EXIT Phase 1.5 + + // Extract option key from selection text + match = selected_option_text.match(/^([a-e])\)/) + IF match: + selected_key = match[1] + user_answers[question.category] = selected_key + REPORT: "✅ {question.category}: Selected option {selected_key}" + ELSE: + ERROR: "Invalid selection format. Expected 'a) ...' format" + EXIT workflow + + REPORT: "✅ Collected {Object.keys(user_answers).length} animation preferences" + +ELSE: + // REFINEMENT MODE - Multi-selection of refinements + AskUserQuestion({ + questions: [{ + question: "Which refinement(s) would you like to apply to your animation system?", + header: "Refinements", + multiSelect: true, // Can select multiple refinements + options: [ + {FOR each refinement IN refinement_options: + label: "{refinement.id}. {refinement.label}", + description: "{refinement.description} (Affects: {refinement.impact_scope})" + } + ] + }] + }) + + // Parse user response (multi-selection) + selected_refinements = user_answer + + // Check for user cancellation + IF selected_refinements == null: + REPORT: "⚠️ User canceled selection. No refinements will be applied." + EXIT Phase 1.5 + + // Extract refinement IDs + selected_ids = [] + FOR each selection IN selected_refinements: + match = selection.match(/^(\d+)\./) + IF match: + selected_ids.push(parseInt(match[1])) + + REPORT: "✅ Selected {selected_ids.length} refinement(s) to apply" +``` + +### Step 5: Update Options File with User Selection + +```bash +IF NOT refine_mode: + # EXPLORATION MODE - Update analysis-options.json + options.user_selection = { + "selected_at": "{current_timestamp}", + "session_id": "{session_id}", + "answers": user_answers // {category: selected_key} + } + + # Write updated file back + Write({base_path}/.intermediates/animation-analysis/analysis-options.json, JSON.stringify(options, indent=2)) + + # Verify + bash(test -f {base_path}/.intermediates/animation-analysis/analysis-options.json && echo "saved") + +ELSE: + # REFINEMENT MODE - Update refinement-options.json + options.user_selection = { + "selected_at": "{current_timestamp}", + "session_id": "{session_id}", + "selected_refinements": selected_ids // Array of refinement IDs + } + + # Write updated file back + Write({base_path}/.intermediates/animation-analysis/refinement-options.json, JSON.stringify(options, indent=2)) + + # Verify + bash(test -f {base_path}/.intermediates/animation-analysis/refinement-options.json && echo "saved") +``` + +### Step 6: Confirmation Message + +``` +IF NOT refine_mode: + // EXPLORATION MODE + ✅ Animation preferences recorded! + + You selected: + {FOR each category, selected_key IN user_answers: + question = find(specification_options, q => q.category == category) + option = find(question.options, o => o.key == selected_key) + • {category}: {option.label} + ({option.details}) + } + + Proceeding to generate animation system with your preferences... + +ELSE: + // REFINEMENT MODE + ✅ Refinement selections recorded! + + You selected {selected_ids.length} refinement(s): + {FOR each id IN selected_ids: + refinement = find(refinement_options, r => r.id == id) + • {refinement.label} ({refinement.category}) + Impact: {refinement.impact_scope} + } + + Proceeding to apply refinements to animation system... +``` + +**Output**: +- Exploration mode: Updated `analysis-options.json` with embedded `user_selection` field +- Refinement mode: Updated `refinement-options.json` with `user_selection.selected_refinements` array + +## Phase 2: Animation System Generation (Agent Task 2) + +**Executor**: `Task(ui-design-agent)` for animation token generation + +### Step 1: Load User Selection or Use Defaults + +```bash +IF NOT refine_mode: + # EXPLORATION MODE - Read analysis-options.json + options = Read({base_path}/.intermediates/animation-analysis/analysis-options.json) + specification_options = options.specification_options + + # Check if user_selection field exists (interactive mode) + IF options.user_selection AND options.user_selection.answers: + # Interactive mode: Use user-selected preferences + user_answers = options.user_selection.answers + REPORT: "🎯 Interactive mode: Using user-selected animation preferences" ELSE: - REPORT: "⚠️ No user selection found in question-options.json" - question_data = null -ELSE: - REPORT: "⚠️ No question-options.json found - using extracted CSS only" + # Non-interactive mode: Use defaults (first option for each question) + user_answers = null + REPORT: "ℹ️ Non-interactive mode: Using default animation preferences" -design_tokens = null -IF has_design_context: - design_tokens = Read({base_path}/style-extraction/style-1/design-tokens.json) +ELSE: + # REFINEMENT MODE - Read refinement-options.json + options = Read({base_path}/.intermediates/animation-analysis/refinement-options.json) + refinement_options = options.refinement_options + + # Check if user_selection field exists (interactive mode) + IF options.user_selection AND options.user_selection.selected_refinements: + # Interactive mode: Use user-selected refinements + selected_refinements = options.user_selection.selected_refinements + REPORT: "🎯 Interactive mode: Applying {selected_refinements.length} selected refinement(s)" + ELSE: + # Non-interactive mode: Apply all refinements + selected_refinements = null + REPORT: "ℹ️ Non-interactive mode: Applying all refinements" + +# Load image references if available for agent context +image_context = null +IF has_images: + IF exists({base_path}/.intermediates/animation-analysis/image-references.json): + image_context = Read({base_path}/.intermediates/animation-analysis/image-references.json) + REPORT: "📸 Using {image_context.count} image reference(s) for animation inference" ``` -### Step 2: Launch Token Generation Task (Pure Synthesis) +### Step 2: Create Output Directory + +```bash +# Create directory for animation system +bash(mkdir -p {base_path}/animation-extraction) +``` + +### Step 3: Launch Animation Generation Task + +**Conditional Task**: Branch based on `refine_mode` flag ```javascript -Task(ui-design-agent): ` - [ANIMATION_TOKEN_GENERATION_TASK] - Synthesize animation data into production-ready tokens - NO user interaction +IF NOT refine_mode: + // EXPLORATION MODE + Task(ui-design-agent): ` + [ANIMATION_SYSTEM_GENERATION_TASK] + Generate production-ready animation system based on user preferences and CSS extraction - SESSION: {session_id} | BASE_PATH: {base_path} + SESSION: {session_id} | MODE: explore | BASE_PATH: {base_path} - ## ⚠️ CRITICAL: Pure Synthesis Task - - NO user questions or interaction - - READ existing specification files ONLY - - Generate tokens based on available data + USER PREFERENCES: + ${user_answers ? "- User Selection: " + JSON.stringify(user_answers) : "- Using Defaults: First option for each category"} + ${user_answers ? "- Specification Options: Read from .intermediates/animation-analysis/analysis-options.json for detailed specs" : ""} - ## Input Sources (Read-Only) - 1. **Extracted CSS Animations** (if available): - ${extracted_animations.length > 0 ? JSON.stringify(extracted_animations) : "None - skip CSS data"} + ## Input Analysis + - Interactive mode: {user_answers ? "Yes (user preferences available)" : "No (using defaults)"} + - Image references: {image_context ? "Available (" + image_context.count + " files)" : "None"} + ${image_context ? "- Image Data: " + JSON.stringify(image_context) : ""} + - Design context: {has_design_context ? "Available" : "None"} + ${has_design_context ? "- Design Tokens: Read from style-extraction/style-1/design-tokens.json" : ""} - 2. **User Answers** (REQUIRED if Phase 2-3 ran): - File: {base_path}/.intermediates/animation-analysis/question-options.json - ${question_data ? "Status: ✅ Found - READ this file for user choices in user_selection field" : "Status: ⚠️ Not found - use CSS extraction only"} + ## Generation Rules + ${user_answers ? ` + - Read analysis-options.json to get user_selection.answers + - For each category in user_selection.answers, find the selected option + - Use the selected option's technical specs (duration_values, easing_curves, transform_value, etc.) + - Apply these specs to generate animation tokens + ` : ` + - Use first option (key "a") from each question in specification_options as default + - Extract technical specs from default options + `} + - Infer animation patterns from image references (if available) + - Align with design tokens (spacing, colors) if available + - All tokens use CSS Custom Property format: var(--duration-fast) + - WCAG-compliant: Respect prefers-reduced-motion + - Semantic naming for all animation values - 3. **Design Tokens Context** (for alignment): - ${design_tokens ? JSON.stringify(design_tokens) : "None - standalone animation system"} - - ## Synthesis Rules - - ### Priority System - 1. User answers from question-options.json user_selection field (highest priority) - 2. Extracted CSS values from animations-*.json (medium priority) + ## Synthesis Priority + 1. User answers from analysis-options.json user_selection field (highest priority) + 2. Inferred patterns from image references (medium priority) 3. Industry best practices (fallback) - ### Duration Normalization - - IF question_data.user_selection.answers.timing_scale EXISTS: - Map user's answer to duration scale using question_data.questions definitions - - ELSE IF extracted CSS durations available: - Cluster extracted durations into 3-5 semantic scales + ## Duration Normalization + - IF user_selection.answers.timing_scale EXISTS: + Find selected option in specification_options + Use option's duration_values for token generation + - ELSE IF image references available: + Infer timing patterns from visual design style (minimalist → faster, ornate → slower) - ELSE: Use standard scale (instant:0ms, fast:150ms, normal:300ms, slow:500ms, very-slow:800ms) - - Align with design token spacing scale if available - ### Easing Standardization - - IF question_data.user_selection.answers.easing_philosophy EXISTS: - Map user's answer to easing curve using question_data.questions definitions - - ELSE IF extracted CSS easings available: - Identify common easing functions from CSS + ## Easing Standardization + - IF user_selection.answers.easing_philosophy EXISTS: + Find selected option in specification_options + Use option's easing_curves for token generation + - ELSE IF image references available: + Infer easing preferences from visual style (sharp edges → snappy, soft curves → smooth) - ELSE: - Use standard easings - - Map to semantic names and convert to cubic-bezier format + Use standard easings (linear, ease-in, ease-out, ease-in-out, spring) - ### Animation Categorization + ## Animation Categorization Organize into: - **duration**: Timing scale (instant, fast, normal, slow, very-slow) - **easing**: Easing functions (linear, ease-in, ease-out, ease-in-out, spring) @@ -442,18 +741,6 @@ Task(ui-design-agent): ` - **page_transitions**: Route/view change animations (if user enabled) - **scroll_animations**: Scroll-triggered animations (if user enabled) - ### User Answers Integration - IF question_data.user_selection EXISTS: - - Map user answers to token values using question definitions: - * answers.timing_scale → duration values (use question options for specs) - * answers.easing_philosophy → easing curves (use question options for specs) - * answers.button_interactions → interactions.button-hover token - * answers.card_interactions → interactions.card-hover token - * answers.input_interactions → micro-interaction tokens - * answers.page_transitions → page_transitions tokens - * answers.loading_states → loading state tokens - * answers.scroll_animations → scroll_animations tokens - ## Generate Files ### 1. animation-tokens.json @@ -462,7 +749,7 @@ Task(ui-design-agent): ` { "duration": { "instant": "0ms", - "fast": "150ms", # Adjust based on user_specification.timing_scale + "fast": "150ms", # From user_selection or CSS extraction or default "normal": "300ms", "slow": "500ms", "very-slow": "800ms" @@ -470,7 +757,7 @@ Task(ui-design-agent): ` "easing": { "linear": "linear", "ease-in": "cubic-bezier(0.4, 0, 1, 1)", - "ease-out": "cubic-bezier(0, 0, 0.2, 1)", # Adjust based on user_specification.easing_philosophy + "ease-out": "cubic-bezier(0, 0, 0.2, 1)", # From user_selection or CSS extraction or default "ease-in-out": "cubic-bezier(0.4, 0, 0.2, 1)", "spring": "cubic-bezier(0.34, 1.56, 0.64, 1)" }, @@ -494,88 +781,142 @@ Task(ui-design-agent): ` "keyframes": { "fadeIn": {"0%": {"opacity": "0"}, "100%": {"opacity": "1"}}, "slideInUp": {"0%": {"transform": "translateY(20px)", "opacity": "0"}, "100%": {"transform": "translateY(0)", "opacity": "1"}}, - "pulse": {"0%, 100%": {"opacity": "1"}, "50%": {"opacity": "0.7"}}, - # Add more keyframes based on user_specification choices + "pulse": {"0%, 100%": {"opacity": "1"}, "50%": {"opacity": "0.7"}} }, "interactions": { "button-hover": { - # Map from user_specification.interactions.button + # From user_selection.answers.button_interactions or CSS extraction or default "properties": ["background-color", "transform"], "duration": "var(--duration-fast)", "easing": "var(--easing-ease-out)", "transform": "scale(1.02)" }, "card-hover": { - # Map from user_specification.interactions.card + # From user_selection.answers.card_interactions or CSS extraction or default "properties": ["box-shadow", "transform"], "duration": "var(--duration-normal)", "easing": "var(--easing-ease-out)", "transform": "translateY(-4px)" } - # Add input-focus, modal-open, dropdown-toggle based on user choices }, "page_transitions": { - # IF user_specification.page_transitions.enabled == true + # IF user_selection.answers.page_transitions enabled "fade": { "duration": "var(--duration-normal)", "enter": "fadeIn", "exit": "fadeOut" } - # Add slide, zoom based on user_specification.page_transitions.style }, "scroll_animations": { - # IF user_specification.scroll_animations.enabled == true + # IF user_selection.answers.scroll_animations enabled "default": { - "animation": "fadeIn", # From user_specification.scroll_animations.style + "animation": "fadeIn", "duration": "var(--duration-slow)", "easing": "var(--easing-ease-out)", - "threshold": "0.1", - "stagger_delay": "100ms" # From user_specification if stagger chosen + "threshold": "0.1" } } } - ### 2. animation-guide.md - Comprehensive usage guide with sections: - - **Animation Philosophy**: Rationale from user choices and CSS analysis - - **Duration Scale**: Explanation of timing values and usage contexts - - **Easing Functions**: When to use each easing curve - - **Transition Presets**: Property-specific transition guidelines - - **Keyframe Animations**: Available animations and use cases - - **Interaction Patterns**: Button, card, input animation examples - - **Page Transitions**: Route change animation implementation (if enabled) - - **Scroll Animations**: Scroll-trigger setup and configuration (if enabled) - - **Implementation Examples**: CSS and JavaScript code samples - - **Accessibility**: prefers-reduced-motion media query setup - - **Performance Best Practices**: Hardware acceleration, will-change usage - ## Output File Paths - animation-tokens.json: {base_path}/animation-extraction/animation-tokens.json - - animation-guide.md: {base_path}/animation-extraction/animation-guide.md ## Critical Requirements - - ✅ READ question-options.json if it exists (from Phase 2-3) - - ✅ Use Write() tool immediately for both files + - ✅ Use Write() tool immediately to generate JSON file - ✅ All tokens use CSS Custom Property format: var(--duration-fast) - ✅ Include prefers-reduced-motion media query guidance - ✅ Validate all cubic-bezier values are valid (4 numbers between 0-1) + - ${user_answers ? "✅ READ analysis-options.json for user_selection field" : "✅ Use first option from each question as default"} - ❌ NO user questions or interaction in this phase - - ❌ NO external research or MCP calls -` + - ✅ Can use Exa MCP to research modern animation patterns and obtain code examples (Explore/Text mode) + ` + +ELSE: + // REFINEMENT MODE + Task(ui-design-agent): ` + [ANIMATION_SYSTEM_REFINEMENT_TASK] + Apply selected refinements to existing animation system + + SESSION: {session_id} | MODE: refine | BASE_PATH: {base_path} + + ## Load Existing Animation System + - Current tokens: Read from {base_path}/animation-extraction/animation-tokens.json + - Refinement options: Read from .intermediates/animation-analysis/refinement-options.json + + REFINEMENT SELECTION: + ${selected_refinements ? ` + - Interactive mode: Apply selected refinements + - Selected IDs: ${JSON.stringify(selected_refinements)} + - For each ID in selected_refinements: + * Find refinement in refinement_options by id + * Apply technical_changes to corresponding tokens + ` : ` + - Non-interactive mode: Apply ALL refinements + - For each refinement in refinement_options: + * Apply technical_changes to corresponding tokens + `} + + ## Input Analysis + - Image references: {image_context ? "Available (" + image_context.count + " files)" : "None"} + ${image_context ? "- Image Data: " + JSON.stringify(image_context) : ""} + - Design context: {has_design_context ? "Available" : "None"} + ${has_design_context ? "- Design Tokens: Read from style-extraction/style-1/design-tokens.json" : ""} + + ## Refinement Application Rules + ${selected_refinements ? ` + - ONLY apply refinements with IDs in selected_refinements array + - Skip refinements not selected by user + ` : ` + - Apply ALL refinements from refinement_options + - Combine multiple refinements that affect same token + `} + - Load current animation-tokens.json + - For each applicable refinement: + * Parse technical_changes field + * Apply "to" values to replace "from" values in tokens + * Preserve structure and var() references + - If multiple refinements affect same token, apply in sequence + - Maintain WCAG compliance and semantic naming + - All tokens use CSS Custom Property format: var(--duration-fast) + + ## Conflict Resolution + - If multiple selected refinements modify same token: + * Apply refinements in ID order (lowest first) + * Later refinements override earlier ones + + ## Generate Updated Files + + ### 1. animation-tokens.json + Updated animation token structure with refinements applied: + - Load existing structure + - Apply technical_changes from selected/all refinements + - Maintain var() references and semantic naming + - Validate all cubic-bezier values + + ## Output File Paths + - animation-tokens.json: {base_path}/animation-extraction/animation-tokens.json (OVERWRITE) + + ## Critical Requirements + - ✅ Use Write() tool immediately to generate JSON file + - ✅ OVERWRITE existing animation-tokens.json with refined version + - ✅ All tokens use CSS Custom Property format: var(--duration-fast) + - ✅ Include prefers-reduced-motion media query guidance + - ✅ Validate all cubic-bezier values are valid (4 numbers between 0-1) + - ${selected_refinements ? "✅ READ refinement-options.json for user_selection.selected_refinements" : "✅ Apply ALL refinements from refinement_options"} + - ❌ NO user questions or interaction in this phase + - ✅ Can use Exa MCP to research modern animation patterns and obtain code examples (Explore/Text mode) + ` ``` ---- +**Output**: Agent generates/updates animation-tokens.json -**Phase 4 Output**: `animation-tokens.json` + `animation-guide.md` - -## Phase 5: Verify Output +## Phase 3: Verify Output ### Step 1: Check Files Created ```bash -# Verify animation tokens created +# Verify animation system created bash(test -f {base_path}/animation-extraction/animation-tokens.json && echo "exists") -bash(test -f {base_path}/animation-extraction/animation-guide.md && echo "exists") # Validate structure bash(cat {base_path}/animation-extraction/animation-tokens.json | grep -q "duration" && echo "valid") @@ -588,7 +929,7 @@ bash(cat {base_path}/animation-extraction/animation-tokens.json | grep -q "easin bash(ls -lh {base_path}/animation-extraction/) ``` -**Output**: 2 files verified (animation-tokens.json, animation-guide.md) +**Output**: animation-tokens.json verified ## Completion @@ -597,11 +938,11 @@ bash(ls -lh {base_path}/animation-extraction/) ```javascript TodoWrite({todos: [ {content: "Setup and input validation", status: "completed", activeForm: "Validating inputs"}, - {content: "CSS animation extraction (auto mode)", status: "completed", activeForm: "Extracting from CSS"}, - {content: "Question generation (agent)", status: "completed", activeForm: "Generating questions"}, - {content: "Interactive specification (user input)", status: "completed", activeForm: "Collecting user answers"}, - {content: "Animation token synthesis (agent - no interaction)", status: "completed", activeForm: "Generating tokens via agent"}, - {content: "Verify output files", status: "completed", activeForm: "Verifying files"} + {content: "CSS animation extraction (Phase 1)", status: "completed", activeForm: "Extracting from CSS"}, + {content: "Specification generation (Phase 1 - Agent)", status: "completed", activeForm: "Generating questions"}, + {content: "User confirmation (Phase 1.5 - Optional)", status: "completed", activeForm: "Collecting user answers"}, + {content: "Animation system generation (Phase 2 - Agent)", status: "completed", activeForm: "Generating animation system"}, + {content: "Verify output files (Phase 3)", status: "completed", activeForm: "Verifying files"} ]}); ``` @@ -612,13 +953,16 @@ TodoWrite({todos: [ Configuration: - Session: {session_id} -- Extraction Mode: {extraction_mode} (auto/interactive) +- Interactive Mode: {interactive_mode ? "Enabled (user preferences collected)" : "Disabled (default preferences)"} - Input Sources: - {IF animations_extracted: - - ✅ CSS extracted from {len(url_list)} URL(s) + {IF has_images: + - ✅ Image references analyzed ({image_count} file(s)) } - {IF question_data AND question_data.user_selection: - - ✅ User answers via interactive mode (agent-generated questions) + {IF interactive_mode AND options.user_selection: + - ✅ User preferences collected via interactive mode + } + {IF NOT interactive_mode: + - ℹ️ Using default animation preferences (no user interaction) } {IF has_design_context: - ✅ Aligned with existing design tokens @@ -626,18 +970,15 @@ Configuration: Generated Files: {base_path}/animation-extraction/ -├── animation-tokens.json # Production-ready animation tokens -└── animation-guide.md # Usage guidelines and examples +└── animation-tokens.json # Production-ready animation tokens -{IF animations_extracted OR question_data: +{IF has_images OR options.user_selection: Intermediate Analysis: {base_path}/.intermediates/animation-analysis/ -{IF animations_extracted: -├── animations-*.json # Extracted CSS data ({len(url_list)} files) -} -{IF question_data: -└── question-options.json # Generated questions + user answers +{IF has_images: +├── image-references.json # Image reference metadata ({image_count} files) } +├── analysis-options.json # Generated questions{options.user_selection ? " + user answers" : ""} } Extracted Data Summary: @@ -694,11 +1035,10 @@ bash(ls {base_path}/animation-extraction/) {base_path}/ ├── .intermediates/ # Intermediate analysis files │ └── animation-analysis/ -│ ├── animations-{target}.json # Extracted CSS (auto mode) -│ └── question-options.json # Generated questions + user answers (interactive mode) -└── animation-extraction/ # Final animation tokens - ├── animation-tokens.json # Production-ready animation tokens - └── animation-guide.md # Usage guide and examples +│ ├── animations-{target}.json # Extracted CSS (URL mode only) +│ └── analysis-options.json # Generated questions + user answers (embedded) +└── animation-extraction/ # Final animation system + └── animation-tokens.json # Production-ready animation tokens ``` ## animation-tokens.json Format @@ -743,14 +1083,11 @@ bash(ls {base_path}/animation-extraction/) ### Common Errors ``` -ERROR: No URL or interactive mode specified -→ Provide --urls for auto mode or use --mode interactive +ERROR: No image references found +→ Provide valid --images glob pattern or proceed with prompt-only mode -ERROR: Chrome DevTools unavailable -→ Automatically falls back to interactive mode - -ERROR: Insufficient animation data extracted -→ Launches interactive mode for supplemental input +ERROR: Invalid image format +→ Skips unsupported files, continues with valid images ERROR: Invalid cubic-bezier values → Validates and corrects to nearest standard easing @@ -758,36 +1095,22 @@ ERROR: Invalid cubic-bezier values ### Recovery Strategies -- **CSS extraction failure**: Falls back to interactive mode -- **Partial extraction**: Supplements with interactive questioning +- **Image loading failure**: Falls back to prompt-only specification mode +- **Partial image set**: Supplements with default values and best practices - **Invalid data**: Validates and uses fallback values ## Key Features -- **Auto-Trigger CSS Extraction** - Automatically extracts animations when --urls provided -- **Hybrid Strategy** - Combines CSS extraction with interactive specification -- **Agent-Generated Questions** - Context-aware questions generated by agent (Phase 2) -- **User Interaction** - User answers questions in main flow (Phase 3) -- **Intelligent Fallback** - Gracefully handles extraction failures +- **Prompt & Image Inference** - Analyzes design intent from textual descriptions and visual references (Phase 0) +- **Agent-Generated Questions** - Context-aware specification questions with visual previews (Phase 1) +- **Visual Previews** - Timeline representations, easing curve ASCII art, and animation sequences for each option +- **Optional User Interaction** - User answers questions only when `--interactive` flag present (Phase 1.5) +- **Non-Interactive Mode** - Default behavior uses inferred patterns + best practices (no user questions) +- **Hybrid Strategy** - Combines image analysis with user preferences (when interactive) +- **No MCP Dependencies** - Pure AI-driven inference from visual and textual inputs - **Context-Aware** - Aligns with existing design tokens - **Production-Ready** - CSS var() format, accessibility support - **Comprehensive Coverage** - Transitions, keyframes, interactions, scroll animations -- **Separated Concerns** - Question generation (Phase 2 agent) → User answers (Phase 3) → Token generation (Phase 4 agent) +- **Clear Phase Separation** - Question generation (Agent) → User confirmation (Optional) → Token synthesis (Agent) -## Integration -**Workflow Position**: Between style extraction and layout extraction (or parallel) - -**New Workflow**: -1. `/workflow:ui-design:style-extract` → `design-tokens.json` + `style-guide.md` -2. **`/workflow:ui-design:animation-extract`** → `animation-tokens.json` + `animation-guide.md` (NEW) -3. `/workflow:ui-design:layout-extract` → `layout-templates.json` -4. `/workflow:ui-design:generate`: - - Reads: design-tokens.json + animation-tokens.json + layout-templates.json - - Generates: Prototypes with animation CSS included - -**Input**: URLs (auto mode) or interactive questioning -**Output**: `animation-tokens.json` + `animation-guide.md` -**Next**: `/workflow:ui-design:layout-extract` OR `/workflow:ui-design:generate` - -**Note**: This command extracts motion design patterns (animations, transitions) to complement visual style tokens. Can run in parallel with layout-extract. diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/capture.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/capture.md index 9ca4d5dd..c080ee09 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/ui-design/capture.md +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/capture.md @@ -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 ] [--session ] 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 diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/codify-style.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/codify-style.md new file mode 100644 index 00000000..643b684f --- /dev/null +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/codify-style.md @@ -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: " [--package-name ] [--output-dir ] [--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 --package-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 [OPTIONS] + +# Required + Source code directory to analyze + +# Optional +--package-name Custom name for the style reference package + (default: auto-generated from directory name) +--output-dir 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: " + REPORT: "USAGE: /workflow:ui-design:codify-style [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 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 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 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 "○") +``` + + + +**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 +``` diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/explore-auto.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/explore-auto.md index 0c5d3a36..c49f2f88 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/ui-design/explore-auto.md +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/explore-auto.md @@ -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 ""] [--images ""] [--targets ""] [--target-type "page|component"] [--session ] [--style-variants ] [--layout-variants ] [--batch-plan]"" +argument-hint: "[--input ""] [--targets ""] [--target-type "page|component"] [--session ] [--style-variants ] [--layout-variants ] [--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 ""`: 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 ""`: Reference image paths (shows deprecation warning) +- `--prompt ""`: Design description (shows deprecation warning) + **Optional Parameters** (all have smart defaults): - `--targets ""`: 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 `: Workflow session ID (standalone mode if omitted) -- `--images ""`: Reference image paths (default: `design-refs/*`) -- `--prompt ""`: Design style and target description - `--style-variants `: Style variants (default: inferred from prompt or 3, range: 1-5) - `--layout-variants `: 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 ""`: Alias for `--targets` with `--target-type page` - `--components ""`: 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) diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/explore-layers.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/explore-layers.md index 4d71c632..c0f157ce 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/ui-design/explore-layers.md +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/explore-layers.md @@ -1,7 +1,7 @@ --- name: explore-layers description: Interactive deep UI capture with depth-controlled layer exploration using MCP puppeteer -argument-hint: --url --depth <1-5> [--session id] [--base-path path] +argument-hint: --url --depth <1-5> [--design-id ] [--session ] 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) ``` diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/generate.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/generate.md index 752b8dd0..c8cb5f7b 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/ui-design/generate.md +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/generate.md @@ -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 ] [--session ] +description: Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation +argument-hint: [--design-id ] [--session ] 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: , , - - CSS link: - - 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: , , + - CSS link: + - 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 + - ✅ CSS filename MUST match HTML + + ## 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: , 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 diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/imitate-auto.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/imitate-auto.md index d3bb9c67..8bcc4472 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/ui-design/imitate-auto.md +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/imitate-auto.md @@ -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 "" [--capture-mode ] [--depth <1-5>] [--session ] [--prompt ""] +description: UI design workflow with direct code/image input for design token extraction and prototype generation +argument-hint: "[--input ""] [--session ]" 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 ""`: 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 ""`: 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 ""`: Reference image paths (shows deprecation warning) +- `--prompt ""`: Design description (shows deprecation warning) **Optional Parameters**: -- `--capture-mode ` (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 ` (Optional): Workflow session ID +- `--session `: 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 ""` (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] ``` diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/import-from-code.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/import-from-code.md index eb4d2638..756e2d12 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/ui-design/import-from-code.md +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/import-from-code.md @@ -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 ] [--source ] [--css \"\"] [--js \"\"] [--scss \"\"] [--html \"\"] [--style-files \"\"] [--session ]" +description: Import design system from code files (CSS/JS/HTML/SCSS) with automatic file discovery and parallel agent analysis +argument-hint: "[--design-id ] [--session ] [--source ]" 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 Output directory for extracted design tokens (default: current directory) ---source Source code directory to analyze (default: base-path) ---css "" CSS file glob pattern (e.g., "theme/*.css") ---scss "" SCSS file glob pattern (e.g., "styles/*.scss") ---js "" JavaScript file glob pattern (e.g., "theme/*.js") ---html "" HTML file glob pattern (e.g., "pages/*.html") ---style-files "" Universal style file glob (applies to CSS/SCSS/JS) ---session Session identifier for workflow tracking +--design-id Design run ID to import into (must exist) +--session Session ID (uses latest design run in session) +--source 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" ``` @@ -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**: -```json -[ - {"content": "Phase 0: 发现和分类代码文件", "status": "completed", "activeForm": "发现代码文件"}, - {"content": "Phase 1: 并行Agent分析并生成completeness-report.json", "status": "in_progress", "activeForm": "生成design system"} -] -``` + --- @@ -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**: -```json -[ - {"content": "Phase 0: 发现和分类代码文件", "status": "completed", "activeForm": "发现代码文件"}, - {"content": "Phase 1: 并行Agent分析并生成completeness-report.json", "status": "completed", "activeForm": "生成design system"} -] -``` + --- @@ -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 diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/layout-extract.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/layout-extract.md index 1baed642..68e8621d 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/ui-design/layout-extract.md +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/layout-extract.md @@ -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 ] [--session ] [--images ""] [--urls ""] [--prompt ""] [--targets ""] [--variants ] [--device-type ] [--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 ] [--session ] [--images ""] [--urls ""] [--prompt ""] [--targets ""] [--variants ] [--device-type ] [--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` diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/list.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/list.md new file mode 100644 index 00000000..11ccafe0 --- /dev/null +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/list.md @@ -0,0 +1,174 @@ +--- +name: list +description: List all available design runs with metadata (session, created time, prototype count) +argument-hint: [--session ] +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 ' to create a design run" + fi +else + echo "Total: $found_count design run(s)" + echo "" + echo "💡 USE: /workflow:ui-design:generate --design-id \"\"" + echo " OR: /workflow:ui-design:generate --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 \\' to create a design run' + fi + else + echo \"Total: \$found_count design run(s)\" + echo '' + echo '💡 USE: /workflow:ui-design:generate --design-id \"\"' + echo ' OR: /workflow:ui-design:generate --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 "" + OR: /workflow:ui-design:generate --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 "" + OR: /workflow:ui-design:generate --session "" +``` diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/reference-page-generator.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/reference-page-generator.md new file mode 100644 index 00000000..210bd8b2 --- /dev/null +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/reference-page-generator.md @@ -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 ] [--package-name ] [--output-dir ]" +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 Design run directory path (required) +--package-name Package name for reference (required) +--output-dir 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 --package-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**: +```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**: +```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
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
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**: +```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 | + +--- + diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/style-extract.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/style-extract.md index 17f2764c..f686a3fe 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/ui-design/style-extract.md +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/style-extract.md @@ -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 ] [--session ] [--images ""] [--urls ""] [--prompt ""] [--variants ] [--interactive]" +description: Extract design style from reference images or text prompts using Claude analysis with variant generation or refinement mode +argument-hint: "[--design-id ] [--session ] [--images ""] [--urls ""] [--prompt ""] [--variants ] [--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`. diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/update.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/update.md index 9b4e35a0..e654d98f 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/ui-design/update.md +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/update.md @@ -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] "" **@ 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"] } } } diff --git a/.claude/workflows/workflow-architecture.md b/.claude/workflows/workflow-architecture.md index 14f785d6..4a0949d6 100644 --- a/.claude/workflows/workflow-architecture.md +++ b/.claude/workflows/workflow-architecture.md @@ -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