diff --git a/.claude/skills/command-guide/index/all-commands.json b/.claude/skills/command-guide/index/all-commands.json index 80317501..cc1e4be7 100644 --- a/.claude/skills/command-guide/index/all-commands.json +++ b/.claude/skills/command-guide/index/all-commands.json @@ -409,8 +409,8 @@ { "name": "plan", "command": "/workflow:plan", - "description": "5-phase planning workflow with Gemini analysis and action-planning-agent task generation, outputs IMPL_PLAN.md and task JSONs with optional CLI auto-execution", - "arguments": "[--agent] [--cli-execute] \\\"text description\\\"|file.md", + "description": "5-phase planning workflow with action-planning-agent task generation, outputs IMPL_PLAN.md and task JSONs with optional CLI auto-execution", + "arguments": "[--cli-execute] \\\"text description\\\"|file.md", "category": "workflow", "subcategory": null, "usage_scenario": "planning", @@ -498,7 +498,7 @@ "name": "tdd-plan", "command": "/workflow:tdd-plan", "description": "TDD workflow planning with Red-Green-Refactor task chain generation, test-first development structure, and cycle tracking", - "arguments": "[--agent] \\\"feature description\\\"|file.md", + "arguments": "[--cli-execute] \\\"feature description\\\"|file.md", "category": "workflow", "subcategory": null, "usage_scenario": "planning", @@ -585,8 +585,8 @@ { "name": "task-generate-tdd", "command": "/workflow:tools:task-generate-tdd", - "description": "Generate TDD task chains with Red-Green-Refactor dependencies, test-first structure, and cycle validation", - "arguments": "--session WFS-session-id [--agent]", + "description": "Autonomous TDD task generation using action-planning-agent with Red-Green-Refactor cycles, test-first structure, and cycle validation", + "arguments": "--session WFS-session-id [--cli-execute]", "category": "workflow", "subcategory": "tools", "usage_scenario": "implementation", @@ -640,7 +640,7 @@ { "name": "test-task-generate", "command": "/workflow:tools:test-task-generate", - "description": "Generate test-fix task JSON with iterative test-fix-retest cycle specification using Gemini/Qwen/Codex", + "description": "Autonomous test-fix task generation using action-planning-agent with test-fix-retest cycle specification and discovery phase", "arguments": "[--use-codex] [--cli-execute] --session WFS-test-session-id", "category": "workflow", "subcategory": "tools", @@ -729,7 +729,7 @@ "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 ] [--css \\\"\\\"] [--js \\\"\\\"] [--scss \\\"\\\"] [--html \\\"\\\"] [--style-files \\\"\\\"] [--session ]", + "arguments": "[--source-path ] [--output-path ] [--css \\\"\\\"] [--js \\\"\\\"] [--scss \\\"\\\"] [--html \\\"\\\"] [--style-files \\\"\\\"] [--session ]", "category": "workflow", "subcategory": "ui-design", "usage_scenario": "planning", @@ -740,7 +740,7 @@ "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 \"\"] [--mode ] [--variants ] [--device-type ]", + "arguments": "[--base-path ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--targets \"\"] [--variants ] [--device-type ]", "category": "workflow", "subcategory": "ui-design", "usage_scenario": "general", @@ -751,7 +751,7 @@ "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 \"\"] [--mode ] [--variants ]", + "arguments": "[--base-path ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--variants ]", "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 508e00e7..3c9c523d 100644 --- a/.claude/skills/command-guide/index/by-category.json +++ b/.claude/skills/command-guide/index/by-category.json @@ -297,8 +297,8 @@ { "name": "plan", "command": "/workflow:plan", - "description": "5-phase planning workflow with Gemini analysis and action-planning-agent task generation, outputs IMPL_PLAN.md and task JSONs with optional CLI auto-execution", - "arguments": "[--agent] [--cli-execute] \\\"text description\\\"|file.md", + "description": "5-phase planning workflow with action-planning-agent task generation, outputs IMPL_PLAN.md and task JSONs with optional CLI auto-execution", + "arguments": "[--cli-execute] \\\"text description\\\"|file.md", "category": "workflow", "subcategory": null, "usage_scenario": "planning", @@ -342,7 +342,7 @@ "name": "tdd-plan", "command": "/workflow:tdd-plan", "description": "TDD workflow planning with Red-Green-Refactor task chain generation, test-first development structure, and cycle tracking", - "arguments": "[--agent] \\\"feature description\\\"|file.md", + "arguments": "[--cli-execute] \\\"feature description\\\"|file.md", "category": "workflow", "subcategory": null, "usage_scenario": "planning", @@ -611,8 +611,8 @@ { "name": "task-generate-tdd", "command": "/workflow:tools:task-generate-tdd", - "description": "Generate TDD task chains with Red-Green-Refactor dependencies, test-first structure, and cycle validation", - "arguments": "--session WFS-session-id [--agent]", + "description": "Autonomous TDD task generation using action-planning-agent with Red-Green-Refactor cycles, test-first structure, and cycle validation", + "arguments": "--session WFS-session-id [--cli-execute]", "category": "workflow", "subcategory": "tools", "usage_scenario": "implementation", @@ -666,7 +666,7 @@ { "name": "test-task-generate", "command": "/workflow:tools:test-task-generate", - "description": "Generate test-fix task JSON with iterative test-fix-retest cycle specification using Gemini/Qwen/Codex", + "description": "Autonomous test-fix task generation using action-planning-agent with test-fix-retest cycle specification and discovery phase", "arguments": "[--use-codex] [--cli-execute] --session WFS-test-session-id", "category": "workflow", "subcategory": "tools", @@ -757,7 +757,7 @@ "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 ] [--css \\\"\\\"] [--js \\\"\\\"] [--scss \\\"\\\"] [--html \\\"\\\"] [--style-files \\\"\\\"] [--session ]", + "arguments": "[--source-path ] [--output-path ] [--css \\\"\\\"] [--js \\\"\\\"] [--scss \\\"\\\"] [--html \\\"\\\"] [--style-files \\\"\\\"] [--session ]", "category": "workflow", "subcategory": "ui-design", "usage_scenario": "planning", @@ -768,7 +768,7 @@ "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 \"\"] [--mode ] [--variants ] [--device-type ]", + "arguments": "[--base-path ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--targets \"\"] [--variants ] [--device-type ]", "category": "workflow", "subcategory": "ui-design", "usage_scenario": "general", @@ -779,7 +779,7 @@ "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 \"\"] [--mode ] [--variants ]", + "arguments": "[--base-path ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--variants ]", "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 146653ee..59249f07 100644 --- a/.claude/skills/command-guide/index/by-use-case.json +++ b/.claude/skills/command-guide/index/by-use-case.json @@ -347,7 +347,7 @@ "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 \"\"] [--mode ] [--variants ] [--device-type ]", + "arguments": "[--base-path ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--targets \"\"] [--variants ] [--device-type ]", "category": "workflow", "subcategory": "ui-design", "usage_scenario": "general", @@ -358,7 +358,7 @@ "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 \"\"] [--mode ] [--variants ]", + "arguments": "[--base-path ] [--session ] [--images \"\"] [--urls \"\"] [--prompt \"\"] [--variants ]", "category": "workflow", "subcategory": "ui-design", "usage_scenario": "general", @@ -458,8 +458,8 @@ { "name": "task-generate-tdd", "command": "/workflow:tools:task-generate-tdd", - "description": "Generate TDD task chains with Red-Green-Refactor dependencies, test-first structure, and cycle validation", - "arguments": "--session WFS-session-id [--agent]", + "description": "Autonomous TDD task generation using action-planning-agent with Red-Green-Refactor cycles, test-first structure, and cycle validation", + "arguments": "--session WFS-session-id [--cli-execute]", "category": "workflow", "subcategory": "tools", "usage_scenario": "implementation", @@ -480,7 +480,7 @@ { "name": "test-task-generate", "command": "/workflow:tools:test-task-generate", - "description": "Generate test-fix task JSON with iterative test-fix-retest cycle specification using Gemini/Qwen/Codex", + "description": "Autonomous test-fix task generation using action-planning-agent with test-fix-retest cycle specification and discovery phase", "arguments": "[--use-codex] [--cli-execute] --session WFS-test-session-id", "category": "workflow", "subcategory": "tools", @@ -592,8 +592,8 @@ { "name": "plan", "command": "/workflow:plan", - "description": "5-phase planning workflow with Gemini analysis and action-planning-agent task generation, outputs IMPL_PLAN.md and task JSONs with optional CLI auto-execution", - "arguments": "[--agent] [--cli-execute] \\\"text description\\\"|file.md", + "description": "5-phase planning workflow with action-planning-agent task generation, outputs IMPL_PLAN.md and task JSONs with optional CLI auto-execution", + "arguments": "[--cli-execute] \\\"text description\\\"|file.md", "category": "workflow", "subcategory": null, "usage_scenario": "planning", @@ -604,7 +604,7 @@ "name": "tdd-plan", "command": "/workflow:tdd-plan", "description": "TDD workflow planning with Red-Green-Refactor task chain generation, test-first development structure, and cycle tracking", - "arguments": "[--agent] \\\"feature description\\\"|file.md", + "arguments": "[--cli-execute] \\\"feature description\\\"|file.md", "category": "workflow", "subcategory": null, "usage_scenario": "planning", @@ -615,7 +615,7 @@ "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 ] [--css \\\"\\\"] [--js \\\"\\\"] [--scss \\\"\\\"] [--html \\\"\\\"] [--style-files \\\"\\\"] [--session ]", + "arguments": "[--source-path ] [--output-path ] [--css \\\"\\\"] [--js \\\"\\\"] [--scss \\\"\\\"] [--html \\\"\\\"] [--style-files \\\"\\\"] [--session ]", "category": "workflow", "subcategory": "ui-design", "usage_scenario": "planning", diff --git a/.claude/skills/command-guide/index/essential-commands.json b/.claude/skills/command-guide/index/essential-commands.json index e36b9325..00238d4b 100644 --- a/.claude/skills/command-guide/index/essential-commands.json +++ b/.claude/skills/command-guide/index/essential-commands.json @@ -2,8 +2,8 @@ { "name": "plan", "command": "/workflow:plan", - "description": "5-phase planning workflow with Gemini analysis and action-planning-agent task generation, outputs IMPL_PLAN.md and task JSONs with optional CLI auto-execution", - "arguments": "[--agent] [--cli-execute] \\\"text description\\\"|file.md", + "description": "5-phase planning workflow with action-planning-agent task generation, outputs IMPL_PLAN.md and task JSONs with optional CLI auto-execution", + "arguments": "[--cli-execute] \\\"text description\\\"|file.md", "category": "workflow", "subcategory": null, "usage_scenario": "planning", diff --git a/.claude/skills/command-guide/reference/agents/action-planning-agent.md b/.claude/skills/command-guide/reference/agents/action-planning-agent.md index cb26b061..be7dfe39 100644 --- a/.claude/skills/command-guide/reference/agents/action-planning-agent.md +++ b/.claude/skills/command-guide/reference/agents/action-planning-agent.md @@ -151,9 +151,17 @@ Generate individual `.task/IMPL-*.json` files with: "agent": "@code-developer" }, "context": { - "requirements": ["from analysis_results"], - "focus_paths": ["src/paths"], - "acceptance": ["measurable criteria"], + "requirements": [ + "Implement 3 features: [authentication, authorization, session management]", + "Create 5 files: [auth.service.ts, auth.controller.ts, auth.middleware.ts, auth.types.ts, auth.test.ts]", + "Modify 2 existing functions: [validateUser() in users.service.ts lines 45-60, hashPassword() in utils.ts lines 120-135]" + ], + "focus_paths": ["src/auth", "tests/auth"], + "acceptance": [ + "3 features implemented: verify by npm test -- auth (exit code 0)", + "5 files created: verify by ls src/auth/*.ts | wc -l = 5", + "Test coverage >=80%: verify by npm test -- --coverage | grep auth" + ], "depends_on": ["IMPL-N"], "artifacts": [ { @@ -181,23 +189,50 @@ Generate individual `.task/IMPL-*.json` files with: { "step": 1, "title": "Load and analyze role analyses", - "description": "Load role analyses from artifacts and extract requirements", - "modification_points": ["Load role analyses", "Extract requirements and design patterns"], - "logic_flow": ["Read role analyses from artifacts", "Parse architecture decisions", "Extract implementation requirements"], + "description": "Load 3 role analysis files and extract quantified requirements", + "modification_points": [ + "Load 3 role analysis files: [system-architect/analysis.md, product-manager/analysis.md, ui-designer/analysis.md]", + "Extract 15 requirements from role analyses", + "Parse 8 architecture decisions from system-architect analysis" + ], + "logic_flow": [ + "Read 3 role analyses from artifacts inventory", + "Parse architecture decisions (8 total)", + "Extract implementation requirements (15 total)", + "Build consolidated requirements list" + ], "depends_on": [], "output": "synthesis_requirements" }, { "step": 2, "title": "Implement following specification", - "description": "Implement task requirements following consolidated role analyses", - "modification_points": ["Apply requirements from [synthesis_requirements]", "Modify target files", "Integrate with existing code"], - "logic_flow": ["Apply changes based on [synthesis_requirements]", "Implement core logic", "Validate against acceptance criteria"], + "description": "Implement 3 features across 5 files following consolidated role analyses", + "modification_points": [ + "Create 5 new files in src/auth/: [auth.service.ts (180 lines), auth.controller.ts (120 lines), auth.middleware.ts (60 lines), auth.types.ts (40 lines), auth.test.ts (200 lines)]", + "Modify 2 functions: [validateUser() in users.service.ts lines 45-60, hashPassword() in utils.ts lines 120-135]", + "Implement 3 core features: [JWT authentication, role-based authorization, session management]" + ], + "logic_flow": [ + "Apply 15 requirements from [synthesis_requirements]", + "Implement 3 features across 5 new files (600 total lines)", + "Modify 2 existing functions (30 lines total)", + "Write 25 test cases covering all features", + "Validate against 3 acceptance criteria" + ], "depends_on": [1], "output": "implementation" } ], - "target_files": ["file:function:lines", "path/to/NewFile.ts"] + "target_files": [ + "src/auth/auth.service.ts", + "src/auth/auth.controller.ts", + "src/auth/auth.middleware.ts", + "src/auth/auth.types.ts", + "tests/auth/auth.test.ts", + "src/users/users.service.ts:validateUser:45-60", + "src/utils/utils.ts:hashPassword:120-135" + ] } } ``` @@ -285,6 +320,35 @@ Use `analysis_results.complexity` or task count to determine structure: - **Re-scope required**: Maximum 10 tasks hard limit - If analysis_results contains >10 tasks, consolidate or request re-scoping +## Quantification Requirements (MANDATORY) + +**Purpose**: Eliminate ambiguity by enforcing explicit counts and enumerations in all task specifications. + +**Core Rules**: +1. **Extract Counts from Analysis**: Search for HOW MANY items and list them explicitly +2. **Enforce Explicit Lists**: Every deliverable uses format `{count} {type}: [{explicit_list}]` +3. **Make Acceptance Measurable**: Include verification commands (e.g., `ls ... | wc -l = N`) +4. **Quantify Modification Points**: Specify exact targets (files, functions with line numbers) +5. **Avoid Vague Language**: Replace "complete", "comprehensive", "reorganize" with quantified statements + +**Standard Formats**: +- **Requirements**: `"Implement N items: [item1, item2, ...]"` or `"Modify N files: [file1:func:lines, ...]"` +- **Acceptance**: `"N items exist: verify by [command]"` or `"Coverage >= X%: verify by [test command]"` +- **Modification Points**: `"Create N files: [list]"` or `"Modify N functions: [func() in file lines X-Y]"` + +**Validation Checklist** (Apply to every generated task JSON): +- [ ] Every requirement contains explicit count or enumerated list +- [ ] Every acceptance criterion is measurable with verification command +- [ ] Every modification_point specifies exact targets (files/functions/lines) +- [ ] No vague language ("complete", "comprehensive", "reorganize" without counts) +- [ ] Each implementation step has its own acceptance criteria + +**Examples**: +- โœ… GOOD: `"Implement 5 commands: [cmd1, cmd2, cmd3, cmd4, cmd5]"` +- โŒ BAD: `"Implement new commands"` +- โœ… GOOD: `"5 files created: verify by ls .claude/commands/*.md | wc -l = 5"` +- โŒ BAD: `"All commands implemented successfully"` + ## Quality Standards **Planning Principles:** @@ -305,6 +369,7 @@ Use `analysis_results.complexity` or task count to determine structure: ## Key Reminders **ALWAYS:** +- **Apply Quantification Requirements**: All requirements, acceptance criteria, and modification points MUST include explicit counts and enumerations - **Use provided context package**: Extract all information from structured context - **Respect memory-first rule**: Use provided content (already loaded from memory/file) - **Follow 5-field schema**: All task JSONs must have id, title, status, meta, context, flow_control @@ -313,6 +378,7 @@ Use `analysis_results.complexity` or task count to determine structure: - **Validate task count**: Maximum 10 tasks hard limit, request re-scope if exceeded - **Use session paths**: Construct all paths using provided session_id - **Link documents properly**: Use correct linking format (๐Ÿ“‹ for JSON, โœ… for summaries) +- **Run validation checklist**: Verify all quantification requirements before finalizing task JSONs **NEVER:** - Load files directly (use provided context package instead) 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 4bc8c988..faf6fce0 100644 --- a/.claude/skills/command-guide/reference/agents/ui-design-agent.md +++ b/.claude/skills/command-guide/reference/agents/ui-design-agent.md @@ -16,89 +16,131 @@ description: | color: orange --- -You are a specialized **UI Design Agent** that executes design generation tasks autonomously. You are invoked by orchestrator commands (e.g., `consolidate.md`, `generate.md`) to produce production-ready design systems and prototypes. +You are a specialized **UI Design Agent** that executes design generation tasks autonomously to produce production-ready design systems and prototypes. -## Core Capabilities +## Task Patterns -### 1. Design Token Synthesis +You execute 6 distinct task types organized into 3 patterns. Each task includes `[TASK_TYPE_IDENTIFIER]` in its prompt. -**Invoked by**: `consolidate.md` -**Input**: Style variants with proposed_tokens from extraction phase -**Task**: Generate production-ready design token systems +### Pattern 1: Option Generation -**Deliverables**: -- `design-tokens.json`: W3C-compliant token definitions using OKLCH colors -- `style-guide.md`: Comprehensive design system documentation -- `layout-strategies.json`: MCP-researched layout variant definitions -- `tokens.css`: CSS custom properties with Google Fonts imports +**Purpose**: Generate multiple design/layout options for user selection (exploration phase) -### 2. Layout Strategy Generation +**Task Types**: +- `[DESIGN_DIRECTION_GENERATION_TASK]` - Generate design direction options +- `[LAYOUT_CONCEPT_GENERATION_TASK]` - Generate layout concept options -**Invoked by**: `consolidate.md` Phase 2.5 -**Input**: Project context from role analysis documents -**Task**: Research and generate adaptive layout strategies via Exa MCP (2024-2025 trends) +**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 -**Output**: layout-strategies.json with strategy definitions and rationale +**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 -### 3. UI Prototype Generation +**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 -**Invoked by**: `generate.md` Phase 2a -**Input**: Design tokens, layout strategies, target specifications -**Task**: Generate style-agnostic HTML/CSS templates +**Key Principles**: +- โœ… Creative exploration with high autonomy +- โœ… Generate diverse, contrasting options +- โœ… Include visual/structural previews for user understanding +- โŒ NO user interaction during generation + +### 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 + +**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 + +**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 + +**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) + +**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 + +**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 + +### 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 **Process**: -- Research implementation patterns via Exa MCP (components, responsive design, accessibility, HTML semantics, CSS architecture) -- Extract exact token variable names from design-tokens.json -- Generate semantic HTML5 structure with ARIA attributes -- Create structural CSS using 100% CSS custom properties -- Implement mobile-first responsive design +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) -**Deliverables**: -- `{target}-layout-{id}.html`: Style-agnostic HTML structure -- `{target}-layout-{id}.css`: Token-driven structural CSS +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 -**โš ๏ธ CRITICAL: CSS Placeholder Links** +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) + - Device-optimized for template.device_type -When generating HTML templates, you MUST include these EXACT placeholder links in the `` section: +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` -```html - - -``` - -**Placeholder Rules**: -1. Use EXACTLY `{{STRUCTURAL_CSS}}` and `{{TOKEN_CSS}}` with double curly braces -2. Place in `` AFTER `` tags, BEFORE `` closing tag -3. DO NOT substitute with actual paths - the instantiation script handles this -4. DO NOT add any other CSS `` tags -5. These enable runtime style switching for all variants - -**Example HTML Template Structure**: -```html - - - - - - {target} - Layout {id} - - - - - - - -``` - -**Quality Gates**: ๐ŸŽฏ ADAPTIVE (multi-device), ๐Ÿ”„ STYLE-SWITCHABLE (runtime theme switching), ๐Ÿ—๏ธ SEMANTIC (HTML5), โ™ฟ ACCESSIBLE (WCAG AA), ๐Ÿ“ฑ MOBILE-FIRST, ๐ŸŽจ TOKEN-DRIVEN (zero hardcoded values) - -### 4. Consistency Validation - -**Invoked by**: `generate.md` Phase 3.5 -**Input**: Multiple target prototypes for same style/layout combination -**Task**: Validate cross-target design consistency - -**Deliverables**: Consistency reports, token usage verification, accessibility compliance checks, layout strategy adherence validation +**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 ## Design Standards @@ -276,135 +318,84 @@ h1, h2, h3, h4, h5, h6 { ## Agent Operation -### Execution Process +### Execution Flow -When invoked by orchestrator command (e.g., `[DESIGN_TOKEN_GENERATION_TASK]`): +All tasks follow this standard flow with pattern-specific variations: ``` -STEP 1: Parse Task Identifier -โ†’ Identify task type from [TASK_TYPE_IDENTIFIER] -โ†’ Load task-specific execution template -โ†’ Validate required parameters present +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 Input Context -โ†’ Read variant data from orchestrator prompt -โ†’ Parse proposed_tokens, design_space_analysis -โ†’ Extract MCP research keywords if provided -โ†’ Verify BASE_PATH and output directory structure +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 MCP Research (if applicable) -FOR each variant: - โ†’ Build variant-specific queries - โ†’ Execute mcp__exa__web_search_exa() calls - โ†’ Accumulate research results in memory - โ†’ (DO NOT write research results to files) +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 -STEP 4: Generate Content -FOR each variant: - โ†’ Refine tokens using proposed_tokens + MCP research - โ†’ Generate design-tokens.json content - โ†’ Generate style-guide.md content - โ†’ Keep content in memory (DO NOT accumulate in text) +โ†’ 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 -STEP 5: WRITE FILES (CRITICAL) -FOR each variant: - โ†’ EXECUTE: Write("{path}/design-tokens.json", tokens_json) - โ†’ VERIFY: File exists and size > 1KB - โ†’ EXECUTE: Write("{path}/style-guide.md", guide_content) - โ†’ VERIFY: File exists and size > 1KB - โ†’ Report completion for this variant - โ†’ (DO NOT wait to write all variants at once) +โ†’ 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 -STEP 6: Final Verification -โ†’ Verify all {variants_count} ร— 2 files written -โ†’ Report total files written with sizes +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 +โ†’ 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 ``` -**Key Execution Principle**: **WRITE FILES IMMEDIATELY** after generating content for each variant. DO NOT accumulate all content and try to output at the end. +**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 -### Invocation Model +### Core Execution Principles -You are invoked by orchestrator commands to execute specific generation tasks: - -**Token Generation** (by `consolidate.md`): -- Synthesize design tokens from style variants -- Generate layout strategies based on MCP research -- Produce design-tokens.json, style-guide.md, layout-strategies.json - -**Prototype Generation** (by `generate.md`): -- Generate style-agnostic HTML/CSS templates -- Create token-driven prototypes using template instantiation -- Produce responsive, accessible HTML/CSS files - -**Consistency Validation** (by `generate.md` Phase 3.5): -- Validate cross-target design consistency -- Generate consistency reports for multi-page workflows - -### Execution Principles - -**Autonomous Operation**: -- Receive all parameters from orchestrator command -- Execute task without user interaction +**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 invocation processes EXACTLY ONE target (page or component) -- Do NOT combine multiple targets into a single template -- Even if targets will coexist in final application, generate them independently -- **Example Scenario**: - - Task: Generate template for "login" (workflow has: ["login", "sidebar"]) - - โŒ WRONG: Generate login page WITH sidebar included - - โœ… CORRECT: Generate login page WITHOUT sidebar (sidebar is separate target) -- **Verification Before Output**: - - Confirm template includes ONLY the specified target - - Check no cross-contamination from other targets in workflow - - Each target must be standalone and reusable +- 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 +- 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 -**Research-Informed**: -- Use MCP tools for trend research and pattern discovery -- Integrate modern best practices into generation decisions -- Cache research results for session reuse - -**Complete Outputs**: -- Generate all required files and documentation -- Include metadata and implementation notes -- Validate file format and completeness - -### Performance Optimization - -**Two-Layer Generation Architecture**: -- **Layer 1 (Your Responsibility)**: Generate style-agnostic layout templates (creative work) - - HTML structure with semantic markup - - Structural CSS with CSS custom property references - - One template per layout variant per target -- **Layer 2 (Orchestrator Responsibility)**: Instantiate style-specific prototypes - - Token conversion (JSON โ†’ CSS) - - Template instantiation (Lร—T templates โ†’ Sร—Lร—T prototypes) - - Performance: Sร— faster than generating all combinations individually - -**Your Focus**: Generate high-quality, reusable templates. Orchestrator handles file operations and instantiation. - -### Scope & Boundaries - -**Your Responsibilities**: -- Execute assigned generation task completely -- Apply all quality standards automatically -- Research when parameters require trend-informed decisions -- Validate outputs against quality gates -- Generate complete documentation - -**NOT Your Responsibilities**: -- User interaction or confirmation -- Workflow orchestration or sequencing -- Parameter collection or validation -- Strategic design decisions (provided by brainstorming phase) -- Task scheduling or dependency management +**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 ## Technical Integration @@ -457,10 +448,10 @@ layout_results = mcp__exa__web_search_exa( - **Edit**: Update token definitions, refine layout strategies when files already exist **Path Handling**: -- Orchestrator provides complete absolute paths in prompts -- Agent uses provided paths exactly as given without modification -- If path contains variables (e.g., `{base_path}`), they will be pre-resolved by orchestrator -- Agent verifies directory structure exists before writing +- 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)` **File Write Verification**: @@ -543,46 +534,50 @@ layout_results = mcp__exa__web_search_exa( ### ALWAYS: -**File Writing**: -- โœ… Use Write() tool for EVERY output file - this is your PRIMARY responsibility -- โœ… Write files IMMEDIATELY after generating content for each variant/target -- โœ… Verify each Write() operation succeeds before proceeding to next file -- โœ… Use EXACT paths provided by orchestrator without modification -- โœ… Report completion with file paths and sizes after each write +**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 -**Task Execution**: -- โœ… Parse task identifier ([DESIGN_TOKEN_GENERATION_TASK], etc.) first -- โœ… Execute MCP research when design_space_analysis is provided -- โœ… Follow the 6-step execution process sequentially -- โœ… Maintain variant independence - research and write separately for each -- โœ… Validate outputs against quality gates (WCAG AA, token completeness, OKLCH format) +**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 -**Quality Standards**: -- โœ… Apply all design standards automatically (WCAG AA, OKLCH, semantic naming) -- โœ… Include Google Fonts imports in CSS with fallback stacks -- โœ… Generate complete token coverage (colors, typography, spacing, radius, shadows, breakpoints) +**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 +- โœ… Implement semantic HTML5 with ARIA attributes (Pattern 2 & 3) +- โœ… Execute MCP research for modern patterns (Pattern 1 & 2 when applicable) + +**Target Independence**: +- โœ… Process EXACTLY ONE target per task +- โœ… Keep targets standalone and reusable +- โœ… Verify no cross-contamination between targets ### NEVER: **File Writing**: -- โŒ Return file contents as text with labeled sections (e.g., "## File 1: design-tokens.json\n{content}") -- โŒ Accumulate all variant content and try to output at once -- โŒ Skip Write() operations and expect orchestrator to write files +- โŒ 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 variant before completing current variant's file writes +- โŒ Continue to next item before completing current item's writes **Task Execution**: -- โŒ Mix multiple targets into a single template (respect target independence) -- โŒ Skip MCP research when design_space_analysis is provided -- โŒ Generate variant N+1 before variant N's files are written -- โŒ Return research results as files (keep in memory for token refinement) -- โŒ Assume default values without checking orchestrator prompt +- โŒ 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) **Quality Violations**: -- โŒ Use hardcoded colors/fonts/spacing instead of tokens -- โŒ Generate tokens without OKLCH format for colors -- โŒ Skip WCAG AA contrast validation -- โŒ Omit Google Fonts imports or fallback stacks -- โŒ Create incomplete token categories +- โŒ 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) diff --git a/.claude/skills/command-guide/reference/commands/workflow/plan.md b/.claude/skills/command-guide/reference/commands/workflow/plan.md index c27b3039..bf47127d 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/plan.md +++ b/.claude/skills/command-guide/reference/commands/workflow/plan.md @@ -1,7 +1,7 @@ --- name: plan -description: 5-phase planning workflow with Gemini analysis and action-planning-agent task generation, outputs IMPL_PLAN.md and task JSONs with optional CLI auto-execution -argument-hint: "[--agent] [--cli-execute] \"text description\"|file.md" +description: 5-phase planning workflow with action-planning-agent task generation, outputs IMPL_PLAN.md and task JSONs with optional CLI auto-execution +argument-hint: "[--cli-execute] \"text description\"|file.md" allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*) --- @@ -20,7 +20,7 @@ This workflow runs **fully autonomously** once triggered. Phase 3 (conflict reso 2. **Phase 1 executes** โ†’ Session discovery โ†’ Auto-continues 3. **Phase 2 executes** โ†’ Context gathering โ†’ Auto-continues 4. **Phase 3 executes** (optional, if conflict_risk โ‰ฅ medium) โ†’ Conflict resolution โ†’ Auto-continues -5. **Phase 4 executes** (task-generate-agent if --agent) โ†’ Task generation โ†’ Reports final summary +5. **Phase 4 executes** โ†’ Task generation (task-generate-agent) โ†’ Reports final summary **Auto-Continue Mechanism**: - TodoList tracks current phase status @@ -28,11 +28,6 @@ This workflow runs **fully autonomously** once triggered. Phase 3 (conflict reso - All phases run autonomously without user interaction (clarification handled in brainstorm phase) - Progress updates shown at each phase for visibility -**Execution Modes**: -- **Manual Mode** (default): Use `/workflow:tools:task-generate` -- **Agent Mode** (`--agent`): Use `/workflow:tools:task-generate-agent` -- **CLI Execute Mode** (`--cli-execute`): Generate tasks with Codex execution commands - ## Core Rules 1. **Start Immediately**: First action is TodoWrite initialization, second action is Phase 1 command execution @@ -159,24 +154,18 @@ CONTEXT: Existing user database schema, REST API endpoints - Task generation translates high-level role analyses into concrete, actionable work items - **Intent priority**: Current user prompt > role analysis.md files > guidance-specification.md -**Command Selection**: -- Manual: `SlashCommand(command="/workflow:tools:task-generate --session [sessionId]")` -- Agent: `SlashCommand(command="/workflow:tools:task-generate-agent --session [sessionId]")` -- CLI Execute: Add `--cli-execute` flag to either command - -**Flag Combination**: -- `--cli-execute` alone: Manual task generation with CLI execution -- `--agent --cli-execute`: Agent task generation with CLI execution - -**Command Examples**: +**Command**: ```bash -# Manual with CLI execution -/workflow:tools:task-generate --session WFS-auth --cli-execute +# Default (agent mode) +SlashCommand(command="/workflow:tools:task-generate-agent --session [sessionId]") -# Agent with CLI execution -/workflow:tools:task-generate-agent --session WFS-auth --cli-execute +# With CLI execution +SlashCommand(command="/workflow:tools:task-generate-agent --session [sessionId] --cli-execute") ``` +**Flag**: +- `--cli-execute`: Generate tasks with Codex execution commands + **Input**: `sessionId` from Phase 1 **Validation**: @@ -296,7 +285,7 @@ Phase 3: conflict-resolution [AUTO-TRIGGERED if conflict_risk โ‰ฅ medium] โ†“ Output: Modified brainstorm artifacts (NO report file) โ†“ Skip if conflict_risk is none/low โ†’ proceed directly to Phase 4 โ†“ -Phase 4: task-generate[--agent] --session sessionId +Phase 4: task-generate-agent --session sessionId [--cli-execute] โ†“ Input: sessionId + resolved brainstorm artifacts + session memory โ†“ Output: IMPL_PLAN.md, task JSONs, TODO_LIST.md โ†“ @@ -333,9 +322,8 @@ Return summary to user - **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 - **If conflict_risk is none/low**: Skip Phase 3, proceed directly to Phase 4 -- **Build Phase 4 command** based on flags: - - Base command: `/workflow:tools:task-generate` (or `-agent` if `--agent` flag) - - Add `--session [sessionId]` +- **Build Phase 4 command**: + - Base command: `/workflow:tools:task-generate-agent --session [sessionId]` - Add `--cli-execute` if flag present - Pass session ID to Phase 4 command - Verify all Phase 4 outputs @@ -380,8 +368,7 @@ CONSTRAINTS: [Limitations or boundaries] - `/workflow:tools:context-gather` - Phase 2: Gather project context and analyze codebase - `/workflow:tools:conflict-resolution` - Phase 3: Detect and resolve conflicts (auto-triggered if conflict_risk โ‰ฅ medium) - `/compact` - Phase 3: Memory optimization (if context approaching limits) -- `/workflow:tools:task-generate` - Phase 4: Generate task JSON files with manual approach -- `/workflow:tools:task-generate-agent` - Phase 4: Generate task JSON files with agent-driven approach (when `--agent` flag used) +- `/workflow:tools:task-generate-agent` - Phase 4: Generate task JSON files with agent-driven approach **Follow-up Commands**: - `/workflow:action-plan-verify` - Recommended: Verify plan quality and catch issues before execution 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 8c1c361a..efdeb912 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/tdd-plan.md +++ b/.claude/skills/command-guide/reference/commands/workflow/tdd-plan.md @@ -1,7 +1,7 @@ --- name: tdd-plan description: TDD workflow planning with Red-Green-Refactor task chain generation, test-first development structure, and cycle tracking -argument-hint: "[--agent] \"feature description\"|file.md" +argument-hint: "[--cli-execute] \"feature description\"|file.md" allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*) --- @@ -12,8 +12,8 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*) **This command is a pure orchestrator**: Execute 5 slash commands in sequence, parse outputs, pass context, and ensure complete TDD workflow creation. **Execution Modes**: -- **Manual Mode** (default): Use `/workflow:tools:task-generate-tdd` -- **Agent Mode** (`--agent`): Use `/workflow:tools:task-generate-tdd --agent` +- **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) ## Core Rules @@ -129,8 +129,8 @@ TEST_FOCUS: [Test scenarios] ### Phase 5: TDD Task Generation **Command**: -- Manual: `/workflow:tools:task-generate-tdd --session [sessionId]` -- Agent: `/workflow:tools:task-generate-tdd --session [sessionId] --agent` +- Agent Mode (default): `/workflow:tools:task-generate-tdd --session [sessionId]` +- CLI Mode (`--cli-execute`): `/workflow:tools:task-generate-tdd --session [sessionId] --cli-execute` **Parse**: Extract feature count, task count (not chain count - tasks now contain internal TDD cycles) @@ -373,8 +373,8 @@ Supports action-planning-agent for more autonomous TDD planning with: - `/workflow:tools:test-context-gather` - Phase 3: Analyze existing test patterns and coverage - `/workflow:tools:conflict-resolution` - Phase 4: Detect and resolve conflicts (auto-triggered if conflict_risk โ‰ฅ medium) - `/compact` - Phase 4: Memory optimization (if context approaching limits) -- `/workflow:tools:task-generate-tdd` - Phase 5: Generate TDD task chains with Red-Green-Refactor cycles -- `/workflow:tools:task-generate-tdd --agent` - Phase 5: Generate TDD tasks with agent-driven approach (when `--agent` flag used) +- `/workflow:tools:task-generate-tdd` - Phase 5: Generate TDD tasks with agent-driven approach (default, autonomous) +- `/workflow:tools:task-generate-tdd --cli-execute` - Phase 5: Generate TDD tasks with CLI tools (Gemini/Qwen, when `--cli-execute` flag used) **Follow-up Commands**: - `/workflow:action-plan-verify` - Recommended: Verify TDD plan quality and structure before execution 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 29dc1ba8..9b32b151 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 @@ -473,9 +473,9 @@ WFS-test-[session]/ - `/workflow:tools:test-context-gather` - Phase 2 (Session Mode): Gather source session context - `/workflow:tools:context-gather` - Phase 2 (Prompt Mode): Analyze codebase directly - `/workflow:tools:test-concept-enhanced` - Phase 3: Generate test requirements using Gemini -- `/workflow:tools:test-task-generate` - Phase 4: Generate test task JSONs with fix cycle specification -- `/workflow:tools:test-task-generate --use-codex` - Phase 4: With automated Codex fixes (when `--use-codex` flag used) -- `/workflow:tools:test-task-generate --cli-execute` - Phase 4: With CLI execution mode (when `--cli-execute` flag used) +- `/workflow:tools:test-task-generate` - Phase 4: Generate test task JSONs using action-planning-agent (autonomous, default) +- `/workflow:tools:test-task-generate --use-codex` - Phase 4: With automated Codex fixes for IMPL-002 (when `--use-codex` flag used) +- `/workflow:tools:test-task-generate --cli-execute` - Phase 4: With CLI execution mode for IMPL-001 test generation (when `--cli-execute` flag used) **Follow-up Commands**: - `/workflow:status` - Review generated test tasks 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 2acb0d38..a24e0221 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/test-gen.md +++ b/.claude/skills/command-guide/reference/commands/workflow/test-gen.md @@ -337,9 +337,9 @@ See `/workflow:tools:test-task-generate` for complete JSON schemas. - `/workflow:session:start` - Phase 1: Create independent test workflow session - `/workflow:tools:test-context-gather` - Phase 2: Analyze test coverage and gather source session context - `/workflow:tools:test-concept-enhanced` - Phase 3: Generate test requirements and strategy using Gemini -- `/workflow:tools:test-task-generate` - Phase 4: Generate test generation and execution task JSONs -- `/workflow:tools:test-task-generate --use-codex` - Phase 4: With automated Codex fixes (when `--use-codex` flag used) -- `/workflow:tools:test-task-generate --cli-execute` - Phase 4: With CLI execution mode (when `--cli-execute` flag used) +- `/workflow:tools:test-task-generate` - Phase 4: Generate test task JSONs using action-planning-agent (autonomous, default) +- `/workflow:tools:test-task-generate --use-codex` - Phase 4: With automated Codex fixes for IMPL-002 (when `--use-codex` flag used) +- `/workflow:tools:test-task-generate --cli-execute` - Phase 4: With CLI execution mode for IMPL-001 test generation (when `--cli-execute` flag used) **Follow-up Commands**: - `/workflow:status` - Review generated test tasks diff --git a/.claude/skills/command-guide/reference/commands/workflow/tools/conflict-resolution.md b/.claude/skills/command-guide/reference/commands/workflow/tools/conflict-resolution.md index 9c65bbe2..2c8b9fe6 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/tools/conflict-resolution.md +++ b/.claude/skills/command-guide/reference/commands/workflow/tools/conflict-resolution.md @@ -24,6 +24,7 @@ Analyzes conflicts between implementation plans and existing codebase, generatin | **Generate Strategies** | Provide 2-4 resolution options per conflict | | **CLI Analysis** | Use Gemini/Qwen (Claude fallback) | | **User Decision** | Present options, never auto-apply | +| **Direct Text Output** | Output questions via text directly, NEVER use bash echo/printf | | **Single Output** | `CONFLICT_RESOLUTION.md` with findings | ## Conflict Categories @@ -462,10 +463,3 @@ If Edit tool fails mid-application: โœ“ Error handling robust (validate/retry/degrade) ``` -## Related Commands -| Command | Relationship | -|---------|--------------| -| `/workflow:tools:context-gather` | Generates input conflict_detection data | -| `/workflow:plan` | Auto-triggers this when risk โ‰ฅ medium | -| `/workflow:tools:task-generate` | Uses resolved conflicts from updated brainstorm files | -| `/workflow:brainstorm:artifacts` | Generates guidance-specification.md (modified by this command) | diff --git a/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate-agent.md b/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate-agent.md index e1b60d91..c90bd32f 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate-agent.md +++ b/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate-agent.md @@ -163,155 +163,50 @@ If conflict_risk was medium/high, modifications have been applied to: ## Phase 2: Document Generation Task -### Task Decomposition Standards -**Core Principle**: Task Merging Over Decomposition -- **Merge Rule**: Execute together when possible -- **Decompose Only When**: - - Excessive workload (>2500 lines or >6 files) - - Different tech stacks or domains - - Sequential dependency blocking - - Parallel execution needed +**Agent Configuration Reference**: All task generation rules, quantification requirements, quality standards, and execution details are defined in action-planning-agent. -**Task Limits**: -- **Maximum 10 tasks** (hard limit) -- **Function-based**: Complete units (logic + UI + tests + config) -- **Hierarchy**: Flat (โ‰ค5) | Two-level (6-10) | Re-scope (>10) +Refer to: @.claude/agents/action-planning-agent.md for: +- Task Decomposition Standards +- Quantification Requirements (MANDATORY) +- 5-Field Task JSON Schema +- IMPL_PLAN.md Structure +- TODO_LIST.md Format +- Execution Flow & Quality Validation -### Required Outputs +### Required Outputs Summary #### 1. Task JSON Files (.task/IMPL-*.json) -**Location**: .workflow/{session-id}/.task/ -**Template**: Read from the template path provided above - -**Task JSON Template Loading**: -\`\`\` -Read({template_path}) -\`\`\` - -**Important**: -- Read the template from the path provided in context -- Use the template structure exactly as written -- Replace placeholder variables ({synthesis_spec_path}, {role_analysis_path}, etc.) with actual session-specific paths -- Include MCP tool integration in pre_analysis steps -- Map artifacts based on task domain (UI โ†’ ui-designer, Backend โ†’ system-architect) +- **Location**: `.workflow/{session-id}/.task/` +- **Template**: Read from `{template_path}` (pre-selected by command based on `--cli-execute` flag) +- **Schema**: 5-field structure (id, title, status, meta, context, flow_control) with artifacts integration +- **Details**: See action-planning-agent.md ยง Task JSON Generation #### 2. IMPL_PLAN.md -**Location**: .workflow/{session-id}/IMPL_PLAN.md - -**IMPL_PLAN Template**: -\`\`\` -$(cat ~/.claude/workflows/cli-templates/prompts/workflow/impl-plan-template.txt) -\`\`\` - -**Important**: -- Use the template above for IMPL_PLAN.md generation -- Replace all {placeholder} variables with actual session-specific values -- Populate CCW Workflow Context based on actual phase progression -- Extract content from role analyses and context-package.json -- List all detected brainstorming artifacts with correct paths (role analyses, guidance-specification.md) -- Include conflict resolution status if CONFLICT_RESOLUTION.md exists +- **Location**: `.workflow/{session-id}/IMPL_PLAN.md` +- **Template**: `~/.claude/workflows/cli-templates/prompts/workflow/impl-plan-template.txt` +- **Details**: See action-planning-agent.md ยง Implementation Plan Creation #### 3. TODO_LIST.md -**Location**: .workflow/{session-id}/TODO_LIST.md -**Structure**: -\`\`\`markdown -# Tasks: {Session Topic} +- **Location**: `.workflow/{session-id}/TODO_LIST.md` +- **Format**: Hierarchical task list with status indicators (โ–ธ, [ ], [x]) and JSON links +- **Details**: See action-planning-agent.md ยง TODO List Generation -## Task Progress -โ–ธ **IMPL-001**: [Main Task Group] โ†’ [๐Ÿ“‹](./.task/IMPL-001.json) - - [ ] **IMPL-001.1**: [Subtask] โ†’ [๐Ÿ“‹](./.task/IMPL-001.1.json) - - [ ] **IMPL-001.2**: [Subtask] โ†’ [๐Ÿ“‹](./.task/IMPL-001.2.json) +### Agent Execution Summary -- [ ] **IMPL-002**: [Simple Task] โ†’ [๐Ÿ“‹](./.task/IMPL-002.json) +**Key Steps** (Detailed instructions in action-planning-agent.md): +1. Load task JSON template from provided path +2. Extract and decompose tasks with quantification +3. Generate task JSON files enforcing quantification requirements +4. Create IMPL_PLAN.md using template +5. Generate TODO_LIST.md matching task JSONs +6. Update session state -## Status Legend -- \`โ–ธ\` = Container task (has subtasks) -- \`- [ ]\` = Pending leaf task -- \`- [x]\` = Completed leaf task -\`\`\` - -### Execution Instructions for Agent - -**Agent Task**: Generate task JSON files, IMPL_PLAN.md, and TODO_LIST.md based on analysis results - -**Note**: The correct task JSON template path has been pre-selected by the command based on the `--cli-execute` flag and is provided in the context as `{template_path}`. - -**Step 1: Load Task JSON Template** -- Read template from the provided path: `Read({template_path})` -- This template is already the correct one based on execution mode - -**Step 2: Extract and Decompose Tasks** -- Parse role analysis.md files for requirements, design specs, and task recommendations -- Review synthesis enhancements and clarifications in role analyses -- Apply conflict resolution strategies (if CONFLICT_RESOLUTION.md exists) -- Apply task merging rules (merge when possible, decompose only when necessary) -- Map artifacts to tasks based on domain (UI โ†’ ui-designer, Backend โ†’ system-architect, Data โ†’ data-architect) -- Ensure task count โ‰ค10 - -**Step 3: Generate Task JSON Files** -- Use the template structure from Step 1 -- Create .task/IMPL-*.json files with proper structure -- Replace all {placeholder} variables with actual session paths -- Embed artifacts array with brainstorming outputs -- Include MCP tool integration in pre_analysis steps - -**Step 4: Create IMPL_PLAN.md** -- Use IMPL_PLAN template -- Populate all sections with session-specific content -- List artifacts with priorities and usage guidelines -- Document execution strategy and dependencies - -**Step 5: Generate TODO_LIST.md** -- Create task progress checklist matching generated JSONs -- Use proper status indicators (โ–ธ, [ ], [x]) -- Link to task JSON files - -**Step 6: Update Session State** -- Update workflow-session.json with task count and artifact inventory -- Mark session ready for execution - -### MCP Enhancement Examples - -**Code Index Usage**: -\`\`\`javascript -// Discover authentication-related files -bash(find . -name "*auth*" -type f) - -// Search for OAuth patterns -bash(rg "oauth|jwt|authentication" -g "*.{ts,js}") - -// Get file summary for key components -bash(rg "^(class|function|export|interface)" src/auth/index.ts) -\`\`\` - -**Exa Research Usage**: -\`\`\`javascript -// Get best practices for task implementation -mcp__exa__get_code_context_exa( - query="TypeScript OAuth2 implementation patterns", - tokensNum="dynamic" -) - -// Research specific API usage -mcp__exa__get_code_context_exa( - query="Express.js JWT middleware examples", - tokensNum=5000 -) -\`\`\` - -### Quality Validation - -Before completion, verify: -- [ ] All task JSON files created in .task/ directory -- [ ] Each task JSON has 5 required fields -- [ ] Artifact references correctly mapped -- [ ] Flow control includes artifact loading steps -- [ ] MCP tool integration added where appropriate -- [ ] IMPL_PLAN.md follows required structure -- [ ] TODO_LIST.md matches task JSONs -- [ ] Dependency graph is acyclic -- [ ] Task count within limits (โ‰ค10) -- [ ] Session state updated +**Quality Gates** (Full checklist in action-planning-agent.md): +- โœ“ Quantification requirements enforced (explicit counts, measurable acceptance, exact targets) +- โœ“ Task count โ‰ค10 (hard limit) +- โœ“ Artifact references mapped correctly +- โœ“ MCP tool integration added +- โœ“ Documents follow template structure ## Output diff --git a/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate-tdd.md b/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate-tdd.md index 7a237a17..7cebed30 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate-tdd.md +++ b/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate-tdd.md @@ -1,14 +1,28 @@ --- name: task-generate-tdd -description: Generate TDD task chains with Red-Green-Refactor dependencies, test-first structure, and cycle validation -argument-hint: "--session WFS-session-id [--agent]" -allowed-tools: Read(*), Write(*), Bash(gemini:*), TodoWrite(*) +description: Autonomous TDD task generation using action-planning-agent with Red-Green-Refactor cycles, test-first structure, and cycle validation +argument-hint: "--session WFS-session-id [--cli-execute]" +examples: + - /workflow:tools:task-generate-tdd --session WFS-auth + - /workflow:tools:task-generate-tdd --session WFS-auth --cli-execute --- -# TDD Task Generation Command +# Autonomous TDD Task Generation Command ## Overview -Generate TDD-specific tasks from analysis results with complete Red-Green-Refactor cycles contained within each task. +Autonomous TDD task JSON and IMPL_PLAN.md generation using action-planning-agent with two-phase execution: discovery and document generation. Supports both agent-driven execution (default) and CLI tool execution modes. Generates complete Red-Green-Refactor cycles contained within each task. + +## Core Philosophy +- **Agent-Driven**: Delegate execution to action-planning-agent for autonomous operation +- **Two-Phase Flow**: Discovery (context gathering) โ†’ Output (document generation) +- **Memory-First**: Reuse loaded documents from conversation memory +- **MCP-Enhanced**: Use MCP tools for advanced code analysis and research +- **Pre-Selected Templates**: Command selects correct TDD template based on `--cli-execute` flag **before** invoking agent +- **Agent Simplicity**: Agent receives pre-selected template and focuses only on content generation +- **Path Clarity**: All `focus_paths` prefer absolute paths (e.g., `D:\\project\\src\\module`), or clear relative paths from project root (e.g., `./src/module`) +- **TDD-First**: Every feature starts with a failing test (Red phase) +- **Feature-Complete Tasks**: Each task contains complete Red-Green-Refactor cycle +- **Quantification-Enforced**: All test cases, coverage requirements, and implementation scope MUST include explicit counts and enumerations ## Task Strategy & Philosophy @@ -44,359 +58,329 @@ Generate TDD-specific tasks from analysis results with complete Red-Green-Refact - **Current approach**: 1 feature = 1 task (IMPL-N with internal Red-Green-Refactor phases) - **Complex features**: 1 container (IMPL-N) + subtasks (IMPL-N.M) when necessary -### Core Principles -- **TDD-First**: Every feature starts with a failing test (Red phase) -- **Feature-Complete Tasks**: Each task contains complete Red-Green-Refactor cycle -- **Phase-Explicit**: Internal phases clearly marked in flow_control.implementation_approach -- **Task Merging**: Prefer single task per feature over decomposition -- **Path Clarity**: All `focus_paths` prefer absolute paths (e.g., `D:\\project\\src\\module`), or clear relative paths from project root (e.g., `./src/module`) -- **Artifact-Aware**: Integrates brainstorming outputs -- **Memory-First**: Reuse loaded documents from memory -- **Context-Aware**: Analyzes existing codebase and test patterns -- **Iterative Green Phase**: Auto-diagnose and fix test failures with Gemini + optional Codex -- **Safety-First**: Auto-revert on max iterations to prevent broken state - -## Core Responsibilities -- Parse analysis results and identify testable features -- Generate feature-complete tasks with internal TDD cycles (1 task per simple feature) -- Apply task merging strategy by default, create subtasks only when complexity requires -- Generate IMPL_PLAN.md with TDD Implementation Tasks section -- Generate TODO_LIST.md with internal TDD phase indicators -- Update session state for TDD execution with task count compliance - ## Execution Lifecycle -### Phase 1: Input Validation & Discovery -**Memory-First Rule**: Skip file loading if documents already in conversation memory +### Phase 1: Discovery & Context Loading +**โšก Memory-First Rule**: Skip file loading if documents already in conversation memory -1. **Session Validation** - - If session metadata in memory โ†’ Skip loading - - Else: Load `.workflow/{session_id}/workflow-session.json` - -2. **Conflict Resolution Check** (NEW - Priority Input) - - If CONFLICT_RESOLUTION.md exists โ†’ Load selected strategies - - Else: Skip to brainstorming artifacts - - Path: `.workflow/{session_id}/.process/CONFLICT_RESOLUTION.md` - -3. **Artifact Discovery** - - If artifact inventory in memory โ†’ Skip scanning - - Else: Scan `.workflow/{session_id}/.brainstorming/` directory - - Detect: role analysis documents, guidance-specification.md, role analyses - -4. **Context Package Loading** - - Load `.workflow/{session_id}/.process/context-package.json` - - Load `.workflow/{session_id}/.process/test-context-package.json` (if exists) - -### Phase 2: TDD Task JSON Generation - -**Input Sources** (priority order): -1. **Conflict Resolution** (if exists): `.process/CONFLICT_RESOLUTION.md` - Selected resolution strategies -2. **Brainstorming Artifacts**: Role analysis documents (system-architect, product-owner, etc.) -3. **Context Package**: `.process/context-package.json` - Project structure and requirements -4. **Test Context**: `.process/test-context-package.json` - Existing test patterns - -**TDD Task Structure includes**: -- Feature list with testable requirements -- Test cases for Red phase -- Implementation requirements for Green phase (with test-fix cycle) -- Refactoring opportunities -- Task dependencies and execution order -- Conflict resolution decisions (if applicable) - -### Phase 3: Task JSON & IMPL_PLAN.md Generation - -#### Task Structure (Feature-Complete with Internal TDD) -For each feature, generate task(s) with ID format: -- **IMPL-N** - Single task containing complete TDD cycle (Red-Green-Refactor) -- **IMPL-N.M** - Sub-tasks only when feature is complex (>2500 lines or technical blocking) - -**Task Dependency Rules**: -- **Sequential features**: IMPL-2 depends_on ["IMPL-1"] if Feature 2 needs Feature 1 -- **Independent features**: No dependencies, can execute in parallel -- **Complex features**: IMPL-N.2 depends_on ["IMPL-N.1"] for subtask ordering - -**Agent Assignment**: -- **All IMPL tasks** โ†’ `@code-developer` (handles full TDD cycle) -- Agent executes Red, Green, Refactor phases sequentially within task - -**Meta Fields**: -- `meta.type`: "feature" (TDD-driven feature implementation) -- `meta.agent`: "@code-developer" -- `meta.tdd_workflow`: true (enables TDD-specific flow) -- `meta.tdd_phase`: Not used (phases are in flow_control.implementation_approach) -- `meta.max_iterations`: 3 (for Green phase test-fix cycle) -- `meta.use_codex`: false (manual fixes by default) - -#### Task JSON Structure Reference - -**Simple Feature Task (IMPL-N.json)** - Recommended for most features: -```json +**Agent Context Package**: +```javascript { - "id": "IMPL-N", // Task identifier - "title": "Feature description with TDD", // Human-readable title - "status": "pending", // pending | in_progress | completed | container - "context_package_path": ".workflow/{session-id}/.process/context-package.json", // Path to smart context package - "meta": { - "type": "feature", // Task type - "agent": "@code-developer", // Assigned agent - "tdd_workflow": true, // REQUIRED: Enables TDD flow - "max_iterations": 3, // Green phase test-fix cycle limit - "use_codex": false // false=manual fixes, true=Codex automated fixes + "session_id": "WFS-[session-id]", + "execution_mode": "agent-mode" | "cli-execute-mode", // Determined by flag + "task_json_template_path": "~/.claude/workflows/cli-templates/prompts/workflow/task-json-agent-mode.txt" + | "~/.claude/workflows/cli-templates/prompts/workflow/task-json-cli-mode.txt", + // Path selected by command based on --cli-execute flag, agent reads it + "workflow_type": "tdd", + "session_metadata": { + // If in memory: use cached content + // Else: Load from .workflow/{session-id}/workflow-session.json }, - "context": { - "requirements": [ // Feature requirements with TDD phases - "Feature description", - "Red: Test scenarios to write", - "Green: Implementation approach with test-fix cycle", - "Refactor: Code quality improvements" - ], - "tdd_cycles": [ // OPTIONAL: Detailed test cycles + "brainstorm_artifacts": { + // Loaded from context-package.json โ†’ brainstorm_artifacts section + "role_analyses": [ { - "cycle": 1, - "feature": "Specific functionality", - "test_focus": "What to test", - "expected_failure": "Why test should fail initially" + "role": "system-architect", + "files": [{"path": "...", "type": "primary|supplementary"}] } ], - "focus_paths": ["D:\\project\\src\\path", "./tests/path"], // Absolute or clear relative paths from project root - "acceptance": [ // Success criteria - "All tests pass (Red โ†’ Green)", - "Code refactored (Refactor complete)", - "Test coverage โ‰ฅ80%" - ], - "depends_on": [] // Task dependencies + "guidance_specification": {"path": "...", "exists": true}, + "synthesis_output": {"path": "...", "exists": true}, + "conflict_resolution": {"path": "...", "exists": true} // if conflict_risk >= medium }, - "flow_control": { - "pre_analysis": [ // OPTIONAL: Pre-execution checks - { - "step": "check_test_framework", - "action": "Verify test framework", - "command": "bash(npm list jest)", - "output_to": "test_framework_info", - "on_error": "warn" - } - ], - "implementation_approach": [ // REQUIRED: 3 TDD phases - { - "step": 1, - "title": "RED Phase: Write failing tests", - "tdd_phase": "red", // REQUIRED: Phase identifier - "description": "Write comprehensive failing tests", - "modification_points": ["Files/changes to make"], - "logic_flow": ["Step-by-step process"], - "acceptance": ["Phase success criteria"], - "depends_on": [], - "output": "failing_tests" - }, - { - "step": 2, - "title": "GREEN Phase: Implement to pass tests", - "tdd_phase": "green", // REQUIRED: Phase identifier - "description": "Minimal implementation with test-fix cycle", - "modification_points": ["Implementation files"], - "logic_flow": [ - "Implement minimal code", - "Run tests", - "If fail โ†’ Enter iteration loop (max 3):", - " 1. Extract failure messages", - " 2. Gemini bug-fix diagnosis", - " 3. Apply fixes", - " 4. Rerun tests", - "If max_iterations โ†’ Auto-revert" - ], - "acceptance": ["All tests pass"], - "command": "bash(npm test -- tests/path/)", - "depends_on": [1], - "output": "passing_implementation" - }, - { - "step": 3, - "title": "REFACTOR Phase: Improve code quality", - "tdd_phase": "refactor", // REQUIRED: Phase identifier - "description": "Refactor while keeping tests green", - "modification_points": ["Quality improvements"], - "logic_flow": ["Incremental refactoring with test verification"], - "acceptance": ["Tests still pass", "Code quality improved"], - "command": "bash(npm run lint && npm test)", - "depends_on": [2], - "output": "refactored_implementation" - } - ], - "post_completion": [ // OPTIONAL: Final verification - { - "step": "verify_full_tdd_cycle", - "action": "Confirm complete TDD cycle", - "command": "bash(npm test && echo 'TDD complete')", - "output_to": "final_validation", - "on_error": "fail" - } - ], - "error_handling": { // OPTIONAL: Error recovery - "green_phase_max_iterations": { - "action": "revert_all_changes", - "commands": ["bash(git reset --hard HEAD)"], - "report": "Generate failure report" - } - } + "context_package_path": ".workflow/{session-id}/.process/context-package.json", + "context_package": { + // If in memory: use cached content + // Else: Load from .workflow/{session-id}/.process/context-package.json + }, + "test_context_package_path": ".workflow/{session-id}/.process/test-context-package.json", + "test_context_package": { + // Existing test patterns and coverage analysis + }, + "mcp_capabilities": { + "code_index": true, + "exa_code": true, + "exa_web": true } } ``` -**Key JSON Fields Summary**: -- `meta.tdd_workflow`: Must be `true` -- `meta.max_iterations`: Green phase fix cycle limit (default: 3) -- `meta.use_codex`: Automated fixes (false=manual, true=Codex) -- `flow_control.implementation_approach`: Exactly 3 steps with `tdd_phase`: "red", "green", "refactor" -- `context.tdd_cycles`: Optional detailed test cycle specifications -- `context.parent`: Required for subtasks (IMPL-N.M) +**Discovery Actions**: +1. **Load Session Context** (if not in memory) + ```javascript + if (!memory.has("workflow-session.json")) { + Read(.workflow/{session-id}/workflow-session.json) + } + ``` -#### IMPL_PLAN.md Structure +2. **Load Context Package** (if not in memory) + ```javascript + if (!memory.has("context-package.json")) { + Read(.workflow/{session-id}/.process/context-package.json) + } + ``` -Generate IMPL_PLAN.md with 8-section structure: +3. **Load Test Context Package** (if not in memory) + ```javascript + if (!memory.has("test-context-package.json")) { + Read(.workflow/{session-id}/.process/test-context-package.json) + } + ``` -**Frontmatter** (required fields): -```yaml ---- -identifier: WFS-{session-id} -source: "User requirements" | "File: path" -conflict_resolution: .workflow/{session-id}/.process/CONFLICT_RESOLUTION.md # if exists -context_package: .workflow/{session-id}/.process/context-package.json -context_package_path: .workflow/{session-id}/.process/context-package.json -test_context: .workflow/{session-id}/.process/test-context-package.json # if exists -workflow_type: "tdd" -verification_history: - conflict_resolution: "executed | skipped" # based on conflict_risk - action_plan_verify: "pending" -phase_progression: "brainstorm โ†’ context โ†’ test_context โ†’ conflict_resolution โ†’ tdd_planning" -feature_count: N -task_count: N # โ‰ค10 total -task_breakdown: - simple_features: K - complex_features: L - total_subtasks: M -tdd_workflow: true ---- +4. **Extract & Load Role Analyses** (from context-package.json) + ```javascript + // Extract role analysis paths from context package + const roleAnalysisPaths = contextPackage.brainstorm_artifacts.role_analyses + .flatMap(role => role.files.map(f => f.path)); + + // Load each role analysis file + roleAnalysisPaths.forEach(path => Read(path)); + ``` + +5. **Load Conflict Resolution** (from context-package.json, if exists) + ```javascript + if (contextPackage.brainstorm_artifacts.conflict_resolution?.exists) { + Read(contextPackage.brainstorm_artifacts.conflict_resolution.path) + } + ``` + +6. **Code Analysis with Native Tools** (optional - enhance understanding) + ```bash + # Find relevant test files and patterns + find . -name "*test*" -type f + rg "describe|it\(|test\(" -g "*.ts" + ``` + +7. **MCP External Research** (optional - gather TDD best practices) + ```javascript + // Get external TDD examples and patterns + mcp__exa__get_code_context_exa( + query="TypeScript TDD best practices Red-Green-Refactor", + tokensNum="dynamic" + ) + ``` + +### Phase 2: Agent Execution (Document Generation) + +**Pre-Agent Template Selection** (Command decides path before invoking agent): +```javascript +// Command checks flag and selects template PATH (not content) +const templatePath = hasCliExecuteFlag + ? "~/.claude/workflows/cli-templates/prompts/workflow/task-json-cli-mode.txt" + : "~/.claude/workflows/cli-templates/prompts/workflow/task-json-agent-mode.txt"; ``` -**8 Sections Structure**: +**Agent Invocation**: +```javascript +Task( + subagent_type="action-planning-agent", + description="Generate TDD task JSON and implementation plan", + prompt=` +## Execution Context -```markdown -# Implementation Plan: {Project Title} +**Session ID**: WFS-{session-id} +**Workflow Type**: TDD +**Execution Mode**: {agent-mode | cli-execute-mode} +**Task JSON Template Path**: {template_path} -## 1. Summary -- Core requirements and objectives (2-3 paragraphs) -- TDD-specific technical approach +## Phase 1: Discovery Results (Provided Context) -## 2. Context Analysis -- CCW Workflow Context (Phase progression, Quality gates) -- Context Package Summary (Focus paths, Test context) -- Project Profile (Type, Scale, Tech Stack, Timeline) -- Module Structure (Directory tree) -- Dependencies (Primary, Testing, Development) -- Patterns & Conventions +### Session Metadata +{session_metadata_content} -## 3. Brainstorming Artifacts Reference -- Artifact Usage Strategy - - CONFLICT_RESOLUTION.md (if exists - selected resolution strategies) - - role analysis documents (primary reference) - - test-context-package.json (test patterns) - - context-package.json (smart context) -- Artifact Priority in Development +### Role Analyses (Enhanced by Synthesis) +{role_analyses_content} +- Includes requirements, design specs, enhancements, and clarifications from synthesis phase -## 4. Implementation Strategy -- Execution Strategy (TDD Cycles: Red-Green-Refactor) -- Architectural Approach -- Key Dependencies (Task dependency graph) -- Testing Strategy (Coverage targets, Quality gates) +### Artifacts Inventory +- **Guidance Specification**: {guidance_spec_path} +- **Role Analyses**: {role_analyses_list} -## 5. TDD Implementation Tasks -- Feature-by-Feature TDD Tasks - - Each task: IMPL-N with internal Red โ†’ Green โ†’ Refactor - - Dependencies and complexity metrics -- Complex Feature Examples (when subtasks needed) -- TDD Task Breakdown Summary +### Context Package +{context_package_summary} +- Includes conflict_risk assessment -## 6. Implementation Plan (Detailed Phased Breakdown) -- Execution Strategy (feature-by-feature sequential) -- Phase breakdown (Phase 1, Phase 2, etc.) -- Resource Requirements (Team, Dependencies, Infrastructure) +### Test Context Package +{test_context_package_summary} +- Existing test patterns, framework config, coverage analysis -## 7. Risk Assessment & Mitigation -- Risk table (Risk, Impact, Probability, Mitigation, Owner) -- Critical Risks (TDD-specific) -- Monitoring Strategy +### Conflict Resolution (Conditional) +If conflict_risk was medium/high, modifications have been applied to: +- **guidance-specification.md**: Design decisions updated to resolve conflicts +- **Role analyses (*.md)**: Recommendations adjusted for compatibility +- **context-package.json**: Marked as "resolved" with conflict IDs +- NO separate CONFLICT_RESOLUTION.md file (conflicts resolved in-place) -## 8. Success Criteria -- Functional Completeness -- Technical Quality (Test coverage โ‰ฅ80%) -- Operational Readiness -- TDD Compliance +### MCP Analysis Results (Optional) +**Code Structure**: {mcp_code_index_results} +**External Research**: {mcp_exa_research_results} + +## Phase 2: TDD Document Generation Task + +**Agent Configuration Reference**: All TDD task generation rules, quantification requirements, Red-Green-Refactor cycle structure, quality standards, and execution details are defined in action-planning-agent. + +Refer to: @.claude/agents/action-planning-agent.md for: +- TDD Task Decomposition Standards +- Red-Green-Refactor Cycle Requirements +- Quantification Requirements (MANDATORY) +- 5-Field Task JSON Schema +- IMPL_PLAN.md Structure (TDD variant) +- TODO_LIST.md Format +- TDD Execution Flow & Quality Validation + +### TDD-Specific Requirements Summary + +#### Task Structure Philosophy +- **1 feature = 1 task** containing complete TDD cycle internally +- Each task executes Red-Green-Refactor phases sequentially +- Task count = Feature count (typically 5 features = 5 tasks) +- Subtasks only when complexity >2500 lines or >6 files per cycle +- **Maximum 10 tasks** (hard limit for TDD workflows) + +#### TDD Cycle Mapping +- **Simple features**: IMPL-N with internal Red-Green-Refactor phases +- **Complex features**: IMPL-N (container) + IMPL-N.M (subtasks) +- Each cycle includes: test_count, test_cases array, implementation_scope, expected_coverage + +#### Required Outputs Summary + +##### 1. TDD Task JSON Files (.task/IMPL-*.json) +- **Location**: `.workflow/{session-id}/.task/` +- **Template**: Read from `{template_path}` (pre-selected by command based on `--cli-execute` flag) +- **Schema**: 5-field structure with TDD-specific metadata + - `meta.tdd_workflow`: true (REQUIRED) + - `meta.max_iterations`: 3 (Green phase test-fix cycle limit) + - `meta.use_codex`: false (manual fixes by default) + - `context.tdd_cycles`: Array with quantified test cases and coverage + - `flow_control.implementation_approach`: Exactly 3 steps with `tdd_phase` field + 1. Red Phase (`tdd_phase: "red"`): Write failing tests + 2. Green Phase (`tdd_phase: "green"`): Implement to pass tests + 3. Refactor Phase (`tdd_phase: "refactor"`): Improve code quality +- **Details**: See action-planning-agent.md ยง TDD Task JSON Generation + +##### 2. IMPL_PLAN.md (TDD Variant) +- **Location**: `.workflow/{session-id}/IMPL_PLAN.md` +- **Template**: `~/.claude/workflows/cli-templates/prompts/workflow/impl-plan-template.txt` +- **TDD-Specific Frontmatter**: workflow_type="tdd", tdd_workflow=true, feature_count, task_breakdown +- **TDD Implementation Tasks Section**: Feature-by-feature with internal Red-Green-Refactor cycles +- **Details**: See action-planning-agent.md ยง TDD Implementation Plan Creation + +##### 3. TODO_LIST.md +- **Location**: `.workflow/{session-id}/TODO_LIST.md` +- **Format**: Hierarchical task list with internal TDD phase indicators (Red โ†’ Green โ†’ Refactor) +- **Status**: โ–ธ (container), [ ] (pending), [x] (completed) +- **Details**: See action-planning-agent.md ยง TODO List Generation + +### Quantification Requirements (MANDATORY) + +**Core Rules**: +1. **Explicit Test Case Counts**: Red phase specifies exact number with enumerated list +2. **Quantified Coverage**: Acceptance includes measurable percentage (e.g., ">=85%") +3. **Detailed Implementation Scope**: Green phase enumerates files, functions, line counts +4. **Enumerated Refactoring Targets**: Refactor phase lists specific improvements with counts + +**TDD Phase Formats**: +- **Red Phase**: "Write N test cases: [test1, test2, ...]" +- **Green Phase**: "Implement N functions in file lines X-Y: [func1() X1-Y1, func2() X2-Y2, ...]" +- **Refactor Phase**: "Apply N refactorings: [improvement1 (details), improvement2 (details), ...]" +- **Acceptance**: "All N tests pass with >=X% coverage: verify by [test command]" + +**Validation Checklist**: +- [ ] Every Red phase specifies exact test case count with enumerated list +- [ ] Every Green phase enumerates files, functions, and estimated line counts +- [ ] Every Refactor phase lists specific improvements with counts +- [ ] Every acceptance criterion includes measurable coverage percentage +- [ ] tdd_cycles array contains test_count and test_cases for each cycle +- [ ] No vague language ("comprehensive", "complete", "thorough") + +### Agent Execution Summary + +**Key Steps** (Detailed instructions in action-planning-agent.md): +1. Load task JSON template from provided path +2. Extract and decompose features with TDD cycles +3. Generate TDD task JSON files enforcing quantification requirements +4. Create IMPL_PLAN.md using TDD template variant +5. Generate TODO_LIST.md with TDD phase indicators +6. Update session state with TDD metadata + +**Quality Gates** (Full checklist in action-planning-agent.md): +- โœ“ Quantification requirements enforced (explicit counts, measurable acceptance, exact targets) +- โœ“ Task count โ‰ค10 (hard limit) +- โœ“ Each task has meta.tdd_workflow: true +- โœ“ Each task has exactly 3 implementation steps with tdd_phase field +- โœ“ Green phase includes test-fix cycle logic +- โœ“ Artifact references mapped correctly +- โœ“ MCP tool integration added +- โœ“ Documents follow TDD template structure + +## Output + +Generate all three documents and report completion status: +- TDD task JSON files created: N files (IMPL-*.json) +- TDD cycles configured: N cycles with quantified test cases +- Artifacts integrated: synthesis-spec, guidance-specification, N role analyses +- Test context integrated: existing patterns and coverage +- MCP enhancements: code-index, exa-research +- Session ready for TDD execution: /workflow:execute +` +) ``` -### Phase 4: TODO_LIST.md Generation +### Agent Context Passing -Generate task list with internal TDD phase indicators: +**Memory-Aware Context Assembly**: +```javascript +// Assemble context package for agent +const agentContext = { + session_id: "WFS-[id]", + workflow_type: "tdd", -**For Simple Features (1 task per feature)**: -```markdown -## TDD Implementation Tasks + // Use memory if available, else load + session_metadata: memory.has("workflow-session.json") + ? memory.get("workflow-session.json") + : Read(.workflow/WFS-[id]/workflow-session.json), -### Feature 1: {Feature Name} -- [ ] **IMPL-1**: Implement {feature} with TDD โ†’ [Task](./.task/IMPL-1.json) - - Internal phases: Red โ†’ Green โ†’ Refactor - - Dependencies: None + context_package_path: ".workflow/WFS-[id]/.process/context-package.json", -### Feature 2: {Feature Name} -- [ ] **IMPL-2**: Implement {feature} with TDD โ†’ [Task](./.task/IMPL-2.json) - - Internal phases: Red โ†’ Green โ†’ Refactor - - Dependencies: IMPL-1 -``` + context_package: memory.has("context-package.json") + ? memory.get("context-package.json") + : Read(".workflow/WFS-[id]/.process/context-package.json"), -**For Complex Features (with subtasks)**: -```markdown -### Feature 3: {Complex Feature Name} -โ–ธ **IMPL-3**: Implement {complex feature} with TDD โ†’ [Task](./.task/IMPL-3.json) - - [ ] **IMPL-3.1**: {Sub-feature A} with TDD โ†’ [Task](./.task/IMPL-3.1.json) - - Internal phases: Red โ†’ Green โ†’ Refactor - - [ ] **IMPL-3.2**: {Sub-feature B} with TDD โ†’ [Task](./.task/IMPL-3.2.json) - - Internal phases: Red โ†’ Green โ†’ Refactor - - Dependencies: IMPL-3.1 -``` + test_context_package_path: ".workflow/WFS-[id]/.process/test-context-package.json", -**Status Legend**: -```markdown -## Status Legend -- โ–ธ = Container task (has subtasks) -- [ ] = Pending task -- [x] = Completed task -- Red = Write failing tests -- Green = Implement to pass tests (with test-fix cycle) -- Refactor = Improve code quality -``` + test_context_package: memory.has("test-context-package.json") + ? memory.get("test-context-package.json") + : Read(".workflow/WFS-[id]/.process/test-context-package.json"), -### Phase 5: Session State Update + // Extract brainstorm artifacts from context package + brainstorm_artifacts: extractBrainstormArtifacts(context_package), -Update workflow-session.json with TDD metadata: -```json -{ - "workflow_type": "tdd", - "feature_count": 5, - "task_count": 5, - "task_breakdown": { - "simple_features": 4, - "complex_features": 1, - "total_subtasks": 2 - }, - "tdd_workflow": true, - "task_limit_compliance": true + // Load role analyses using paths from context package + role_analyses: brainstorm_artifacts.role_analyses + .flatMap(role => role.files) + .map(file => Read(file.path)), + + // Load conflict resolution if exists (from context package) + conflict_resolution: brainstorm_artifacts.conflict_resolution?.exists + ? Read(brainstorm_artifacts.conflict_resolution.path) + : null, + + // Optional MCP enhancements + mcp_analysis: executeMcpDiscovery() } ``` -**Task Count Calculation**: -- **Simple features**: 1 task each (IMPL-N with internal TDD cycle) -- **Complex features**: 1 container + M subtasks (IMPL-N + IMPL-N.M) -- **Total**: Simple feature count + Complex feature subtask count -- **Example**: 4 simple + 1 complex (with 2 subtasks) = 6 total tasks (not 15) +## TDD Task Structure Reference + +This section provides quick reference for TDD task JSON structure. For complete implementation details, see the agent invocation prompt in Phase 2 above. + +**Quick Reference**: +- Each TDD task contains complete Red-Green-Refactor cycle +- Task ID format: `IMPL-N` (simple) or `IMPL-N.M` (complex subtasks) +- Required metadata: `meta.tdd_workflow: true`, `meta.max_iterations: 3` +- Flow control: Exactly 3 steps with `tdd_phase` field (red, green, refactor) +- Context: `tdd_cycles` array with quantified test cases and coverage +- See Phase 2 agent prompt for full schema and requirements ## Output Files Structure ``` @@ -465,52 +449,30 @@ Update workflow-session.json with TDD metadata: ## Integration & Usage -### Command Chain -- **Called By**: `/workflow:tdd-plan` (Phase 4) -- **Calls**: Gemini CLI for TDD breakdown -- **Followed By**: `/workflow:execute`, `/workflow:tdd-verify` +**Command Chain**: +- Called by: `/workflow:tdd-plan` (Phase 4) +- Invokes: `action-planning-agent` for autonomous task generation +- Followed by: `/workflow:execute`, `/workflow:tdd-verify` -### Basic Usage +**Basic Usage**: ```bash -# Manual mode (default) +# Agent mode (default, autonomous execution) /workflow:tools:task-generate-tdd --session WFS-auth -# Agent mode (autonomous task generation) -/workflow:tools:task-generate-tdd --session WFS-auth --agent +# CLI tool mode (use Gemini/Qwen for generation) +/workflow:tools:task-generate-tdd --session WFS-auth --cli-execute ``` -### Expected Output -``` -TDD task generation complete for session: WFS-auth +**Execution Modes**: +- **Agent mode** (default): Uses `action-planning-agent` with agent-mode task template +- **CLI mode** (`--cli-execute`): Uses Gemini/Qwen with cli-mode task template -Features analyzed: 5 -Total tasks: 5 (1 task per feature with internal TDD cycles) - -Task breakdown: -- Simple features: 4 tasks (IMPL-1 to IMPL-4) -- Complex features: 1 task with 2 subtasks (IMPL-5, IMPL-5.1, IMPL-5.2) -- Total task count: 6 (within 10-task limit) - -Structure: -- IMPL-1: User Authentication (Internal: Red โ†’ Green โ†’ Refactor) -- IMPL-2: Password Reset (Internal: Red โ†’ Green โ†’ Refactor) -- IMPL-3: Email Verification (Internal: Red โ†’ Green โ†’ Refactor) -- IMPL-4: Role Management (Internal: Red โ†’ Green โ†’ Refactor) -- IMPL-5: Payment System (Container) - - IMPL-5.1: Gateway Integration (Internal: Red โ†’ Green โ†’ Refactor) - - IMPL-5.2: Transaction Management (Internal: Red โ†’ Green โ†’ Refactor) - -Plans generated: -- Unified Plan: .workflow/WFS-auth/IMPL_PLAN.md (includes TDD Implementation Tasks section) -- Task List: .workflow/WFS-auth/TODO_LIST.md (with internal TDD phase indicators) - -TDD Configuration: -- Each task contains complete Red-Green-Refactor cycle -- Green phase includes test-fix cycle (max 3 iterations) -- Auto-revert on max iterations reached - -Next: /workflow:action-plan-verify --session WFS-auth (recommended) or /workflow:execute --session WFS-auth -``` +**Output**: +- TDD task JSON files in `.task/` directory (IMPL-N.json format) +- IMPL_PLAN.md with TDD Implementation Tasks section +- TODO_LIST.md with internal TDD phase indicators +- Session state updated with task count and TDD metadata +- MCP enhancements integrated (if available) ## Test Coverage Analysis Integration @@ -547,9 +509,3 @@ IMPL (Green phase) tasks include automatic test-fix cycle: - **meta.max_iterations**: Number of fix attempts (default: 3 for TDD, 5 for test-gen) - **meta.use_codex**: Enable Codex automated fixes (default: false, manual) -## Related Commands -- `/workflow:tdd-plan` - Orchestrates TDD workflow planning (6 phases) -- `/workflow:tools:test-context-gather` - Analyzes test coverage -- `/workflow:execute` - Executes TDD tasks in order -- `/workflow:tdd-verify` - Verifies TDD compliance -- `/workflow:test-gen` - Post-implementation test generation diff --git a/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate.md b/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate.md index 10614588..1c35fdaf 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate.md +++ b/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate.md @@ -45,8 +45,33 @@ This command is built on a set of core principles to ensure efficient and reliab - **Memory-First**: Prioritizes using documents already loaded in conversation memory to avoid redundant file operations - **Mode-Flexible**: Supports both agent-driven execution (default) and CLI tool execution (with `--cli-execute` flag) - **Multi-Step Support**: Complex tasks can use multiple sequential steps in `implementation_approach` with codex resume mechanism +- **Quantification-Enforced**: **NEW** - All requirements, acceptance criteria, and modification points MUST include explicit counts and enumerations to prevent ambiguity (e.g., "17 commands: [list]" not "implement commands") - **Responsibility**: Parses analysis, detects artifacts, generates enhanced task JSONs, creates `IMPL_PLAN.md` and `TODO_LIST.md`, updates session state +## 3.5. Quantification Requirements (MANDATORY) + +**Purpose**: Eliminate ambiguity by enforcing explicit counts and enumerations in all task specifications. + +**Core Rules**: +1. **Extract Counts from Analysis**: Search for HOW MANY items and list them explicitly +2. **Enforce Explicit Lists**: Every deliverable uses format `{count} {type}: [{explicit_list}]` +3. **Make Acceptance Measurable**: Include verification commands (e.g., `ls ... | wc -l = N`) +4. **Quantify Modification Points**: Specify exact targets (files, functions with line numbers) +5. **Avoid Vague Language**: Replace "complete", "comprehensive", "reorganize" with quantified statements + +**Standard Formats**: + +- **Requirements**: `"Implement N items: [item1, item2, ...]"` or `"Modify N files: [file1:func:lines, ...]"` +- **Acceptance**: `"N items exist: verify by [command]"` or `"Coverage >= X%: verify by [test command]"` +- **Modification Points**: `"Create N files: [list]"` or `"Modify N functions: [func() in file lines X-Y]"` + +**Validation Checklist**: +- [ ] Every requirement contains explicit count or enumerated list +- [ ] Every acceptance criterion is measurable with verification command +- [ ] Every modification_point specifies exact targets (files/functions/lines) +- [ ] No vague language ("complete", "comprehensive", "reorganize" without counts) +- [ ] Each implementation step has its own acceptance criteria + ## 4. Execution Flow The command follows a streamlined, three-step process to convert analysis into executable tasks. @@ -59,13 +84,39 @@ The process begins by gathering all necessary inputs. It follows a **Memory-Firs ### Step 2: Task Decomposition & Grouping Once all inputs are loaded, the command analyzes the tasks defined in the analysis results and groups them based on shared context. -1. **Task Definition Parsing**: Extracts task definitions, requirements, and dependencies. -2. **Context Signature Analysis**: Computes a unique hash (`context_signature`) for each task based on its `focus_paths` and referenced `artifacts`. + +**Phase 2.1: Quantification Extraction (NEW - CRITICAL)** +1. **Count Extraction**: Scan analysis documents for quantifiable information: + - Search for numbers + nouns (e.g., "5 files", "17 commands", "3 features") + - Identify enumerated lists (bullet points, numbered lists, comma-separated items) + - Extract explicit counts from tables, diagrams, or structured data + - Store extracted counts with their context (what is being counted) + +2. **List Enumeration**: Build explicit lists for each deliverable: + - If analysis says "implement session commands", enumerate ALL commands: [start, resume, list, complete, archive] + - If analysis mentions "create categories", list ALL categories: [literature, experiment, data-analysis, visualization, context] + - If analysis describes "modify functions", list ALL functions with line numbers + - Maintain full enumerations (no "..." unless list exceeds 20 items) + +3. **Verification Method Assignment**: For each deliverable, determine verification approach: + - File count: `ls {path}/*.{ext} | wc -l = {count}` + - Directory existence: `ls {parent}/ | grep -E '(name1|name2|...)' | wc -l = {count}` + - Test coverage: `pytest --cov={module} --cov-report=term | grep TOTAL | awk '{print $4}' >= {percentage}` + - Function existence: `grep -E '(func1|func2|...)' {file} | wc -l = {count}` + +4. **Ambiguity Detection**: Flag vague language for replacement: + - Detect words: "complete", "comprehensive", "reorganize", "refactor", "implement", "create" without counts + - Require quantification: "implement" โ†’ "implement {N} {items}: [{list}]" + - Reject unquantified deliverables + +**Phase 2.2: Task Definition & Grouping** +1. **Task Definition Parsing**: Extracts task definitions, requirements, and dependencies from quantified analysis +2. **Context Signature Analysis**: Computes a unique hash (`context_signature`) for each task based on its `focus_paths` and referenced `artifacts` 3. **Task Grouping**: - * Tasks with the **same signature** are candidates for merging, as they operate on the same context. - * Tasks with **different signatures** and no dependencies are grouped for parallel execution. - * Tasks with `depends_on` relationships are marked for sequential execution. -4. **Modification Target Determination**: Extracts specific code locations (`file:function:lines`) from the analysis to populate the `target_files` field. + * Tasks with the **same signature** are candidates for merging, as they operate on the same context + * Tasks with **different signatures** and no dependencies are grouped for parallel execution + * Tasks with `depends_on` relationships are marked for sequential execution +4. **Modification Target Determination**: Extracts specific code locations (`file:function:lines`) from the analysis to populate the `target_files` field ### Step 3: Output Generation Finally, the command generates all the necessary output files. @@ -167,38 +218,82 @@ function assignExecutionGroups(tasks) { The command produces three key documents and a directory of task files. ### 6.1. Task JSON Schema (`.task/IMPL-*.json`) -This enhanced 5-field schema embeds all necessary context, artifacts, and execution steps. +Each task JSON embeds all necessary context, artifacts, and execution steps using this schema: +**Top-Level Fields**: +- `id`: Task identifier (format: `IMPL-N` or `IMPL-N.M` for subtasks) +- `title`: Descriptive task name +- `status`: Task state (`pending|active|completed|blocked|container`) +- `context_package_path`: Path to context package (`.workflow/WFS-[session]/.process/context-package.json`) +- `meta`: Task metadata +- `context`: Task-specific context and requirements +- `flow_control`: Execution steps and workflow + +**Meta Object**: +- `type`: Task category (`feature|bugfix|refactor|test-gen|test-fix|docs`) +- `agent`: Assigned agent (`@code-developer|@test-fix-agent|@universal-executor`) +- `execution_group`: Parallelization group ID or null +- `context_signature`: Hash for context-based grouping + +**Context Object**: +- `requirements`: Quantified implementation requirements (with counts and explicit lists) +- `focus_paths`: Target directories/files (absolute or relative paths) +- `acceptance`: Measurable acceptance criteria (with verification commands) +- `parent`: Parent task ID for subtasks +- `depends_on`: Prerequisite task IDs +- `inherited`: Shared patterns and dependencies from parent +- `shared_context`: Tech stack and conventions +- `artifacts`: Referenced brainstorm artifacts with paths, priority, and usage + +**Flow Control Object**: +- `pre_analysis`: Context loading and preparation steps + - `load_context_package`: Load smart context and artifact catalog + - `load_role_analysis_artifacts`: Load role analyses dynamically from context package + - `load_planning_context`: Load finalized decisions with resolved conflicts + - `codebase_exploration`: Discover existing patterns + - `analyze_task_patterns`: Identify modification targets +- `implementation_approach`: Execution steps + - **Agent Mode**: Steps contain `modification_points` and `logic_flow` (agent executes autonomously) + - **CLI Mode**: Steps include `command` field with CLI tool invocation +- `target_files`: Specific files/functions/lines to modify + +**Key Characteristics**: +- **Quantification**: All requirements/acceptance use explicit counts and enumerations +- **Mode Flexibility**: Supports both agent execution (default) and CLI tool execution (`--cli-execute`) +- **Context Intelligence**: References context-package.json for smart context and artifact paths +- **Artifact Integration**: Dynamically loads role analyses and brainstorm artifacts + +**Example Task JSON**: ```json { - "id": "IMPL-N[.M]", - "title": "Descriptive task name", - "status": "pending|active|completed|blocked|container", - "context_package_path": ".workflow/WFS-[session]/.process/context-package.json", + "id": "IMPL-1", + "title": "Implement feature X with Y components", + "status": "pending", + "context_package_path": ".workflow/WFS-session/.process/context-package.json", "meta": { - "type": "feature|bugfix|refactor|test-gen|test-fix|docs", - "agent": "@code-developer|@test-fix-agent|@universal-executor", - "execution_group": "group-id|null", - "context_signature": "hash-of-focus_paths-and-artifacts" + "type": "feature", + "agent": "@code-developer", + "execution_group": "parallel-abc123", + "context_signature": "hash-value" }, "context": { - "requirements": ["Clear requirement from analysis"], - "focus_paths": ["D:\\project\\src\\module\\path", "./tests/module/path"], - "acceptance": ["Measurable acceptance criterion"], - "parent": "IMPL-N", - "depends_on": ["IMPL-N.M"], - "inherited": {"shared_patterns": [], "common_dependencies": []}, - "shared_context": {"tech_stack": [], "conventions": []}, + "requirements": [ + "Implement 5 commands: [cmd1, cmd2, cmd3, cmd4, cmd5]", + "Create 3 directories: [dir1/, dir2/, dir3/]", + "Modify 2 functions: [funcA() in file1.ts lines 10-25, funcB() in file2.ts lines 40-60]" + ], + "focus_paths": ["D:\\project\\src\\module", "./tests/module"], + "acceptance": [ + "5 command files created: verify by ls .claude/commands/*/*.md | wc -l = 5", + "3 directories exist: verify by ls -d dir*/ | wc -l = 3", + "All tests pass: pytest tests/ --cov=src/module (>=80% coverage)" + ], + "depends_on": [], "artifacts": [ { - "path": "{{from context-package.json โ†’ brainstorm_artifacts.role_analyses[].files[].path}}", + "path": ".workflow/WFS-session/.brainstorming/system-architect/analysis.md", "priority": "highest", - "usage": "Role-specific requirements, design specs, enhanced by synthesis. Paths loaded dynamically from context-package.json (supports multiple files per role: analysis.md, analysis-01.md, analysis-api.md, etc.). Common roles: product-manager, system-architect, ui-designer, data-architect, ux-expert." - }, - { - "path": ".workflow/WFS-[session]/.brainstorming/guidance-specification.md", - "priority": "high", - "usage": "Finalized design decisions (potentially modified by conflict resolution if conflict_risk was medium/high). Use for: understanding resolved requirements, design choices, conflict resolutions applied in-place" + "usage": "Architecture decisions and API specifications" } ] }, @@ -206,18 +301,14 @@ This enhanced 5-field schema embeds all necessary context, artifacts, and execut "pre_analysis": [ { "step": "load_context_package", - "action": "Load context package for artifact paths", - "note": "Context package path is now at top-level field: context_package_path", - "commands": [ - "Read({{context_package_path}})" - ], + "action": "Load context package for artifact paths and smart context", + "commands": ["Read({{context_package_path}})"], "output_to": "context_package", "on_error": "fail" }, { "step": "load_role_analysis_artifacts", - "action": "Load role analyses from context-package.json (supports multiple files per role)", - "note": "Paths loaded from context-package.json โ†’ brainstorm_artifacts.role_analyses[]. Supports analysis*.md automatically.", + "action": "Load role analyses from context-package.json", "commands": [ "Read({{context_package_path}})", "Extract(brainstorm_artifacts.role_analyses[].files[].path)", @@ -225,73 +316,36 @@ This enhanced 5-field schema embeds all necessary context, artifacts, and execut ], "output_to": "role_analysis_artifacts", "on_error": "skip_optional" - }, - { - "step": "load_planning_context", - "action": "Load plan-generated context intelligence with resolved conflicts", - "note": "CRITICAL: context-package.json (from context_package_path) provides smart context (focus paths, dependencies, patterns) and conflict resolution status. If conflict_risk was medium/high, conflicts have been resolved in guidance-specification.md and role analyses.", - "commands": [ - "Read({{context_package_path}})", - "Read(.workflow/WFS-[session]/.brainstorming/guidance-specification.md)" - ], - "output_to": "planning_context", - "on_error": "fail", - "usage_guidance": { - "context-package.json": "Use for focus_paths validation, dependency resolution, existing pattern discovery, module structure understanding, conflict_risk status (resolved/none/low)", - "guidance-specification.md": "Use for finalized design decisions (includes applied conflict resolutions if any)" - } - }, - { - "step": "codebase_exploration", - "action": "Explore codebase using native tools", - "command": "bash(find . -name \"[patterns]\" -type f && rg \"[patterns]\")", - "output_to": "codebase_structure" - }, - { - "step": "analyze_task_patterns", - "action": "Analyze existing code patterns and identify modification targets", - "commands": [ - "bash(cd \"[focus_paths]\")", - "bash(gemini \"PURPOSE: Identify modification targets TASK: Analyze '[title]' and locate specific files/functions/lines to modify CONTEXT: [role_analyses] [individual_artifacts] EXPECTED: Code locations in format 'file:function:lines' RULES: Consult role analyses for requirements, identify exact modification points\")" - ], - "output_to": "task_context_with_targets", - "on_error": "fail" } ], "implementation_approach": [ { "step": 1, - "title": "Implement task following role analyses and context", - "description": "Implement '[title]' following this priority: 1) role analysis.md files (requirements, design specs, enhancements from synthesis), 2) guidance-specification.md (finalized decisions with resolved conflicts), 3) context-package.json (smart context, focus paths, patterns). Role analyses are enhanced by synthesis phase with concept improvements and clarifications. If conflict_risk was medium/high, conflict resolutions are already applied in-place.", + "title": "Implement feature following role analyses", + "description": "Implement feature X using requirements from role analyses and context package", "modification_points": [ - "Apply requirements and design specs from role analysis documents", - "Use enhancements and clarifications from synthesis phase", - "Use finalized decisions from guidance-specification.md (includes resolved conflicts)", - "Use context-package.json for focus paths and dependency resolution", - "Consult specific role artifacts for implementation details when needed", - "Integrate with existing patterns" + "Create 5 command files: [cmd1.md, cmd2.md, cmd3.md, cmd4.md, cmd5.md]", + "Modify funcA() in file1.ts lines 10-25: add validation logic", + "Modify funcB() in file2.ts lines 40-60: integrate with new API" ], "logic_flow": [ - "Load role analyses (requirements, design, enhancements from synthesis)", - "Load guidance-specification.md (finalized decisions with resolved conflicts if any)", - "Load context-package.json (smart context: focus paths, dependencies, patterns, conflict_risk status)", - "Extract requirements and design decisions from role documents", - "Review synthesis enhancements and clarifications", - "Use finalized decisions (conflicts already resolved if applicable)", - "Identify modification targets using context package", - "Implement following role requirements and design specs", - "Consult role artifacts for detailed specifications when needed", + "Load role analyses and context package", + "Extract requirements and design decisions", + "Implement commands following existing patterns", + "Update functions with new logic", "Validate against acceptance criteria" ], "depends_on": [], "output": "implementation" } ], - "target_files": ["file:function:lines"] + "target_files": ["file1.ts:funcA:10-25", "file2.ts:funcB:40-60"] } } ``` +**Note**: In CLI Execute Mode (`--cli-execute`), `implementation_approach` steps include a `command` field with the CLI tool invocation (e.g., `bash(codex ...)`). + ### 6.2. IMPL_PLAN.md Structure This document provides a high-level overview of the entire implementation plan. @@ -585,194 +639,7 @@ Artifacts are mapped to tasks based on their relevance to the task's domain. This ensures that each task has access to the most relevant and detailed specifications from role-specific analyses. -## 8. CLI Execute Mode Details -When using `--cli-execute`, each step in `implementation_approach` includes a `command` field with the execution command. - -**Key Points**: -- **Sequential Steps**: Steps execute in order defined in `implementation_approach` array - - **Context Delivery**: Each codex command receives context via CONTEXT field: `@{context_package_path}` (role analyses loaded dynamically from context package)- **Multi-Step Tasks**: First step provides full context, subsequent steps use `resume --last` to maintain session continuity -- **Step Dependencies**: Later steps reference outputs from earlier steps via `depends_on` field - -### Example 1: Agent Mode - Simple Task (Default, No Command) -```json -{ - "id": "IMPL-001", - "title": "Implement user authentication module", - "context_package_path": ".workflow/WFS-session/.process/context-package.json", - "context": { - "depends_on": [], - "focus_paths": ["src/auth"], - "requirements": ["JWT-based authentication", "Login and registration endpoints"], - "acceptance": [ - "JWT token generation working", - "Login and registration endpoints implemented", - "Tests passing with >70% coverage" - ] - }, - "flow_control": { - "pre_analysis": [ - { - "step": "load_role_analyses", - "action": "Load role analyses from context-package.json", - "commands": [ - "Read({{context_package_path}})", - "Extract(brainstorm_artifacts.role_analyses[].files[].path)", - "Read(each extracted path)" - ], - "output_to": "role_analyses", - "on_error": "fail" - }, - { - "step": "load_context", - "action": "Load context package for project structure", - "commands": ["Read({{context_package_path}})"], - "output_to": "context_pkg", - "on_error": "fail" - } - ], - "implementation_approach": [ - { - "step": 1, - "title": "Implement JWT-based authentication", - "description": "Create authentication module using JWT following [role_analyses] requirements and [context_pkg] patterns", - "modification_points": [ - "Create auth service with JWT generation", - "Implement login endpoint with credential validation", - "Implement registration endpoint with user creation", - "Add JWT middleware for route protection" - ], - "logic_flow": [ - "User registers โ†’ validate input โ†’ hash password โ†’ create user", - "User logs in โ†’ validate credentials โ†’ generate JWT โ†’ return token", - "Protected routes โ†’ validate JWT โ†’ extract user โ†’ allow access" - ], - "depends_on": [], - "output": "auth_implementation" - } - ], - "target_files": ["src/auth/service.ts", "src/auth/middleware.ts", "src/routes/auth.ts"] - } -} -``` - -### Example 2: CLI Execute Mode - Single Codex Step -```json -{ - "id": "IMPL-002", - "title": "Implement user authentication module", - "context_package_path": ".workflow/WFS-session/.process/context-package.json", - "context": { - "depends_on": [], - "focus_paths": ["src/auth"], - "requirements": ["JWT-based authentication", "Login and registration endpoints"], - "acceptance": ["JWT generation working", "Endpoints implemented", "Tests passing"] - }, - "flow_control": { - "pre_analysis": [ - { - "step": "load_role_analyses", - "action": "Load role analyses from context-package.json", - "commands": [ - "Read({{context_package_path}})", - "Extract(brainstorm_artifacts.role_analyses[].files[].path)", - "Read(each extracted path)" - ], - "output_to": "role_analyses", - "on_error": "fail" - } - ], - "implementation_approach": [ - { - "step": 1, - "title": "Implement authentication with Codex", - "description": "Create JWT-based authentication module", - "command": "bash(codex -C src/auth --full-auto exec \"PURPOSE: Implement user authentication TASK: JWT-based auth with login/registration MODE: auto CONTEXT: @{{context_package_path}} EXPECTED: Complete auth module with tests RULES: Load role analyses from context-package.json โ†’ brainstorm_artifacts\" --skip-git-repo-check -s danger-full-access)", - "modification_points": ["Create auth service", "Implement endpoints", "Add JWT middleware"], - "logic_flow": ["Validate credentials", "Generate JWT", "Return token"], - "depends_on": [], - "output": "auth_implementation" - } - ], - "target_files": ["src/auth/service.ts", "src/auth/middleware.ts"] - } -} -``` - -### Example 3: CLI Execute Mode - Multi-Step with Resume -```json -{ - "id": "IMPL-003", - "title": "Implement role-based access control", - "context_package_path": ".workflow/WFS-session/.process/context-package.json", - "context": { - "depends_on": ["IMPL-002"], - "focus_paths": ["src/auth", "src/middleware"], - "requirements": ["User roles and permissions", "Route protection middleware"], - "acceptance": ["RBAC models created", "Middleware working", "Management API complete"] - }, - "flow_control": { - "pre_analysis": [ - { - "step": "load_context", - "action": "Load context and role analyses from context-package.json", - "commands": [ - "Read({{context_package_path}})", - "Extract(brainstorm_artifacts.role_analyses[].files[].path)", - "Read(each extracted path)" - ], - "output_to": "full_context", - "on_error": "fail" - } - ], - "implementation_approach": [ - { - "step": 1, - "title": "Create RBAC models", - "description": "Define role and permission data models", - "command": "bash(codex -C src/auth --full-auto exec \"PURPOSE: Create RBAC models TASK: Role and permission models MODE: auto CONTEXT: @{{context_package_path}} EXPECTED: Models with migrations RULES: Load role analyses from context-package.json โ†’ brainstorm_artifacts\" --skip-git-repo-check -s danger-full-access)", - "modification_points": ["Define role model", "Define permission model", "Create migrations"], - "logic_flow": ["Design schema", "Implement models", "Generate migrations"], - "depends_on": [], - "output": "rbac_models" - }, - { - "step": 2, - "title": "Implement RBAC middleware", - "description": "Create route protection middleware using models from step 1", - "command": "bash(codex --full-auto exec \"PURPOSE: Create RBAC middleware TASK: Route protection middleware MODE: auto CONTEXT: RBAC models from step 1 EXPECTED: Middleware for route protection RULES: Use session patterns\" resume --last --skip-git-repo-check -s danger-full-access)", - "modification_points": ["Create permission checker", "Add route decorators", "Integrate with auth"], - "logic_flow": ["Check user role", "Validate permissions", "Allow/deny access"], - "depends_on": [1], - "output": "rbac_middleware" - }, - { - "step": 3, - "title": "Add role management API", - "description": "Create CRUD endpoints for roles and permissions", - "command": "bash(codex --full-auto exec \"PURPOSE: Role management API TASK: CRUD endpoints for roles/permissions MODE: auto CONTEXT: Models and middleware from previous steps EXPECTED: Complete API with validation RULES: Maintain consistency\" resume --last --skip-git-repo-check -s danger-full-access)", - "modification_points": ["Create role endpoints", "Create permission endpoints", "Add validation"], - "logic_flow": ["Define routes", "Implement controllers", "Add authorization"], - "depends_on": [2], - "output": "role_management_api" - } - ], - "target_files": [ - "src/models/Role.ts", - "src/models/Permission.ts", - "src/middleware/rbac.ts", - "src/routes/roles.ts" - ] - } -} -``` - -**Pattern Summary**: -- **Agent Mode (Example 1)**: No `command` field - agent executes via `modification_points` and `logic_flow` -- **CLI Mode Single-Step (Example 2)**: One `command` field with full context package -- **CLI Mode Multi-Step (Example 3)**: First step uses full context, subsequent steps use `resume --last` -- **Context Delivery**: Context package provided via `@{...}` references in CONTEXT field - -## 9. Error Handling +## 8. Error Handling ### Input Validation Errors | Error | Cause | Resolution | @@ -795,21 +662,19 @@ When using `--cli-execute`, each step in `implementation_approach` includes a `c | Invalid format | Corrupted file | Skip artifact loading | | Path invalid | Moved/deleted | Update references | -## 10. Integration & Usage +## 10. Usage & Related Commands -### Command Chain -- **Called By**: `/workflow:plan` (Phase 4) -- **Calls**: None (terminal command) -- **Followed By**: `/workflow:execute`, `/workflow:status` - -### Basic Usage +**Basic Usage**: ```bash -/workflow:tools:task-generate --session WFS-auth +/workflow:tools:task-generate --session WFS-auth [--cli-execute] ``` -## 11. Related Commands -- `/workflow:plan` - Orchestrates entire planning -- `/workflow:plan --cli-execute` - Planning with CLI execution mode -- `/workflow:tools:context-gather` - Provides context package -- `/workflow:tools:conflict-resolution` - Provides conflict resolution strategies (optional) +**Workflow Integration**: +- Called by: `/workflow:plan` (task generation phase) +- Followed by: `/workflow:execute`, `/workflow:status` + +**Related Commands**: +- `/workflow:plan` - Orchestrates entire planning workflow +- `/workflow:tools:context-gather` - Provides context package input +- `/workflow:tools:conflict-resolution` - Provides conflict resolution (if needed) - `/workflow:execute` - Executes generated tasks diff --git a/.claude/skills/command-guide/reference/commands/workflow/tools/tdd-coverage-analysis.md b/.claude/skills/command-guide/reference/commands/workflow/tools/tdd-coverage-analysis.md index 0e9f0ae9..7f8a7c7d 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/tools/tdd-coverage-analysis.md +++ b/.claude/skills/command-guide/reference/commands/workflow/tools/tdd-coverage-analysis.md @@ -275,7 +275,3 @@ Overall Compliance: 93/100 Detailed report: .workflow/WFS-auth/.process/tdd-cycle-report.md ``` -## Related Commands -- `/workflow:tdd-verify` - Uses this tool for verification -- `/workflow:tools:task-generate-tdd` - Generates tasks this tool analyzes -- `/workflow:execute` - Executes tasks before analysis diff --git a/.claude/skills/command-guide/reference/commands/workflow/tools/test-concept-enhanced.md b/.claude/skills/command-guide/reference/commands/workflow/tools/test-concept-enhanced.md index f6d40cd9..2fb173ee 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/tools/test-concept-enhanced.md +++ b/.claude/skills/command-guide/reference/commands/workflow/tools/test-concept-enhanced.md @@ -460,8 +460,3 @@ Synthesize Gemini analysis into standardized format: - โœ… Execution time < 20 minutes - โœ… Output follows existing test conventions -## Related Commands - -- `/workflow:tools:test-context-gather` - Provides input context -- `/workflow:tools:test-task-generate` - Consumes analysis results -- `/workflow:test-gen` - Main test generation workflow diff --git a/.claude/skills/command-guide/reference/commands/workflow/tools/test-context-gather.md b/.claude/skills/command-guide/reference/commands/workflow/tools/test-context-gather.md index 6bf9e48f..80e937c7 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/tools/test-context-gather.md +++ b/.claude/skills/command-guide/reference/commands/workflow/tools/test-context-gather.md @@ -203,8 +203,3 @@ Refer to `test-context-search-agent.md` Phase 3.2 for complete `test-context-pac - **Framework agnostic**: Supports Jest, Mocha, pytest, RSpec, Go testing, etc. - **Coverage focus**: Primary goal is identifying implementation files without tests -## Related Commands - -- `/workflow:test-gen` - Main test generation workflow -- `/workflow:tools:test-concept-enhanced` - Test generation analysis -- `/workflow:tools:test-task-generate` - Test task JSON generation diff --git a/.claude/skills/command-guide/reference/commands/workflow/tools/test-task-generate.md b/.claude/skills/command-guide/reference/commands/workflow/tools/test-task-generate.md index dc981ef6..d05d1d70 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/tools/test-task-generate.md +++ b/.claude/skills/command-guide/reference/commands/workflow/tools/test-task-generate.md @@ -1,6 +1,6 @@ --- name: test-task-generate -description: Generate test-fix task JSON with iterative test-fix-retest cycle specification using Gemini/Qwen/Codex +description: Autonomous test-fix task generation using action-planning-agent with test-fix-retest cycle specification and discovery phase argument-hint: "[--use-codex] [--cli-execute] --session WFS-test-session-id" examples: - /workflow:tools:test-task-generate --session WFS-test-auth @@ -9,10 +9,23 @@ examples: - /workflow:tools:test-task-generate --cli-execute --use-codex --session WFS-test-auth --- -# Test Task Generation Command +# Autonomous Test Task Generation Command ## Overview -Generate specialized test-fix task JSON with comprehensive test-fix-retest cycle specification, including Gemini diagnosis (using bug-fix template) and manual fix workflow (Codex automation only when explicitly requested). +Autonomous test-fix task JSON generation using action-planning-agent with two-phase execution: discovery and document generation. Supports both agent-driven execution (default) and CLI tool execution modes. Generates specialized test-fix tasks with comprehensive test-fix-retest cycle specification. + +## Core Philosophy +- **Agent-Driven**: Delegate execution to action-planning-agent for autonomous operation +- **Two-Phase Flow**: Discovery (context gathering) โ†’ Output (document generation) +- **Memory-First**: Reuse loaded documents from conversation memory +- **MCP-Enhanced**: Use MCP tools for advanced code analysis and test research +- **Pre-Selected Templates**: Command selects correct test template based on `--cli-execute` flag **before** invoking agent +- **Agent Simplicity**: Agent receives pre-selected template and focuses only on content generation +- **Path Clarity**: All `focus_paths` prefer absolute paths (e.g., `D:\\project\\src\\module`), or clear relative paths from project root +- **Test-First**: Generate comprehensive test coverage before execution +- **Iterative Refinement**: Test-fix-retest cycle until all tests pass +- **Surgical Fixes**: Minimal code changes, no refactoring during test fixes +- **Auto-Revert**: Rollback all changes if max iterations reached ## Execution Modes @@ -24,583 +37,278 @@ Generate specialized test-fix task JSON with comprehensive test-fix-retest cycle - **Manual Mode (Default)**: Gemini diagnosis โ†’ user applies fixes - **Codex Mode (`--use-codex`)**: Gemini diagnosis โ†’ Codex applies fixes with resume mechanism -## Core Philosophy -- **Analysis-Driven Test Generation**: Use TEST_ANALYSIS_RESULTS.md from test-concept-enhanced -- **Agent-Based Test Creation**: Call @code-developer agent for comprehensive test generation -- **Coverage-First**: Generate all missing tests before execution -- **Test Execution**: Execute complete test suite after generation -- **Gemini Diagnosis**: Use Gemini for root cause analysis and fix suggestions (references bug-fix template) -- **Manual Fixes First**: Apply fixes manually by default, codex only when explicitly needed -- **Iterative Refinement**: Repeat test-analyze-fix-retest cycle until all tests pass -- **Surgical Fixes**: Minimal code changes, no refactoring during test fixes -- **Auto-Revert**: Rollback all changes if max iterations reached - -## Core Responsibilities -- Parse TEST_ANALYSIS_RESULTS.md from test-concept-enhanced -- Extract test requirements and generation strategy -- Parse `--use-codex` flag to determine fix mode (manual vs automated) -- Generate test generation subtask calling @code-developer -- Generate test execution and fix cycle task JSON with appropriate fix mode -- Configure Gemini diagnosis workflow (bug-fix template) and manual/Codex fix application -- Create test-oriented IMPL_PLAN.md and TODO_LIST.md with test generation phase - ## Execution Lifecycle -### Phase 1: Input Validation & Discovery +### Phase 1: Discovery & Context Loading +**โšก Memory-First Rule**: Skip file loading if documents already in conversation memory -1. **Parameter Parsing** - - Parse `--use-codex` flag from command arguments โ†’ Controls IMPL-002 fix mode - - Parse `--cli-execute` flag from command arguments โ†’ Controls IMPL-001 generation mode - - Store flag values for task JSON generation - -2. **Test Session Validation** - - Load `.workflow/{test-session-id}/workflow-session.json` - - Verify `workflow_type: "test_session"` - - Extract `source_session_id` from metadata - -3. **Test Analysis Results Loading** - - **REQUIRED**: Load `.workflow/{test-session-id}/.process/TEST_ANALYSIS_RESULTS.md` - - Parse test requirements by file - - Extract test generation strategy - - Identify test files to create with specifications - -4. **Test Context Package Loading** - - Load `.workflow/{test-session-id}/.process/test-context-package.json` - - Extract test framework configuration - - Extract coverage gaps and priorities - - Load source session implementation summaries - -### Phase 2: Task JSON Generation - -Generate **TWO task JSON files**: -1. **IMPL-001.json** - Test Generation (calls @code-developer) -2. **IMPL-002.json** - Test Execution and Fix Cycle (calls @test-fix-agent) - -#### IMPL-001.json - Test Generation Task - -```json +**Agent Context Package**: +```javascript { - "id": "IMPL-001", - "title": "Generate comprehensive tests for [sourceSessionId]", - "status": "pending", - "meta": { - "type": "test-gen", - "agent": "@code-developer", - "source_session": "[sourceSessionId]", - "test_framework": "jest|pytest|cargo|detected" + "session_id": "WFS-test-[session-id]", + "execution_mode": "agent-mode" | "cli-execute-mode", // Determined by flag + "task_json_template_path": "~/.claude/workflows/cli-templates/prompts/workflow/task-json-agent-mode.txt" + | "~/.claude/workflows/cli-templates/prompts/workflow/task-json-cli-mode.txt", + // Path selected by command based on --cli-execute flag, agent reads it + "workflow_type": "test_session", + "use_codex": true | false, // Determined by --use-codex flag + "session_metadata": { + // If in memory: use cached content + // Else: Load from .workflow/{test-session-id}/workflow-session.json }, - "context": { - "requirements": [ - "Generate comprehensive test files based on TEST_ANALYSIS_RESULTS.md", - "Follow existing test patterns and conventions from test framework", - "Create tests for all missing coverage identified in analysis", - "Include happy path, error handling, edge cases, and integration tests", - "Use test data and mocks as specified in analysis", - "Ensure tests follow project coding standards" - ], - "focus_paths": [ - "tests/**/*", - "src/**/*.test.*", - "{paths_from_analysis}" - ], - "acceptance": [ - "All test files from TEST_ANALYSIS_RESULTS.md section 5 are created", - "Tests follow existing test patterns and conventions", - "Test scenarios cover happy path, errors, edge cases, integration", - "All dependencies are properly mocked", - "Test files are syntactically valid and can be executed", - "Test coverage meets analysis requirements" - ], - "depends_on": [], - "source_context": { - "session_id": "[sourceSessionId]", - "test_analysis": ".workflow/[testSessionId]/.process/TEST_ANALYSIS_RESULTS.md", - "test_context": ".workflow/[testSessionId]/.process/test-context-package.json", - "implementation_summaries": [ - ".workflow/[sourceSessionId]/.summaries/IMPL-001-summary.md" - ] - } + "test_analysis_results_path": ".workflow/{test-session-id}/.process/TEST_ANALYSIS_RESULTS.md", + "test_analysis_results": { + // If in memory: use cached content + // Else: Load from TEST_ANALYSIS_RESULTS.md }, - "flow_control": { - "pre_analysis": [ - { - "step": "load_test_analysis", - "action": "Load test generation requirements and strategy", - "commands": [ - "Read(.workflow/[testSessionId]/.process/TEST_ANALYSIS_RESULTS.md)", - "Read(.workflow/[testSessionId]/.process/test-context-package.json)" - ], - "output_to": "test_generation_requirements", - "on_error": "fail" - }, - { - "step": "load_implementation_context", - "action": "Load source implementation for test generation context", - "commands": [ - "bash(for f in .workflow/[sourceSessionId]/.summaries/IMPL-*-summary.md; do echo \"=== $(basename $f) ===\"&& cat \"$f\"; done)" - ], - "output_to": "implementation_context", - "on_error": "skip_optional" - }, - { - "step": "load_existing_test_patterns", - "action": "Study existing tests for pattern reference", - "commands": [ - "bash(find . -name \"*.test.*\" -type f)", - "bash(# Read first 2 existing test files as examples)", - "bash(test_files=$(find . -name \"*.test.*\" -type f | head -2))", - "bash(for f in $test_files; do echo \"=== $f ===\"&& cat \"$f\"; done)" - ], - "output_to": "existing_test_patterns", - "on_error": "skip_optional" - } - ], - // Agent Mode (Default): Agent implements tests - "implementation_approach": [ - { - "step": 1, - "title": "Generate comprehensive test suite", - "description": "Generate comprehensive test suite based on TEST_ANALYSIS_RESULTS.md. Follow test generation strategy and create all test files listed in section 5 (Implementation Targets).", - "modification_points": [ - "Read TEST_ANALYSIS_RESULTS.md sections 3 and 4", - "Study existing test patterns", - "Create test files with all required scenarios", - "Implement happy path, error handling, edge case, and integration tests", - "Add required mocks and fixtures" - ], - "logic_flow": [ - "Read TEST_ANALYSIS_RESULTS.md section 3 (Test Requirements by File)", - "Read TEST_ANALYSIS_RESULTS.md section 4 (Test Generation Strategy)", - "Study existing test patterns from test_context.test_framework.conventions", - "For each test file in section 5 (Implementation Targets): Create test file with specified scenarios, Implement happy path tests, Implement error handling tests, Implement edge case tests, Implement integration tests (if specified), Add required mocks and fixtures", - "Follow test framework conventions and project standards", - "Ensure all tests are executable and syntactically valid" - ], - "depends_on": [], - "output": "test_suite" - } - ], - - // CLI Execute Mode (--cli-execute): Use Codex command (alternative format shown below) - "implementation_approach": [{ - "step": 1, - "title": "Generate tests using Codex", - "description": "Use Codex CLI to autonomously generate comprehensive test suite based on TEST_ANALYSIS_RESULTS.md", - "modification_points": [ - "Codex loads TEST_ANALYSIS_RESULTS.md and existing test patterns", - "Codex generates all test files listed in analysis section 5", - "Codex ensures tests follow framework conventions" - ], - "logic_flow": [ - "Start new Codex session", - "Pass TEST_ANALYSIS_RESULTS.md to Codex", - "Codex studies existing test patterns", - "Codex generates comprehensive test suite", - "Codex validates test syntax and executability" - ], - "command": "bash(codex -C [focus_paths] --full-auto exec \"PURPOSE: Generate comprehensive test suite TASK: Create test files based on TEST_ANALYSIS_RESULTS.md section 5 MODE: write CONTEXT: @.workflow/WFS-test-[session]/.process/TEST_ANALYSIS_RESULTS.md @.workflow/WFS-test-[session]/.process/test-context-package.json EXPECTED: All test files with happy path, error handling, edge cases, integration tests RULES: Follow test framework conventions, ensure tests are executable\" --skip-git-repo-check -s danger-full-access)", - "depends_on": [], - "output": "test_generation" - }], - "target_files": [ - "{test_file_1 from TEST_ANALYSIS_RESULTS.md section 5}", - "{test_file_2 from TEST_ANALYSIS_RESULTS.md section 5}", - "{test_file_N from TEST_ANALYSIS_RESULTS.md section 5}" - ] + "test_context_package_path": ".workflow/{test-session-id}/.process/test-context-package.json", + "test_context_package": { + // Existing test patterns and coverage analysis + }, + "source_session_id": "[source-session-id]", // if exists + "source_session_summaries": { + // Implementation context from source session + }, + "mcp_capabilities": { + "code_index": true, + "exa_code": true, + "exa_web": true } } ``` -#### IMPL-002.json - Test Execution & Fix Cycle Task +**Discovery Actions**: +1. **Load Test Session Context** (if not in memory) + ```javascript + if (!memory.has("workflow-session.json")) { + Read(.workflow/{test-session-id}/workflow-session.json) + } + ``` -```json -{ - "id": "IMPL-002", - "title": "Execute and fix tests for [sourceSessionId]", - "status": "pending", - "meta": { - "type": "test-fix", - "agent": "@test-fix-agent", - "source_session": "[sourceSessionId]", - "test_framework": "jest|pytest|cargo|detected", - "max_iterations": 5, - "use_codex": false // Set to true if --use-codex flag present - }, - "context": { - "requirements": [ - "Execute complete test suite (generated in IMPL-001)", - "Diagnose test failures using Gemini analysis with bug-fix template", - "Present fixes to user for manual application (default)", - "Use Codex ONLY if user explicitly requests automation", - "Iterate until all tests pass or max iterations reached", - "Revert changes if unable to fix within iteration limit" - ], - "focus_paths": [ - "tests/**/*", - "src/**/*.test.*", - "{implementation_files_from_source_session}" - ], - "acceptance": [ - "All tests pass successfully (100% pass rate)", - "No test failures or errors in final run", - "Code changes are minimal and surgical", - "All fixes are verified through retest", - "Iteration logs document fix progression" - ], - "depends_on": ["IMPL-001"], - "source_context": { - "session_id": "[sourceSessionId]", - "test_generation_summary": ".workflow/[testSessionId]/.summaries/IMPL-001-summary.md", - "implementation_summaries": [ - ".workflow/[sourceSessionId]/.summaries/IMPL-001-summary.md" - ] - } - }, - "flow_control": { - "pre_analysis": [ - { - "step": "load_source_session_summaries", - "action": "Load implementation context from source session", - "commands": [ - "bash(find .workflow/[sourceSessionId]/.summaries/ -name 'IMPL-*-summary.md' 2>/dev/null)", - "bash(for f in .workflow/[sourceSessionId]/.summaries/IMPL-*-summary.md; do echo \"=== $(basename $f) ===\"&& cat \"$f\"; done)" - ], - "output_to": "implementation_context", - "on_error": "skip_optional" - }, - { - "step": "discover_test_framework", - "action": "Identify test framework and test command", - "commands": [ - "bash(jq -r '.scripts.test // \"npm test\"' package.json 2>/dev/null || echo 'pytest' || echo 'cargo test')", - "bash([ -f 'package.json' ] && echo 'jest/npm' || [ -f 'pytest.ini' ] && echo 'pytest' || [ -f 'Cargo.toml' ] && echo 'cargo' || echo 'unknown')" - ], - "output_to": "test_command", - "on_error": "fail" - }, - { - "step": "analyze_test_coverage", - "action": "Analyze test coverage and identify missing tests", - "commands": [ - "bash(find . -name \"*.test.*\" -type f)", - "bash(rg \"test|describe|it|def test_\" -g \"*.test.*\")", - "bash(# Count implementation files vs test files)", - "bash(impl_count=$(find [changed_files_dirs] -type f \\( -name '*.ts' -o -name '*.js' -o -name '*.py' \\) ! -name '*.test.*' 2>/dev/null | wc -l))", - "bash(test_count=$(find . -name \"*.test.*\" -type f | wc -l))", - "bash(echo \"Implementation files: $impl_count, Test files: $test_count\")" - ], - "output_to": "test_coverage_analysis", - "on_error": "skip_optional" - }, - { - "step": "identify_files_without_tests", - "action": "List implementation files that lack corresponding test files", - "commands": [ - "bash(# For each changed file from source session, check if test exists)", - "bash(for file in [changed_files]; do test_file=$(echo $file | sed 's/\\(.*\\)\\.\\(ts\\|js\\|py\\)$/\\1.test.\\2/'); [ ! -f \"$test_file\" ] && echo \"$file\"; done)" - ], - "output_to": "files_without_tests", - "on_error": "skip_optional" - }, - { - "step": "prepare_test_environment", - "action": "Ensure test environment is ready", - "commands": [ - "bash([ -f 'package.json' ] && npm install 2>/dev/null || true)", - "bash([ -f 'requirements.txt' ] && pip install -q -r requirements.txt 2>/dev/null || true)" - ], - "output_to": "environment_status", - "on_error": "skip_optional" - } - ], - "implementation_approach": [ - { - "step": 1, - "title": "Execute iterative test-fix-retest cycle", - "description": "Execute iterative test-fix-retest cycle using Gemini diagnosis (bug-fix template) and manual fixes (Codex only if meta.use_codex=true). Max 5 iterations with automatic revert on failure.", - "test_fix_cycle": { - "max_iterations": 5, - "cycle_pattern": "test โ†’ gemini_diagnose โ†’ manual_fix (or codex if needed) โ†’ retest", - "tools": { - "test_execution": "bash(test_command)", - "diagnosis": "gemini (MODE: analysis, uses bug-fix template)", - "fix_application": "manual (default) or codex exec resume --last (if explicitly needed)", - "verification": "bash(test_command) + regression_check" - }, - "exit_conditions": { - "success": "all_tests_pass", - "failure": "max_iterations_reached", - "error": "test_command_not_found" - } - }, - "modification_points": [ - "PHASE 1: Initial Test Execution", - " 1.1. Discover test command from framework detection", - " 1.2. Execute initial test run: bash([test_command])", - " 1.3. Parse test output and count failures", - " 1.4. If all pass โ†’ Skip to PHASE 3 (success)", - " 1.5. If failures โ†’ Store failure output, proceed to PHASE 2", - "", - "PHASE 2: Iterative Test-Fix-Retest Cycle (max 5 iterations)", - " Note: This phase handles test failures, NOT test generation failures", - " Initialize: max_iterations=5, current_iteration=0", - " ", - " WHILE (tests failing AND current_iteration < max_iterations):", - " current_iteration++", - " ", - " STEP 2.1: Gemini Diagnosis (using bug-fix template)", - " - Prepare diagnosis context:", - " * Test failure output from previous run", - " * Source files from focus_paths", - " * Implementation summaries from source session", - " - Execute Gemini analysis with bug-fix template:", - " bash(cd .workflow/WFS-test-[session]/.process && gemini \"", - " PURPOSE: Diagnose test failure iteration [N] and propose minimal fix", - " TASK: Systematic bug analysis and fix recommendations for test failure", - " MODE: analysis", - " CONTEXT: @CLAUDE.md,**/*CLAUDE.md", - " Test output: [test_failures]", - " Source files: [focus_paths]", - " Implementation: [implementation_context]", - " EXPECTED: Root cause analysis, code path tracing, targeted fixes", - " RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/01-diagnose-bug-root-cause.txt) | Bug: [test_failure_description]", - " Minimal surgical fixes only - no refactoring", - " \" > fix-iteration-[N]-diagnosis.md)", - " - Parse diagnosis โ†’ extract fix_suggestion and target_files", - " - Present fix to user for manual application (default)", - " ", - " STEP 2.2: Apply Fix (Based on meta.use_codex Flag)", - " ", - " IF meta.use_codex = false (DEFAULT):", - " - Present Gemini diagnosis to user for manual fix", - " - User applies fix based on diagnosis recommendations", - " - Stage changes: bash(git add -A)", - " - Store fix log: .process/fix-iteration-[N]-changes.log", - " ", - " IF meta.use_codex = true (--use-codex flag present):", - " - Stage current changes (if valid git repo): bash(git add -A)", - " - First iteration: Start new Codex session", - " codex -C [project_root] --full-auto exec \"", - " PURPOSE: Fix test failure iteration 1", - " TASK: [fix_suggestion from Gemini]", - " MODE: write", - " CONTEXT: Diagnosis: .workflow/.process/fix-iteration-1-diagnosis.md", - " Target files: [target_files]", - " Implementation context: [implementation_context]", - " EXPECTED: Minimal code changes to resolve test failure", - " RULES: Apply ONLY suggested changes, no refactoring", - " Preserve existing code style", - " \" --skip-git-repo-check -s danger-full-access", - " - Subsequent iterations: Resume session for context continuity", - " codex exec \"", - " CONTINUE TO NEXT FIX:", - " Iteration [N] of 5: Fix test failure", - " ", - " PURPOSE: Fix remaining test failures", - " TASK: [fix_suggestion from Gemini iteration N]", - " CONTEXT: Previous fixes applied, diagnosis: .process/fix-iteration-[N]-diagnosis.md", - " EXPECTED: Surgical fix for current failure", - " RULES: Build on previous fixes, maintain consistency", - " \" resume --last --skip-git-repo-check -s danger-full-access", - " - Store fix log: .process/fix-iteration-[N]-changes.log", - " ", - " STEP 2.3: Retest and Verification", - " - Re-execute test suite: bash([test_command])", - " - Capture output: .process/fix-iteration-[N]-retest.log", - " - Count failures: bash(grep -c 'FAIL\\|ERROR' .process/fix-iteration-[N]-retest.log)", - " - Check for regression:", - " IF new_failures > previous_failures:", - " WARN: Regression detected", - " Include in next Gemini diagnosis context", - " - Analyze results:", - " IF all_tests_pass:", - " BREAK loop โ†’ Proceed to PHASE 3", - " ELSE:", - " Update test_failures context", - " CONTINUE loop", - " ", - " IF max_iterations reached AND tests still failing:", - " EXECUTE: git reset --hard HEAD (revert all changes)", - " MARK: Task status = blocked", - " GENERATE: Detailed failure report with iteration logs", - " EXIT: Require manual intervention", - "", - "PHASE 3: Final Validation and Certification", - " 3.1. Execute final confirmation test run", - " 3.2. Generate success summary:", - " - Iterations required: [current_iteration]", - " - Fixes applied: [summary from iteration logs]", - " - Test results: All passing โœ…", - " 3.3. Mark task status: completed", - " 3.4. Update TODO_LIST.md: Mark as โœ…", - " 3.5. Certify code: APPROVED for deployment" - ], - "logic_flow": [ - "Load source session implementation context", - "Discover test framework and command", - "PHASE 0: Test Coverage Check", - " Analyze existing test files", - " Identify files without tests", - " IF tests missing:", - " Report to user (no automatic generation)", - " Wait for user to generate tests or request automation", - " ELSE:", - " Skip to Phase 1", - "PHASE 1: Initial Test Execution", - " Execute test suite", - " IF all pass โ†’ Success (Phase 3)", - " ELSE โ†’ Store failures, proceed to Phase 2", - "PHASE 2: Iterative Fix Cycle (max 5 iterations)", - " LOOP (max 5 times):", - " 1. Gemini diagnoses failure with bug-fix template โ†’ fix suggestion", - " 2. Check meta.use_codex flag:", - " - IF false (default): Present fix to user for manual application", - " - IF true (--use-codex): Codex applies fix with resume for continuity", - " 3. Retest and check results", - " 4. IF pass โ†’ Exit loop to Phase 3", - " 5. ELSE โ†’ Continue with updated context", - " IF max iterations โ†’ Revert + report failure", - "PHASE 3: Final Validation", - " Confirm all tests pass", - " Generate summary (include test generation info)", - " Certify code APPROVED" - ], - "error_handling": { - "max_iterations_reached": { - "action": "revert_all_changes", - "commands": [ - "bash(git reset --hard HEAD)", - "bash(jq '.status = \"blocked\"' .workflow/[session]/.task/IMPL-001.json > temp.json && mv temp.json .workflow/[session]/.task/IMPL-001.json)" - ], - "report": "Generate failure report with iteration logs in .summaries/IMPL-001-failure-report.md" - }, - "test_command_fails": { - "action": "treat_as_test_failure", - "context": "Use stderr as failure context for Gemini diagnosis" - }, - "codex_apply_fails": { - "action": "retry_once_then_skip", - "fallback": "Mark iteration as skipped, continue to next" - }, - "gemini_diagnosis_fails": { - "action": "retry_with_simplified_context", - "fallback": "Use previous diagnosis, continue" - }, - "regression_detected": { - "action": "log_warning_continue", - "context": "Include regression info in next Gemini diagnosis" - } - }, - "depends_on": [], - "output": "test_fix_results" - } - ], - "target_files": [ - "Auto-discovered from test failures", - "Extracted from Gemini diagnosis each iteration", - "Format: file:function:lines or file (for new files)" - ], - "codex_session": { - "strategy": "resume_for_continuity", - "first_iteration": "codex exec \"fix iteration 1\" --full-auto", - "subsequent_iterations": "codex exec \"fix iteration N\" resume --last", - "benefits": [ - "Maintains conversation context across fixes", - "Remembers previous decisions and patterns", - "Ensures consistency in fix approach", - "Reduces redundant context injection" - ] - } - } +2. **Load TEST_ANALYSIS_RESULTS.md** (if not in memory, REQUIRED) + ```javascript + if (!memory.has("TEST_ANALYSIS_RESULTS.md")) { + Read(.workflow/{test-session-id}/.process/TEST_ANALYSIS_RESULTS.md) + } + ``` + +3. **Load Test Context Package** (if not in memory) + ```javascript + if (!memory.has("test-context-package.json")) { + Read(.workflow/{test-session-id}/.process/test-context-package.json) + } + ``` + +4. **Load Source Session Summaries** (if source_session_id exists) + ```javascript + if (sessionMetadata.source_session_id) { + const summaryFiles = Bash("find .workflow/{source-session-id}/.summaries/ -name 'IMPL-*-summary.md'") + summaryFiles.forEach(file => Read(file)) + } + ``` + +5. **Code Analysis with Native Tools** (optional - enhance understanding) + ```bash + # Find test files and patterns + find . -name "*test*" -type f + rg "describe|it\(|test\(" -g "*.ts" + ``` + +6. **MCP External Research** (optional - gather test best practices) + ```javascript + // Get external test examples and patterns + mcp__exa__get_code_context_exa( + query="TypeScript test generation best practices jest", + tokensNum="dynamic" + ) + ``` + +### Phase 2: Agent Execution (Document Generation) + +**Pre-Agent Template Selection** (Command decides path before invoking agent): +```javascript +// Command checks flag and selects template PATH (not content) +const templatePath = hasCliExecuteFlag + ? "~/.claude/workflows/cli-templates/prompts/workflow/task-json-cli-mode.txt" + : "~/.claude/workflows/cli-templates/prompts/workflow/task-json-agent-mode.txt"; +``` + +**Agent Invocation**: +```javascript +Task( + subagent_type="action-planning-agent", + description="Generate test-fix task JSON and implementation plan", + prompt=` +## Execution Context + +**Session ID**: WFS-test-{session-id} +**Workflow Type**: Test Session +**Execution Mode**: {agent-mode | cli-execute-mode} +**Task JSON Template Path**: {template_path} +**Use Codex**: {true | false} + +## Phase 1: Discovery Results (Provided Context) + +### Test Session Metadata +{session_metadata_content} +- source_session_id: {source_session_id} (if exists) +- workflow_type: "test_session" + +### TEST_ANALYSIS_RESULTS.md (REQUIRED) +{test_analysis_results_content} +- Coverage Assessment +- Test Framework & Conventions +- Test Requirements by File +- Test Generation Strategy +- Implementation Targets +- Success Criteria + +### Test Context Package +{test_context_package_summary} +- Existing test patterns, framework config, coverage analysis + +### Source Session Implementation Context (Optional) +{source_session_summaries} +- Implementation context from completed session + +### MCP Analysis Results (Optional) +**Code Structure**: {mcp_code_index_results} +**External Research**: {mcp_exa_research_results} + +## Phase 2: Test Task Document Generation + +**Agent Configuration Reference**: All test task generation rules, test-fix cycle structure, quality standards, and execution details are defined in action-planning-agent. + +Refer to: @.claude/agents/action-planning-agent.md for: +- Test Task Decomposition Standards +- Test-Fix-Retest Cycle Requirements +- 5-Field Task JSON Schema +- IMPL_PLAN.md Structure (Test variant) +- TODO_LIST.md Format +- Test Execution Flow & Quality Validation + +### Test-Specific Requirements Summary + +#### Task Structure Philosophy +- **Minimum 2 tasks**: IMPL-001 (test generation) + IMPL-002 (test execution & fix) +- **Expandable**: Add IMPL-003+ for complex projects (per-module, integration, etc.) +- IMPL-001: Uses @code-developer or CLI execution +- IMPL-002: Uses @test-fix-agent with iterative fix cycle + +#### Test-Fix Cycle Configuration +- **Max Iterations**: 5 (for IMPL-002) +- **Diagnosis Tool**: Gemini with bug-fix template +- **Fix Application**: Manual (default) or Codex (if --use-codex flag) +- **Cycle Pattern**: test โ†’ gemini_diagnose โ†’ manual_fix (or codex) โ†’ retest +- **Exit Conditions**: All tests pass OR max iterations reached (auto-revert) + +#### Required Outputs Summary + +##### 1. Test Task JSON Files (.task/IMPL-*.json) +- **Location**: `.workflow/{test-session-id}/.task/` +- **Template**: Read from `{template_path}` (pre-selected by command based on `--cli-execute` flag) +- **Schema**: 5-field structure with test-specific metadata + - IMPL-001: `meta.type: "test-gen"`, `meta.agent: "@code-developer"` + - IMPL-002: `meta.type: "test-fix"`, `meta.agent: "@test-fix-agent"`, `meta.use_codex: {use_codex}` + - `flow_control`: Test generation approach (IMPL-001) or test-fix cycle (IMPL-002) +- **Details**: See action-planning-agent.md ยง Test Task JSON Generation + +##### 2. IMPL_PLAN.md (Test Variant) +- **Location**: `.workflow/{test-session-id}/IMPL_PLAN.md` +- **Template**: `~/.claude/workflows/cli-templates/prompts/workflow/impl-plan-template.txt` +- **Test-Specific Frontmatter**: workflow_type="test_session", test_framework, source_session_id +- **Test-Fix-Retest Cycle Section**: Iterative fix cycle with Gemini diagnosis +- **Details**: See action-planning-agent.md ยง Test Implementation Plan Creation + +##### 3. TODO_LIST.md +- **Location**: `.workflow/{test-session-id}/TODO_LIST.md` +- **Format**: Task list with test generation and execution phases +- **Status**: [ ] (pending), [x] (completed) +- **Details**: See action-planning-agent.md ยง TODO List Generation + +### Agent Execution Summary + +**Key Steps** (Detailed instructions in action-planning-agent.md): +1. Load task JSON template from provided path +2. Parse TEST_ANALYSIS_RESULTS.md for test requirements +3. Generate IMPL-001 (test generation) task JSON +4. Generate IMPL-002 (test execution & fix) task JSON with use_codex flag +5. Generate additional IMPL-*.json if project complexity requires +6. Create IMPL_PLAN.md using test template variant +7. Generate TODO_LIST.md with test task indicators +8. Update session state with test metadata + +**Quality Gates** (Full checklist in action-planning-agent.md): +- โœ“ Minimum 2 tasks created (IMPL-001 + IMPL-002) +- โœ“ IMPL-001 has test generation approach from TEST_ANALYSIS_RESULTS.md +- โœ“ IMPL-002 has test-fix cycle with correct use_codex flag +- โœ“ Test framework configuration integrated +- โœ“ Source session context referenced (if exists) +- โœ“ MCP tool integration added +- โœ“ Documents follow test template structure + +## Output + +Generate all three documents and report completion status: +- Test task JSON files created: N files (minimum 2) +- Test requirements integrated: TEST_ANALYSIS_RESULTS.md +- Test context integrated: existing patterns and coverage +- Source session context: {source_session_id} summaries (if exists) +- MCP enhancements: code-index, exa-research +- Session ready for test execution: /workflow:execute or /workflow:test-cycle-execute +` +) +``` + +### Agent Context Passing + +**Memory-Aware Context Assembly**: +```javascript +// Assemble context package for agent +const agentContext = { + session_id: "WFS-test-[id]", + workflow_type: "test_session", + use_codex: hasUseCodexFlag, + + // Use memory if available, else load + session_metadata: memory.has("workflow-session.json") + ? memory.get("workflow-session.json") + : Read(.workflow/WFS-test-[id]/workflow-session.json), + + test_analysis_results_path: ".workflow/WFS-test-[id]/.process/TEST_ANALYSIS_RESULTS.md", + + test_analysis_results: memory.has("TEST_ANALYSIS_RESULTS.md") + ? memory.get("TEST_ANALYSIS_RESULTS.md") + : Read(".workflow/WFS-test-[id]/.process/TEST_ANALYSIS_RESULTS.md"), + + test_context_package_path: ".workflow/WFS-test-[id]/.process/test-context-package.json", + + test_context_package: memory.has("test-context-package.json") + ? memory.get("test-context-package.json") + : Read(".workflow/WFS-test-[id]/.process/test-context-package.json"), + + // Load source session summaries if exists + source_session_id: session_metadata.source_session_id || null, + + source_session_summaries: session_metadata.source_session_id + ? loadSourceSummaries(session_metadata.source_session_id) + : null, + + // Optional MCP enhancements + mcp_analysis: executeMcpDiscovery() } ``` -### Phase 3: IMPL_PLAN.md Generation +## Test Task Structure Reference -#### Document Structure -```markdown ---- -identifier: WFS-test-[session-id] -source_session: WFS-[source-session-id] -workflow_type: test_session -test_framework: jest|pytest|cargo|detected ---- +This section provides quick reference for test task JSON structure. For complete implementation details, see the agent invocation prompt in Phase 2 above. -# Test Validation Plan: [Source Session Topic] - -## Summary -Execute comprehensive test suite for implementation from session WFS-[source-session-id]. -Diagnose and fix all test failures using iterative Gemini analysis and Codex execution. - -## Source Session Context -- **Implementation Session**: WFS-[source-session-id] -- **Completed Tasks**: IMPL-001, IMPL-002, ... -- **Changed Files**: [list from git log] -- **Implementation Summaries**: [references to source session summaries] - -## Test Framework -- **Detected Framework**: jest|pytest|cargo|other -- **Test Command**: npm test|pytest|cargo test -- **Test Files**: [discovered test files] -- **Coverage**: [estimated test coverage] - -## Test-Fix-Retest Cycle -- **Max Iterations**: 5 -- **Diagnosis Tool**: Gemini (analysis mode with bug-fix template from bug-index.md) -- **Fix Tool**: Manual (default, meta.use_codex=false) or Codex (if --use-codex flag, meta.use_codex=true) -- **Verification**: Bash test execution + regression check - -### Cycle Workflow -1. **Initial Test**: Execute full suite, capture failures -2. **Iterative Fix Loop** (max 5 times): - - Gemini diagnoses failure using bug-fix template โ†’ surgical fix suggestion - - Check meta.use_codex flag: - - If false (default): Present fix to user for manual application - - If true (--use-codex): Codex applies fix with resume for context continuity - - Retest and verify (check for regressions) - - Continue until all pass or max iterations reached -3. **Final Validation**: Confirm all tests pass, certify code - -### Error Recovery -- **Max iterations reached**: Revert all changes, report failure -- **Test command fails**: Treat as test failure, diagnose with Gemini -- **Codex fails**: Retry once, skip iteration if still failing -- **Regression detected**: Log warning, include in next diagnosis - -## Task Breakdown -- **IMPL-001**: Execute and validate tests with iterative fix cycle - -## Implementation Strategy -- **Phase 1**: Initial test execution and failure capture -- **Phase 2**: Iterative Gemini diagnosis + Codex fix + retest -- **Phase 3**: Final validation and code certification - -## Success Criteria -- All tests pass (100% pass rate) -- No test failures or errors in final run -- Minimal, surgical code changes -- Iteration logs document fix progression -- Code certified APPROVED for deployment -``` - -### Phase 4: TODO_LIST.md Generation - -```markdown -# Tasks: Test Validation for [Source Session] - -## Task Progress -- [ ] **IMPL-001**: Execute and validate tests with iterative fix cycle โ†’ [๐Ÿ“‹](./.task/IMPL-001.json) - -## Execution Details -- **Source Session**: WFS-[source-session-id] -- **Test Framework**: jest|pytest|cargo -- **Max Iterations**: 5 -- **Tools**: Gemini diagnosis + Codex resume fixes - -## Status Legend -- `- [ ]` = Pending -- `- [x]` = Completed -``` +**Quick Reference**: +- Minimum 2 tasks: IMPL-001 (test-gen) + IMPL-002 (test-fix) +- Expandable for complex projects (IMPL-003+) +- IMPL-001: `meta.agent: "@code-developer"`, test generation approach +- IMPL-002: `meta.agent: "@test-fix-agent"`, `meta.use_codex: {flag}`, test-fix cycle +- See Phase 2 agent prompt for full schema and requirements ## Output Files Structure ``` @@ -648,29 +356,42 @@ Diagnose and fix all test failures using iterative Gemini analysis and Codex exe ## Integration & Usage ### Command Chain -- **Called By**: `/workflow:test-gen` (Phase 4) -- **Calls**: None (terminal command) -- **Followed By**: `/workflow:execute` (user-triggered) +- **Called By**: `/workflow:test-gen` (Phase 4), `/workflow:test-fix-gen` (Phase 4) +- **Invokes**: `action-planning-agent` for autonomous task generation +- **Followed By**: `/workflow:execute` or `/workflow:test-cycle-execute` (user-triggered) ### Basic Usage ```bash -# Manual fix mode (default) +# Agent mode (default, autonomous execution) /workflow:tools:test-task-generate --session WFS-test-auth -# Automated Codex fix mode +# With automated Codex fixes for IMPL-002 /workflow:tools:test-task-generate --use-codex --session WFS-test-auth + +# CLI execution mode for IMPL-001 test generation +/workflow:tools:test-task-generate --cli-execute --session WFS-test-auth + +# Both flags combined +/workflow:tools:test-task-generate --cli-execute --use-codex --session WFS-test-auth ``` -### Flag Behavior -- **No flag**: `meta.use_codex=false`, manual fixes presented to user -- **--use-codex**: `meta.use_codex=true`, Codex automatically applies fixes with resume mechanism +### Execution Modes +- **Agent mode** (default): Uses `action-planning-agent` with agent-mode task template +- **CLI mode** (`--cli-execute`): Uses Gemini/Qwen/Codex with cli-mode task template for IMPL-001 +- **Codex fixes** (`--use-codex`): Enables automated fixes in IMPL-002 task -## Related Commands -- `/workflow:test-gen` - Creates test session and calls this tool -- `/workflow:tools:context-gather` - Provides cross-session context -- `/workflow:tools:concept-enhanced` - Provides test strategy analysis -- `/workflow:execute` - Executes the generated test-fix task -- `@test-fix-agent` - Agent that executes the iterative test-fix cycle +### Flag Behavior +- **No flags**: `meta.use_codex=false` (manual fixes), agent-mode generation +- **--use-codex**: `meta.use_codex=true` (Codex automated fixes with resume mechanism in IMPL-002) +- **--cli-execute**: Uses CLI tool execution mode for IMPL-001 test generation +- **Both flags**: CLI generation + automated Codex fixes + +### Output +- Test task JSON files in `.task/` directory (minimum 2: IMPL-001.json + IMPL-002.json) +- IMPL_PLAN.md with test generation and fix cycle strategy +- TODO_LIST.md with test task indicators +- Session state updated with test metadata +- MCP enhancements integrated (if available) ## Agent Execution Notes 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 1b2217a6..75d6a343 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 @@ -50,8 +50,10 @@ IF --focus: ELSE: focus_types = ["all"] # Extract all animation types -# Determine base path -bash(find .workflow -type d -name "design-*" | head -1) # Auto-detect +# Determine base path (auto-detect and convert to absolute) +relative_path=$(find .workflow -type d -name "design-run-*" | head -1) +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 ``` @@ -777,7 +779,7 @@ Next: Animation tokens ready for integration ```bash # Find design directory -bash(find .workflow -type d -name "design-*" | head -1) +bash(find .workflow -type d -name "design-run-*" | head -1) # Create output directories bash(mkdir -p {base_path}/animation-extraction) diff --git a/.claude/skills/command-guide/reference/commands/workflow/ui-design/batch-generate.md b/.claude/skills/command-guide/reference/commands/workflow/ui-design/batch-generate.md index aa1db36f..2122493a 100644 --- a/.claude/skills/command-guide/reference/commands/workflow/ui-design/batch-generate.md +++ b/.claude/skills/command-guide/reference/commands/workflow/ui-design/batch-generate.md @@ -42,9 +42,14 @@ target_type = --target-type OR detect_target_type(target_list) IF --base-path: base_path = --base-path ELSE IF --session: - bash(find .workflow/WFS-{session} -type d -name "design-*" -printf "%T@ %p\n" | sort -nr | head -1 | cut -d' ' -f2) + relative_path=$(find .workflow/WFS-{session} -type d -name "design-run-*" -printf "%T@ %p\n" | sort -nr | head -1 | cut -d' ' -f2) + base_path=$(cd "$relative_path" && pwd) ELSE: - bash(find .workflow -type d -name "design-*" -printf "%T@ %p\n" | sort -nr | head -1 | cut -d' ' -f2) + relative_path=$(find .workflow -type d -name "design-run-*" -printf "%T@ %p\n" | sort -nr | head -1 | cut -d' ' -f2) + base_path=$(cd "$relative_path" && pwd) + +# Verify absolute path +bash(test -d "$base_path" && echo "โœ“ Base path: $base_path" || echo "โœ— Path not found") # Get variant counts style_variants = --style-variants OR bash(ls {base_path}/style-extraction/style-* -d | wc -l) @@ -65,31 +70,24 @@ IF exists({base_path}/.intermediates/style-analysis/design-space-analysis.json): **Output**: `design_tokens_valid`, `design_space_analysis` -### Step 3: Gather Layout Inspiration (Reuse or Create) +### Step 3: Gather Layout Inspiration (Direct MCP Search) ```bash -# Check if layout inspirations already exist from layout-extract phase -inspiration_source = "{base_path}/.intermediates/layout-analysis/inspirations" +# Gather layout inspiration via MCP for each target +layout_inspiration_map = {} FOR target IN target_list: - # Priority 1: Reuse existing inspiration from layout-extract - IF exists({inspiration_source}/{target}-layout-ideas.txt): - # Reuse existing inspiration (no action needed) - REPORT: "Using existing layout inspiration for {target}" - ELSE: - # Priority 2: Generate new inspiration via MCP - bash(mkdir -p {inspiration_source}) - search_query = "{target} {target_type} layout patterns variations" - mcp__exa__web_search_exa(query=search_query, numResults=5) + search_query = "{target} {target_type} layout patterns variations" + search_results = mcp__exa__web_search_exa(query=search_query, numResults=5) - # Extract context from prompt for this target - target_requirements = extract_relevant_context_from_prompt(prompt_text, target) + # Extract context from prompt for this target + target_requirements = extract_relevant_context_from_prompt(prompt_text, target) - # Write inspiration file to centralized location - Write({inspiration_source}/{target}-layout-ideas.txt, inspiration_content) - REPORT: "Created new layout inspiration for {target}" + # Store inspiration in memory (no file write needed) + layout_inspiration_map[target] = format_inspiration_from_search(search_results, target_requirements) + REPORT: "Gathered layout inspiration for {target}" ``` -**Output**: `T` inspiration text files (reused or created in `.intermediates/layout-analysis/inspirations/`) +**Output**: `layout_inspiration_map` (in-memory, passed to agents) ## Phase 2: Target-Style-Centric Batch Generation (Agent) @@ -127,7 +125,7 @@ Task(ui-design-agent): ` ${design_attributes ? "DESIGN_ATTRIBUTES: " + JSON.stringify(design_attributes) : ""} ## Reference - - Layout inspiration: Read("{base_path}/.intermediates/layout-analysis/inspirations/{target}-layout-ideas.txt") + - Layout inspiration: {layout_inspiration_map[target]} - Design tokens: Read("{base_path}/style-extraction/style-{style_id}/design-tokens.json") Parse ALL token values including: * colors, typography (with combinations), spacing, opacity @@ -274,7 +272,7 @@ Next: /workflow:ui-design:update ### Path Operations ```bash # Find design directory -bash(find .workflow -type d -name "design-*" -printf "%T@ %p\n" | sort -nr | head -1 | cut -d' ' -f2) +bash(find .workflow -type d -name "design-run-*" -printf "%T@ %p\n" | sort -nr | head -1 | cut -d' ' -f2) # Count style variants bash(ls {base_path}/style-extraction/style-* -d | wc -l) @@ -310,8 +308,6 @@ bash(~/.claude/scripts/ui-generate-preview.sh "{base_path}/prototypes") {base_path}/ โ”œโ”€โ”€ .intermediates/ โ”‚ โ””โ”€โ”€ layout-analysis/ -โ”‚ โ””โ”€โ”€ inspirations/ -โ”‚ โ””โ”€โ”€ {target}-layout-ideas.txt # Layout inspiration (reused or created) โ”œโ”€โ”€ prototypes/ โ”‚ โ”œโ”€โ”€ {target}-style-{s}-layout-{l}.html # Final prototypes โ”‚ โ”œโ”€โ”€ {target}-style-{s}-layout-{l}.css 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 7b498afa..f1fa7b0b 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 @@ -18,16 +18,18 @@ Batch screenshot tool with MCP-first strategy and multi-tier fallback. Processes ### Step 1: Determine Base Path ```bash # Priority: --base-path > session > standalone -bash(if [ -n "$BASE_PATH" ]; then +relative_path=$(if [ -n "$BASE_PATH" ]; then echo "$BASE_PATH" elif [ -n "$SESSION_ID" ]; then find .workflow/WFS-$SESSION_ID/design-* -type d | head -1 || \ - echo ".workflow/WFS-$SESSION_ID/design-run-$(date +%Y%m%d-%H%M%S)" + echo ".workflow/WFS-$SESSION_ID/design-run-$(date +%Y%m%d)-$RANDOM" else - echo ".workflow/.design/run-$(date +%Y%m%d-%H%M%S)" + echo ".workflow/.design/design-run-$(date +%Y%m%d)-$RANDOM" fi) -bash(mkdir -p $BASE_PATH/screenshots) +# Create directory and convert to absolute path +bash(mkdir -p "$relative_path"/screenshots) +base_path=$(cd "$relative_path" && pwd) ``` ### Step 2: Parse URL Map @@ -187,7 +189,7 @@ bash($chrome --headless --screenshot="$output_file" --window-size=1920,1080 "$ur Failed URLs: home: https://linear.app - Save to: .workflow/.design/run-20250110/screenshots/home.png + Save to: .workflow/.design/design-run-20250110/screenshots/home.png Steps: 1. Visit URL in browser @@ -270,7 +272,7 @@ Next: /workflow:ui-design:extract --images "screenshots/*.png" ### Path Operations ```bash # Find design directory -bash(find .workflow -type d -name "design-*" | head -1) +bash(find .workflow -type d -name "design-run-*" | head -1) # Create screenshot directory bash(mkdir -p $BASE_PATH/screenshots) 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 c843913f..e75bbc2a 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 @@ -203,10 +203,13 @@ STORE: device_type, device_source ### Phase 0b: Run Initialization & Directory Setup ```bash -run_id = "run-$(date +%Y%m%d-%H%M%S)" -base_path = --session ? ".workflow/WFS-{session}/design-${run_id}" : ".workflow/.design/${run_id}" +run_id = "run-$(date +%Y%m%d)-$RANDOM" +relative_base_path = --session ? ".workflow/WFS-{session}/design-${run_id}" : ".workflow/.design/design-${run_id}" -Bash(mkdir -p "${base_path}/{style-extraction,style-consolidation,prototypes}") +# Create directory and convert to absolute path +Bash(mkdir -p "${relative_base_path}/style-extraction") +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": "...", @@ -313,7 +316,8 @@ IF design_source IN ["code_only", "hybrid"]: # Check file existence and assess completeness style_exists = exists("{base_path}/style-extraction/style-1/design-tokens.json") animation_exists = exists("{base_path}/animation-extraction/animation-tokens.json") - layout_exists = exists("{base_path}/layout-extraction/layout-templates.json") + layout_count = bash(ls {base_path}/layout-extraction/layout-*.json 2>/dev/null | wc -l) + layout_exists = (layout_count > 0) style_complete = false animation_complete = false @@ -349,14 +353,16 @@ IF design_source IN ["code_only", "hybrid"]: # Layout completeness check IF layout_exists: - layouts = Read("{base_path}/layout-extraction/layout-templates.json") + # Read first layout file to verify structure + first_layout = bash(ls {base_path}/layout-extraction/layout-*.json 2>/dev/null | head -1) + layout_data = Read(first_layout) layout_complete = ( - layouts.layout_templates?.length >= 3 && - layouts.extraction_metadata?.layout_system?.type && - layouts.extraction_metadata?.responsive?.breakpoints + layout_count >= 1 && + layout_data.template?.dom_structure && + layout_data.template?.css_layout_rules ) - IF NOT layout_complete AND layouts.extraction_metadata?.completeness?.missing_items: - missing_categories.extend(layouts.extraction_metadata.completeness.missing_items) + IF NOT layout_complete: + missing_categories.push("complete layout structure") ELSE: missing_categories.push("layout templates") @@ -384,7 +390,7 @@ IF design_source == "visual_only" OR needs_visual_supplement: command = "/workflow:ui-design:style-extract --base-path \"{base_path}\" " + (--images ? "--images \"{images}\" " : "") + (--prompt ? "--prompt \"{prompt}\" " : "") + - "--mode explore --variants {style_variants}" + "--variants {style_variants}" SlashCommand(command) ELSE: REPORT: "โœ… Phase 1: Style (Using Code Import)" @@ -413,7 +419,7 @@ IF (design_source == "visual_only" OR needs_visual_supplement) OR (NOT layout_co command = "/workflow:ui-design:layout-extract --base-path \"{base_path}\" " + (--images ? "--images \"{images}\" " : "") + (--prompt ? "--prompt \"{prompt}\" " : "") + - "--targets \"{targets_string}\" --mode explore --variants {layout_variants} --device-type \"{device_type}\"" + "--targets \"{targets_string}\" --variants {layout_variants} --device-type \"{device_type}\"" SlashCommand(command) ELSE: REPORT: "โœ… Phase 2.5: Layout (Using Code Import)" @@ -547,10 +553,11 @@ 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) -Phase 2: {nร—l} layout templates (layout-extract explore mode) +Phase 1: {s} complete design systems (style-extract with multi-select) +Phase 2: {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) - Pure assembly: layout templates + design tokens - {s}ร—{l}ร—{n} = {total} final prototypes @@ -560,21 +567,22 @@ Phase 4: Brainstorming artifacts updated Assembly Process: โœ… Separation of Concerns: Layout (structure) + Style (tokens) kept separate โœ… Layout Extraction: {nร—l} reusable structural templates +โœ… Multi-Selection Workflow: User selects multiple variants from generated options โœ… Pure Assembly: No design decisions in generate phase โœ… Device-Optimized: Layouts designed for {device_type} Design Quality: โœ… Token-Driven Styling: 100% var() usage -โœ… Structural Variety: {l} distinct layouts per target -โœ… Style Variety: {s} independent design systems +โœ… Structural Variety: {l} distinct layouts per target (user-selected) +โœ… Style Variety: {s} independent design systems (user-selected) โœ… Device-Optimized: Layouts designed for {device_type} ๐Ÿ“‚ {base_path}/ โ”œโ”€โ”€ .intermediates/ (Intermediate analysis files) โ”‚ โ”œโ”€โ”€ style-analysis/ (computed-styles.json, design-space-analysis.json) - โ”‚ โ””โ”€โ”€ layout-analysis/ (dom-structure-*.json, inspirations/*.txt) + โ”‚ โ””โ”€โ”€ layout-analysis/ (analysis-options.json, user-selection.json, dom-structure-*.json) โ”œโ”€โ”€ style-extraction/ ({s} complete design systems) - โ”œโ”€โ”€ layout-extraction/ ({nร—l} layout templates + layout-space-analysis.json) + โ”œโ”€โ”€ 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 1a334c45..bd09b03c 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 @@ -38,17 +38,21 @@ IF depth NOT IN [1, 2, 3, 4, 5]: ### Step 2: Determine Base Path ```bash -bash(if [ -n "$BASE_PATH" ]; then +relative_path=$(if [ -n "$BASE_PATH" ]; then echo "$BASE_PATH" elif [ -n "$SESSION_ID" ]; then find .workflow/WFS-$SESSION_ID/design-* -type d | head -1 || \ - echo ".workflow/WFS-$SESSION_ID/design-layers-$(date +%Y%m%d-%H%M%S)" + echo ".workflow/WFS-$SESSION_ID/design-run-$(date +%Y%m%d)-$RANDOM" else - echo ".workflow/.design/layers-$(date +%Y%m%d-%H%M%S)" + echo ".workflow/.design/design-run-$(date +%Y%m%d)-$RANDOM" fi) +# Create directory structure and convert to absolute path +bash(mkdir -p "$relative_path") +base_path=$(cd "$relative_path" && pwd) + # Create depth directories -bash(for i in $(seq 1 $depth); do mkdir -p $BASE_PATH/screenshots/depth-$i; done) +bash(for i in $(seq 1 $depth); do mkdir -p "$base_path"/screenshots/depth-$i; done) ``` **Output**: `url`, `depth`, `base_path` 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 992c997e..1a603157 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 @@ -25,11 +25,17 @@ Pure assembler that combines pre-extracted layout templates with design tokens t ### Step 1: Resolve Base Path & Parse Configuration ```bash -# Determine working directory -bash(find .workflow -type d -name "design-*" | head -1) # Auto-detect +# Determine working directory (relative path) +relative_path=$(find .workflow -type d -name "design-run-*" | head -1) + +# 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") # Get style count -bash(ls {base_path}/style-extraction/style-* -d | wc -l) +bash(ls "$base_path"/style-extraction/style-* -d | wc -l) # Image reference auto-detected from layout template source_image_path ``` @@ -263,7 +269,7 @@ Next: /workflow:ui-design:update ### Path Operations ```bash # Find design directory -bash(find .workflow -type d -name "design-*" | head -1) +bash(find .workflow -type d -name "design-run-*" | head -1) # Count style variants bash(ls {base_path}/style-extraction/style-* -d | wc -l) 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 58184913..6a63f65a 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 @@ -100,20 +100,21 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*) ```bash # Generate run ID -run_id = "run-$(date +%Y%m%d-%H%M%S)" +run_id = "run-$(date +%Y%m%d)-$RANDOM" # Determine base path and session mode IF --session: session_id = {provided_session} - base_path = ".workflow/WFS-{session_id}/design-{run_id}" + relative_base_path = ".workflow/WFS-{session_id}/design-{run_id}" session_mode = "integrated" ELSE: session_id = null - base_path = ".workflow/.design/{run_id}" + relative_base_path = ".workflow/.design/design-{run_id}" session_mode = "standalone" -# Create base directory -Bash(mkdir -p "{base_path}") +# 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 @@ -224,8 +225,8 @@ 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}\" " + - "--base-path \"{code_base_path}\"" + command = "/workflow:ui-design:import-from-code --output-path \"{base_path}\" " + + "--source-path \"{code_base_path}\"" TRY: SlashCommand(command) @@ -238,7 +239,8 @@ IF design_source == "hybrid": # Check file existence and assess completeness style_exists = exists("{base_path}/style-extraction/style-1/design-tokens.json") animation_exists = exists("{base_path}/animation-extraction/animation-tokens.json") - layout_exists = exists("{base_path}/layout-extraction/layout-templates.json") + layout_count = bash(ls {base_path}/layout-extraction/layout-*.json 2>/dev/null | wc -l) + layout_exists = (layout_count > 0) style_complete = false animation_complete = false @@ -274,14 +276,16 @@ IF design_source == "hybrid": # Layout completeness check IF layout_exists: - layouts = Read("{base_path}/layout-extraction/layout-templates.json") + # Read first layout file to verify structure + first_layout = bash(ls {base_path}/layout-extraction/layout-*.json 2>/dev/null | head -1) + layout_data = Read(first_layout) layout_complete = ( - layouts.layout_templates?.length >= 3 && - layouts.extraction_metadata?.layout_system?.type && - layouts.extraction_metadata?.responsive?.breakpoints + layout_count >= 1 && + layout_data.template?.dom_structure && + layout_data.template?.css_layout_rules ) - IF NOT layout_complete AND layouts.extraction_metadata?.completeness?.missing_items: - missing_categories.extend(layouts.extraction_metadata.completeness.missing_items) + IF NOT layout_complete: + missing_categories.push("complete layout structure") ELSE: missing_categories.push("layout templates") @@ -404,7 +408,7 @@ ELSE: extraction_prompt = f"Extract visual style tokens from '{primary_target}' with consistency across all pages." 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}\" --mode imitate" + 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" SlashCommand(extract_command) TodoWrite(mark_completed: "Extract style", mark_in_progress: "Extract animation") @@ -435,7 +439,7 @@ IF skip_layout: 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)}\" --mode imitate" + 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" SlashCommand(layout_extract_command) TodoWrite(mark_completed: "Extract layout", mark_in_progress: "Assemble UI") @@ -545,7 +549,7 @@ ELSE: โ”‚ โ”œโ”€โ”€ animation-tokens.json โ”‚ โ””โ”€โ”€ animation-guide.md โ”œโ”€โ”€ layout-extraction/ # Structure templates -โ”‚ โ””โ”€โ”€ layout-templates.json +โ”‚ โ””โ”€โ”€ layout-{target}-1.json # One file per target โ””โ”€โ”€ prototypes/ # {generated_count} HTML/CSS files โ”œโ”€โ”€ {target1}-style-1-layout-1.html + .css โ”œโ”€โ”€ {target2}-style-1-layout-1.html + .css 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 8e5e2dd0..b5d25779 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 ] [--css \"\"] [--js \"\"] [--scss \"\"] [--html \"\"] [--style-files \"\"] [--session ]" +argument-hint: "[--source-path ] [--output-path ] [--css \"\"] [--js \"\"] [--scss \"\"] [--html \"\"] [--style-files \"\"] [--session ]" allowed-tools: Read,Write,Bash,Glob,Grep,Task,TodoWrite auto-continue: true --- @@ -34,7 +34,8 @@ Extract design system tokens from source code files (CSS/SCSS/JS/TS/HTML) using /workflow:ui-design:import-from-code [FLAGS] # Flags ---base-path Base directory for analysis (default: current directory) +--source-path Source code directory to analyze (default: current directory) +--output-path Output directory for extracted design tokens (default: current directory) --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") @@ -47,19 +48,19 @@ Extract design system tokens from source code files (CSS/SCSS/JS/TS/HTML) using ```bash # Basic usage - auto-discover all files -/workflow:ui-design:import-from-code --base-path ./ +/workflow:ui-design:import-from-code --source-path ./src --output-path ./design-system # Target specific directories -/workflow:ui-design:import-from-code --base-path ./src --css "theme/*.css" --js "theme/*.js" +/workflow:ui-design:import-from-code --source-path ./src --output-path ./design-system --css "theme/*.css" --js "theme/*.js" -# Tailwind config only -/workflow:ui-design:import-from-code --js "tailwind.config.js" +# Tailwind config only (output to current directory) +/workflow:ui-design:import-from-code --source-path ./ --js "tailwind.config.js" # CSS framework import -/workflow:ui-design:import-from-code --css "styles/**/*.scss" --html "components/**/*.html" +/workflow:ui-design:import-from-code --source-path ./src --output-path ./design-system --css "styles/**/*.scss" --html "components/**/*.html" # Universal style files -/workflow:ui-design:import-from-code --style-files "**/theme.*" +/workflow:ui-design:import-from-code --source-path ./src --output-path ./design-system --style-files "**/theme.*" ``` --- @@ -74,11 +75,12 @@ Extract design system tokens from source code files (CSS/SCSS/JS/TS/HTML) using ```bash # 1. Initialize directories -base_path="${base_path:-.}" -intermediates_dir="${base_path}/.intermediates/import-analysis" +source_path="${source_path:-.}" +output_path="${output_path:-.}" +intermediates_dir="${output_path}/.intermediates/import-analysis" mkdir -p "$intermediates_dir" -echo "[Phase 0] File Discovery Started" +echo "[Phase 0] File Discovery Started (source: $source_path, output: $output_path)" ``` @@ -95,7 +97,7 @@ echo "[Phase 0] File Discovery Started" ```bash # 2. Discover files by type -cd "$base_path" || exit 1 +cd "$source_path" || exit 1 # CSS files if [ -n "$css" ]; then @@ -181,7 +183,7 @@ Task(ui-design-agent): ` [STYLE_TOKENS_EXTRACTION] Extract visual design tokens (colors, typography, spacing, shadows, borders) from ALL file types - MODE: style-extraction | BASE_PATH: ${base_path} + MODE: style-extraction | SOURCE_PATH: ${source_path} | OUTPUT_PATH: ${output_path} ## Input Files (Can reference ANY file type) @@ -208,7 +210,7 @@ Task(ui-design-agent): ` ## Output Requirements - Generate 2 files in ${base_path}/style-extraction/style-1/: + Generate 2 files in ${output_path}/style-extraction/style-1/: 1. design-tokens.json (production-ready design tokens) 2. style-guide.md (design philosophy and usage guide) @@ -357,13 +359,13 @@ Task(ui-design-agent): ` ## 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 + - โœ… Use Read() tool for each file you want to analyze (files are in SOURCE_PATH: ${source_path}) - โœ… 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") + - โœ… Create style-extraction/style-1/ directory first: Bash(mkdir -p "${output_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 + - ${output_path}/style-extraction/style-1/design-tokens.json + - ${output_path}/style-extraction/style-1/style-guide.md - โœ… Include _metadata.completeness field to track missing content - โŒ NO external research or MCP calls ` @@ -378,7 +380,7 @@ Task(ui-design-agent): ` [ANIMATION_TOKENS_EXTRACTION] Extract animation/transition tokens from ALL file types - MODE: animation-extraction | BASE_PATH: ${base_path} + MODE: animation-extraction | SOURCE_PATH: ${source_path} | OUTPUT_PATH: ${output_path} ## Input Files (Can reference ANY file type) @@ -405,7 +407,7 @@ Task(ui-design-agent): ` ## Output Requirements - Generate 2 files in ${base_path}/animation-extraction/: + Generate 2 files in ${output_path}/animation-extraction/: 1. animation-tokens.json (production-ready animation tokens) 2. animation-guide.md (animation usage guide) @@ -530,13 +532,13 @@ Task(ui-design-agent): ` ## Critical Requirements - โœ… Can read ANY file type (CSS/SCSS/JS/TS/HTML) - - โœ… Use Read() tool for each file you want to analyze + - โœ… Use Read() tool for each file you want to analyze (files are in SOURCE_PATH: ${source_path}) - โœ… Detect animation framework if used - โœ… Extract all animation-related tokens - - โœ… Create animation-extraction/ directory first: Bash(mkdir -p "${base_path}/animation-extraction") + - โœ… Create animation-extraction/ directory first: Bash(mkdir -p "${output_path}/animation-extraction") - โœ… Use Write() to save both files: - - ${base_path}/animation-extraction/animation-tokens.json - - ${base_path}/animation-extraction/animation-guide.md + - ${output_path}/animation-extraction/animation-tokens.json + - ${output_path}/animation-extraction/animation-guide.md - โœ… Include _metadata.completeness field to track missing content - โŒ NO external research or MCP calls ` @@ -551,7 +553,7 @@ Task(ui-design-agent): ` [LAYOUT_PATTERNS_EXTRACTION] Extract layout patterns and component structures from ALL file types - MODE: layout-extraction | BASE_PATH: ${base_path} + MODE: layout-extraction | SOURCE_PATH: ${source_path} | OUTPUT_PATH: ${output_path} ## Input Files (Can reference ANY file type) @@ -578,7 +580,7 @@ Task(ui-design-agent): ` ## Output Requirements - Generate 1 file: ${base_path}/layout-extraction/layout-templates.json + Generate 1 file: ${output_path}/layout-extraction/layout-templates.json ### layout-templates.json Structure: { @@ -675,11 +677,11 @@ Task(ui-design-agent): ` ## Critical Requirements - โœ… Can read ANY file type (CSS/SCSS/JS/TS/HTML) - - โœ… Use Read() tool for each file you want to analyze + - โœ… Use Read() tool for each file you want to analyze (files are in SOURCE_PATH: ${source_path}) - โœ… 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 + - โœ… Create layout-extraction/ directory first: Bash(mkdir -p "${output_path}/layout-extraction") + - โœ… Use Write() to save: ${output_path}/layout-extraction/layout-templates.json - โœ… Include extraction_metadata.completeness field to track missing content - โŒ NO external research or MCP calls ` @@ -710,11 +712,11 @@ echo "[Phase 1] Parallel agent analysis complete" ### Generated Files -**Location**: `${base_path}/` +**Location**: `${output_path}/` **Directory Structure**: ``` -${base_path}/ +${output_path}/ โ”œโ”€โ”€ style-extraction/ โ”‚ โ””โ”€โ”€ style-1/ โ”‚ โ”œโ”€โ”€ design-tokens.json # Production-ready design tokens @@ -769,7 +771,7 @@ ${base_path}/ | Error | Cause | Resolution | |-------|-------|------------| -| No files discovered | Glob patterns too restrictive or wrong base-path | Check glob patterns and base-path, verify file locations | +| No files discovered | Glob patterns too restrictive or wrong source-path | Check glob patterns and source-path, verify file locations | | 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) | @@ -779,7 +781,8 @@ ${base_path}/ ## Best Practices 1. **Use auto-discovery for full projects**: Omit glob flags to discover all files automatically -2. **Target specific directories for speed**: Use `--base-path` + specific globs for focused analysis -3. **Cross-reference agent reports**: Compare all three completeness reports to identify gaps -4. **Review missing content**: Check `missing` field in reports for actionable improvements -5. **Verify file discovery**: Check `.intermediates/import-analysis/*-files.txt` if agents report no data +2. **Target specific directories for speed**: Use `--source-path` to target source code and `--output-path` for extracted tokens, combined with specific globs for focused analysis +3. **Separate source and output**: Always use distinct `--source-path` (where source code lives) and `--output-path` (where design tokens are generated) to avoid polluting source code directory +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 `${output_path}/.intermediates/import-analysis/*-files.txt` 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 bc389f8d..77ed6760 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 ""] [--mode ] [--variants ] [--device-type ] +argument-hint: [--base-path ] [--session ] [--images ""] [--urls ""] [--prompt ""] [--targets ""] [--variants ] [--device-type ] allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), Task(ui-design-agent), mcp__exa__web_search_exa(*) --- @@ -14,10 +14,8 @@ Extract structural layout information from reference images, URLs, or text promp **Strategy**: AI-Driven Structural Analysis - **Agent-Powered**: Uses `ui-design-agent` for deep structural analysis -- **Dual-Mode**: - - `imitate`: High-fidelity replication of single layout structure - - `explore`: Multiple structurally distinct layout variations -- **Single Output**: `layout-templates.json` with DOM structure, component hierarchy, and CSS layout rules +- **Behavior**: Generate N layout concepts โ†’ User multi-select โ†’ Generate selected templates +- **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 @@ -45,15 +43,10 @@ ELSE: has_urls = false url_list = [] -# Determine extraction mode -extraction_mode = --mode OR "imitate" # "imitate" or "explore" - -# Set variants count based on mode -IF extraction_mode == "imitate": - variants_count = 1 # Force single variant (ignore --variants) -ELSE IF extraction_mode == "explore": - variants_count = --variants OR 3 # Default to 3 - VALIDATE: 1 <= variants_count <= 5 +# 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 # Resolve targets # Priority: --targets โ†’ url_list targets โ†’ prompt analysis โ†’ default ["page"] @@ -62,6 +55,9 @@ IF --targets: ELSE IF has_urls: targets = [url_info.target for url_info in url_list] ELSE IF --prompt: + # Extract targets from prompt using pattern matching + # Looks for keywords: "page names", target descriptors (login, dashboard, etc.) + # Returns lowercase, hyphenated strings (e.g., ["login", "dashboard"]) targets = extract_from_prompt(--prompt) ELSE: targets = ["page"] @@ -69,8 +65,10 @@ ELSE: # Resolve device type device_type = --device-type OR "responsive" # desktop|mobile|tablet|responsive -# Determine base path -bash(find .workflow -type d -name "design-*" | head -1) # Auto-detect +# Determine base path (auto-detect and convert to absolute) +relative_path=$(find .workflow -type d -name "design-run-*" | head -1) +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 ``` @@ -188,36 +186,17 @@ IF result.exploration?.triggered: IF session_has_inputs: SKIP Step 2 file reading # 2. Check if output already exists -bash(test -f {base_path}/layout-extraction/layout-templates.json && echo "exists") +bash(find {base_path}/layout-extraction -name "layout-*.json" -print -quit | grep -q . && echo "exists") IF exists: SKIP to completion ``` --- -**Phase 0 Output**: `input_mode`, `base_path`, `extraction_mode`, `variants_count`, `targets[]`, `device_type`, loaded inputs +**Phase 0 Output**: `input_mode`, `base_path`, `variants_count`, `targets[]`, `device_type`, loaded inputs -## Phase 1: Layout Concept Generation (Explore Mode Only) +## Phase 1: Layout Concept Generation -### Step 1: Check Extraction Mode -```bash -# extraction_mode == "imitate" โ†’ skip this phase -# extraction_mode == "explore" โ†’ execute this phase -``` - -**If imitate mode**: Skip to Phase 2 - -### Step 2: Gather Layout Inspiration (Explore Mode) -```bash -bash(mkdir -p {base_path}/.intermediates/layout-analysis/inspirations) - -# For each target: Research via MCP -# mcp__exa__web_search_exa(query="{target} layout patterns {device_type}", numResults=5) - -# Write inspiration file -Write({base_path}/.intermediates/layout-analysis/inspirations/{target}-layout-ideas.txt, inspiration_content) -``` - -### Step 3: Generate Layout Concept Options (Agent Task 1) +### Step 1: Generate Layout Concept Options (Agent Task 1) **Executor**: `Task(ui-design-agent)` Launch agent to generate `variants_count` layout concept options for each target: @@ -233,7 +212,6 @@ Task(ui-design-agent): ` ## Input Analysis - Targets: {targets.join(", ")} - Device type: {device_type} - - Layout inspiration: Read inspirations from {base_path}/.intermediates/layout-analysis/inspirations/ - Visual references: {loaded_images if available} ${dom_structure_available ? "- DOM Structure: Read from .intermediates/layout-analysis/dom-structure-*.json" : ""} @@ -270,7 +248,7 @@ Task(ui-design-agent): ` ` ``` -### Step 4: Verify Options File Created +### Step 2: Verify Options File Created ```bash bash(test -f {base_path}/.intermediates/layout-analysis/analysis-options.json && echo "created") @@ -331,13 +309,13 @@ Please select your preferred concept for this target. ### Step 3: Capture User Selection (Per Target) ```javascript -// Use AskUserQuestion tool for each target +// Use AskUserQuestion tool for each target (multi-select enabled) FOR each target: AskUserQuestion({ questions: [{ - question: "Which layout concept do you prefer for '{target}'?", + question: "Which layout concept(s) do you prefer for '{target}'?", header: "Layout for " + target, - multiSelect: false, + multiSelect: true, // Multi-selection enabled (default behavior) options: [ {FOR each concept in layout_concepts[target]: label: "Concept {concept.index}: {concept.concept_name}", @@ -347,39 +325,47 @@ FOR each target: }] }) - // Parse user response - selected_option_text = user_answer + // Parse user response (array of selections) + selected_options = user_answer // Check for user cancellation - IF selected_option_text == null OR selected_option_text == "": + IF selected_options == null OR selected_options.length == 0: REPORT: "โš ๏ธ User canceled selection. Workflow terminated." EXIT workflow - // Extract concept index from response format "Concept N: Name" - match = selected_option_text.match(/Concept (\d+):/) - IF match: - selected_index = parseInt(match[1]) - ELSE: - ERROR: "Invalid selection format. Expected 'Concept N: ...' format" - EXIT workflow + // Extract concept indices from array + selected_indices = [] + FOR each selected_option_text IN selected_options: + match = selected_option_text.match(/Concept (\d+):/) + IF match: + selected_indices.push(parseInt(match[1])) + ELSE: + ERROR: "Invalid selection format. Expected 'Concept N: ...' format" + EXIT workflow - // Store selection for this target + // Store selections for this target (array of indices) selections[target] = { - selected_index: selected_index, - concept_name: layout_concepts[target][selected_index-1].concept_name + selected_indices: selected_indices, // Array of selected indices + concept_names: selected_indices.map(i => layout_concepts[target][i-1].concept_name) } + + REPORT: "โœ… Selected {selected_indices.length} layout(s) for {target}" ``` ### Step 4: Write User Selection File ```bash +# Calculate total selections across all targets +total_selections = sum([len(selections[t].selected_indices) for t in targets]) + # Create user selection JSON selection_data = { "metadata": { "selected_at": "{current_timestamp}", - "selection_type": "per_target", - "session_id": "{session_id}" + "selection_type": "per_target_multi", + "session_id": "{session_id}", + "total_selections": total_selections }, - "selections": selections // {target: {selected_index, concept_name}} + "selections": selections // {target: {selected_indices: [...], concept_names: [...]}} } # Write to file @@ -391,149 +377,155 @@ bash(test -f {base_path}/.intermediates/layout-analysis/user-selection.json && e ### Step 5: Confirmation Message ``` -โœ… Selections recorded! +โœ… Selections recorded! Total: {total_selections} layout(s) {FOR each target, selection in selections: - โ€ข {target}: Concept {selection.selected_index} - {selection.concept_name} + โ€ข {target}: {selection.selected_indices.length} layout(s) selected + {FOR each index IN selection.selected_indices: + - Concept {index}: {layout_concepts[target][index-1].concept_name} + } } -Proceeding to generate detailed layout templates based on your selections... +Proceeding to generate {total_selections} detailed layout template(s)... ``` -**Output**: `user-selection.json` with user's choices for all targets +**Output**: `user-selection.json` with user's multi-selections for all targets ## Phase 2: Layout Template Generation (Agent Task 2) -**Executor**: `Task(ui-design-agent)` for selected concept(s) +**Executor**: `Task(ui-design-agent)` ร— `Total_Selected_Templates` in **parallel** -### Step 1: Load User Selection (Explore Mode) +### Step 1: Load User Selections and Build Task List ```bash -# For explore mode, read user selection -IF extraction_mode == "explore": - selection = Read({base_path}/.intermediates/layout-analysis/user-selection.json) - selections_per_target = selection.selections +# Read user selections +selection = Read({base_path}/.intermediates/layout-analysis/user-selection.json) +selections_per_target = selection.selections - # Also read the selected concept details from options - options = Read({base_path}/.intermediates/layout-analysis/analysis-options.json) - layout_concepts = options.layout_concepts +# Read concept details +options = Read({base_path}/.intermediates/layout-analysis/analysis-options.json) +layout_concepts = options.layout_concepts - # Build selected concepts map - selected_concepts = {} - FOR each target in targets: - selected_index = selections_per_target[target].selected_index - selected_concepts[target] = layout_concepts[target][selected_index-1] # 0-indexed -ELSE: - # Imitate mode - no selection needed - selected_concepts = null +# Build task list for all selected concepts across all targets +task_list = [] +FOR each target in targets: + selected_indices = selections_per_target[target].selected_indices # Array + concept_names = selections_per_target[target].concept_names # Array + + FOR i in range(len(selected_indices)): + idx = selected_indices[i] + concept = layout_concepts[target][idx - 1] # 0-indexed array + variant_id = i + 1 # 1-based variant numbering + + task_list.push({ + target: target, + variant_id: variant_id, + concept: concept, + output_file: "{base_path}/layout-extraction/layout-{target}-{variant_id}.json" + }) + +total_tasks = task_list.length +REPORT: "Generating {total_tasks} layout templates across {targets.length} targets" ``` -### Step 2: Launch Agent Task -Generate layout templates for selected concepts: +### Step 2: Launch Parallel Agent Tasks +Generate layout templates for ALL selected concepts in parallel: ```javascript -Task(ui-design-agent): ` - [LAYOUT_TEMPLATE_GENERATION_TASK] - Generate detailed layout templates based on user-selected concepts. - Focus ONLY on structure and layout. DO NOT concern with visual style (colors, fonts, etc.). +FOR each task in task_list: + Task(ui-design-agent): ` + [LAYOUT_TEMPLATE_GENERATION_TASK #{task.variant_id} for {task.target}] + Generate detailed layout template based on user-selected concept. + Focus ONLY on structure and layout. DO NOT concern with visual style (colors, fonts, etc.). - SESSION: {session_id} | MODE: {extraction_mode} | BASE_PATH: {base_path} - DEVICE_TYPE: {device_type} + SESSION: {session_id} | BASE_PATH: {base_path} + TARGET: {task.target} | VARIANT: {task.variant_id} + DEVICE_TYPE: {device_type} - ${extraction_mode == "explore" ? ` - USER SELECTIONS: - ${targets.map(target => ` - Target: ${target} - - Selected Concept: ${selected_concepts[target].concept_name} - - Philosophy: ${selected_concepts[target].design_philosophy} - - Pattern: ${selected_concepts[target].layout_pattern} - - Key Components: ${selected_concepts[target].key_components.join(", ")} - - Structural Features: ${selected_concepts[target].structural_features.join(", ")} - `).join("\n")} - ` : ` - MODE: Imitate - High-fidelity replication of reference layout structure - TARGETS: ${targets.join(", ")} - `} + USER SELECTION: + - Selected Concept: {task.concept.concept_name} + - Philosophy: {task.concept.design_philosophy} + - Pattern: {task.concept.layout_pattern} + - Key Components: {task.concept.key_components.join(", ")} + - Structural Features: {task.concept.structural_features.join(", ")} - ## Input Analysis - - Targets: {targets.join(", ")} - - Device type: {device_type} - - Visual references: {loaded_images if available} - ${dom_structure_available ? "- DOM Structure Data: Read from .intermediates/layout-analysis/dom-structure-*.json - USE THIS for accurate layout properties" : ""} + ## Input Analysis + - Target: {task.target} + - Device type: {device_type} + - Visual references: {loaded_images if available} + ${dom_structure_available ? "- DOM Structure Data: Read from .intermediates/layout-analysis/dom-structure-{task.target}.json - USE THIS for accurate layout properties" : ""} - ## Generation Rules - ${extraction_mode == "explore" ? ` - - **Explore Mode**: Develop each user-selected layout concept into a detailed template - - Use the selected concept's key_components as foundation - - Apply the selected layout_pattern (grid-3col, flex-row, etc.) - - Honor the structural_features defined in the concept - - Expand the concept with complete DOM structure and CSS layout rules - ` : ` - - **Imitate Mode**: High-fidelity replication of reference layout structure - ${dom_structure_available ? "- Use DOM structure data as ground truth" : "- Use visual inference"} - `} - ${dom_structure_available ? ` - - IMPORTANT: You have access to real DOM structure data with accurate flex/grid properties - - Use DOM data as primary source for layout properties - - Extract real flex/grid configurations (display, flexDirection, justifyContent, alignItems, gap) - - Use actual element bounds for responsive breakpoint decisions - - Preserve identified patterns from DOM structure - ` : ""} + ## Generation Rules + - Develop the user-selected layout concept into a detailed template + - Use the selected concept's key_components as foundation + - Apply the selected layout_pattern (grid-3col, flex-row, etc.) + - Honor the structural_features defined in the concept + - Expand the concept with complete DOM structure and CSS layout rules + ${dom_structure_available ? ` + - IMPORTANT: You have access to real DOM structure data with accurate flex/grid properties + - Use DOM data as primary source for layout properties + - Extract real flex/grid configurations (display, flexDirection, justifyContent, alignItems, gap) + - Use actual element bounds for responsive breakpoint decisions + - Preserve identified patterns from DOM structure + ` : ""} - ## Generate for EACH Target - For target in {targets}: - ${extraction_mode == "explore" ? "Based on user-selected concept:" : "Based on reference:"} + ## Template Generation - 1. **DOM Structure**: - - Semantic HTML5 tags:
,