diff --git a/.claude/agents/action-planning-agent.md b/.claude/agents/action-planning-agent.md index b0f3291e..883b2035 100644 --- a/.claude/agents/action-planning-agent.md +++ b/.claude/agents/action-planning-agent.md @@ -142,37 +142,6 @@ mcp__exa__get_code_context_exa( } ``` -**Legacy Pre-Execution Analysis** (backward compatibility): -- **Multi-step Pre-Analysis**: Execute comprehensive analysis BEFORE implementation begins - - **Sequential Processing**: Process each step sequentially, expanding brief actions - - **Template Usage**: Use full template paths with $(cat template_path) - - **Method Selection**: gemini/codex/manual/auto-detected -- **CLI Commands**: - - **Gemini**: `bash(~/.claude/scripts/gemini-wrapper -p "$(cat template_path) [action]")` - - **Codex**: `bash(codex --full-auto exec "$(cat template_path) [action]" -s danger-full-access)` -- **Follow Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md - -### Pre-Execution Analysis -**When [MULTI_STEP_ANALYSIS] marker is present:** - -#### Multi-Step Pre-Analysis Execution -1. Process each analysis step sequentially from pre_analysis array -2. For each step: - - Expand brief action into comprehensive analysis task - - Use specified template with $(cat template_path) - - Execute with specified method (gemini/codex/manual/auto-detected) -3. Accumulate results across all steps for comprehensive context -4. Use consolidated analysis to inform implementation stages and task breakdown - -#### Analysis Dimensions Coverage -- **Exa Research**: Use `mcp__exa__get_code_context_exa` for technology stack selection and API patterns -- Architecture patterns and component relationships -- Implementation conventions and coding standards -- Module dependencies and integration points -- Testing requirements and coverage patterns -- Security considerations and performance implications -3. Use Codex insights to create self-guided implementation stages - ## Core Functions ### 1. Stage Design @@ -222,11 +191,26 @@ Generate individual `.task/IMPL-*.json` files with: "output_to": "codebase_structure" } ], - "implementation_approach": { - "task_description": "Implement following synthesis specification", - "modification_points": ["Apply requirements"], - "logic_flow": ["Load spec", "Analyze", "Implement", "Validate"] - }, + "implementation_approach": [ + { + "step": 1, + "title": "Load and analyze synthesis specification", + "description": "Load synthesis specification from artifacts and extract requirements", + "modification_points": ["Load synthesis specification", "Extract requirements and design patterns"], + "logic_flow": ["Read synthesis specification from artifacts", "Parse architecture decisions", "Extract implementation requirements"], + "depends_on": [], + "output": "synthesis_requirements" + }, + { + "step": 2, + "title": "Implement following specification", + "description": "Implement task requirements following consolidated synthesis specification", + "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"], + "depends_on": [1], + "output": "implementation" + } + ], "target_files": ["file:function:lines", "path/to/NewFile.ts"] } } diff --git a/.claude/agents/code-developer.md b/.claude/agents/code-developer.md index ff711d94..478a0666 100644 --- a/.claude/agents/code-developer.md +++ b/.claude/agents/code-developer.md @@ -90,6 +90,32 @@ ELIF context insufficient OR task has flow control marker: - Get API examples: `mcp__exa__get_code_context_exa(query="React authentication hooks", tokensNum="dynamic")` - Update after changes: `mcp__code-index__refresh_index()` +**Implementation Approach Execution**: +When task JSON contains `flow_control.implementation_approach` array: +1. **Sequential Processing**: Execute steps in order, respecting `depends_on` dependencies +2. **Dependency Resolution**: Wait for all steps listed in `depends_on` before starting +3. **Variable Substitution**: Use `[variable_name]` to reference outputs from previous steps +4. **Step Structure**: + - `step`: Unique identifier (1, 2, 3...) + - `title`: Step title + - `description`: Detailed description with variable references + - `modification_points`: Code modification targets + - `logic_flow`: Business logic sequence + - `command`: Optional CLI command (only when explicitly specified) + - `depends_on`: Array of step numbers that must complete first + - `output`: Variable name for this step's output +5. **Execution Rules**: + - Execute step 1 first (typically has `depends_on: []`) + - For each subsequent step, verify all `depends_on` steps completed + - Substitute `[variable_name]` with actual outputs from previous steps + - Store this step's result in the `output` variable for future steps + - If `command` field present, execute it; otherwise use agent capabilities + +**CLI Command Execution (CLI Execute Mode)**: +When step contains `command` field with Codex CLI, execute via Bash tool. For Codex resume: +- First task (`depends_on: []`): `codex -C [path] --full-auto exec "..." --skip-git-repo-check -s danger-full-access` +- Subsequent tasks (has `depends_on`): Add `resume --last` flag to maintain session context + **Test-Driven Development**: - Write tests first (red → green → refactor) - Focus on core functionality and edge cases diff --git a/.claude/agents/conceptual-planning-agent.md b/.claude/agents/conceptual-planning-agent.md index 8673625f..50d2e1fe 100644 --- a/.claude/agents/conceptual-planning-agent.md +++ b/.claude/agents/conceptual-planning-agent.md @@ -83,6 +83,54 @@ def handle_brainstorm_assignment(prompt): generate_brainstorm_analysis(role, context_vars, output_location, topic) ``` +## Flow Control Format Handling + +This agent processes **simplified inline [FLOW_CONTROL]** format from brainstorm workflows. + +### Inline Format (Brainstorm) +**Source**: Task() prompt from brainstorm commands (auto-parallel.md, etc.) + +**Structure**: Markdown list format (3-5 steps) + +**Example**: +```markdown +[FLOW_CONTROL] + +### Flow Control Steps +1. **load_topic_framework** + - Action: Load structured topic framework + - Command: Read(.workflow/WFS-{session}/.brainstorming/topic-framework.md) + - Output: topic_framework + +2. **load_role_template** + - Action: Load role-specific planning template + - Command: bash($(cat "~/.claude/workflows/cli-templates/planning-roles/{role}.md")) + - Output: role_template + +3. **load_session_metadata** + - Action: Load session metadata + - Command: bash(cat .workflow/WFS-{session}/workflow-session.json) + - Output: session_metadata +``` + +**Characteristics**: +- 3-5 simple context loading steps +- Written directly in prompt (not persistent) +- No dependency management +- Used for temporary context preparation + +### NOT Handled by This Agent + +**JSON format** (used by code-developer, test-fix-agent): +```json +"flow_control": { + "pre_analysis": [...], + "implementation_approach": [...] +} +``` + +This complete JSON format is stored in `.task/IMPL-*.json` files and handled by implementation agents, not conceptual-planning-agent. + ### Role-Specific Analysis Dimensions | Role | Primary Dimensions | Focus Areas | Exa Usage | diff --git a/.claude/agents/doc-generator.md b/.claude/agents/doc-generator.md index 59473359..6a30ea13 100644 --- a/.claude/agents/doc-generator.md +++ b/.claude/agents/doc-generator.md @@ -68,8 +68,17 @@ You are an expert technical documentation specialist. Your responsibility is to ### 3. Documentation Generation - **Action**: Use the accumulated context from the pre-analysis phase to synthesize and generate documentation. -- **Instructions**: Follow the `implementation_approach` defined in the `flow_control` block. -- **Templates**: Apply templates as specified in `meta.template` or `implementation_approach`. +- **Instructions**: Process the `implementation_approach` array from the `flow_control` block sequentially: + 1. **Array Structure**: `implementation_approach` is an array of step objects + 2. **Sequential Execution**: Execute steps in order, respecting `depends_on` dependencies + 3. **Variable Substitution**: Use `[variable_name]` to reference outputs from previous steps + 4. **Step Processing**: + - Verify all `depends_on` steps completed before starting + - Follow `modification_points` and `logic_flow` for each step + - Execute `command` if present, otherwise use agent capabilities + - Store result in `output` variable for future steps + 5. **CLI Command Execution**: When step contains `command` field, execute via Bash tool (Codex/Gemini CLI). For Codex with dependencies, use `resume --last` flag. +- **Templates**: Apply templates as specified in `meta.template` or step-level templates. - **Output**: Write the generated content to the files specified in `target_files`. ### 4. Progress Tracking with TodoWrite diff --git a/.claude/agents/test-fix-agent.md b/.claude/agents/test-fix-agent.md index f859d5f9..25c4c9bb 100644 --- a/.claude/agents/test-fix-agent.md +++ b/.claude/agents/test-fix-agent.md @@ -41,6 +41,30 @@ You will execute tests, analyze failures, and fix code to ensure all tests pass. ## Execution Process +### Flow Control Execution +When task JSON contains `flow_control` field, execute preparation and implementation steps systematically. + +**Pre-Analysis Steps** (`flow_control.pre_analysis`): +1. **Sequential Processing**: Execute steps in order, accumulating context +2. **Variable Substitution**: Use `[variable_name]` to reference previous outputs +3. **Error Handling**: Follow step-specific strategies (`skip_optional`, `fail`, `retry_once`) + +**Implementation Approach** (`flow_control.implementation_approach`): +When task JSON contains implementation_approach array: +1. **Sequential Execution**: Process steps in order, respecting `depends_on` dependencies +2. **Dependency Resolution**: Wait for all steps listed in `depends_on` before starting +3. **Variable References**: Use `[variable_name]` to reference outputs from previous steps +4. **Step Structure**: + - `step`: Step number (1, 2, 3...) + - `title`: Step title + - `description`: Detailed description with variable references + - `modification_points`: Test and code modification targets + - `logic_flow`: Test-fix iteration sequence + - `command`: Optional CLI command (only when explicitly specified) + - `depends_on`: Array of step numbers that must complete first + - `output`: Variable name for this step's output + + ### 1. Context Assessment & Test Discovery - Analyze task context to identify test files and source code paths - Load test framework configuration (Jest, Pytest, Mocha, etc.) @@ -61,16 +85,34 @@ fi - Parse test results to identify failures ### 3. Failure Diagnosis & Fixing Loop + +**Execution Modes**: + +**A. Manual Mode (Default, meta.use_codex=false)**: ``` -WHILE tests are failing: - 1. Analyze failure output - 2. Identify root cause in source code - 3. Modify source code to fix issue - 4. Re-run affected tests +WHILE tests are failing AND iterations < max_iterations: + 1. Use Gemini to diagnose failure (bug-fix template) + 2. Present fix recommendations to user + 3. User applies fixes manually + 4. Re-run test suite 5. Verify fix doesn't break other tests END WHILE ``` +**B. Codex Mode (meta.use_codex=true)**: +``` +WHILE tests are failing AND iterations < max_iterations: + 1. Use Gemini to diagnose failure (bug-fix template) + 2. Use Codex to apply fixes automatically with resume mechanism + 3. Re-run test suite + 4. Verify fix doesn't break other tests +END WHILE +``` + +**Codex Resume in Test-Fix Cycle** (when `meta.use_codex=true`): +- First iteration: Start new Codex session with full context +- Subsequent iterations: Use `resume --last` to maintain fix history and apply consistent strategies + ### 4. Code Quality Certification - All tests pass → Code is APPROVED ✅ - Generate summary documenting: diff --git a/.claude/commands/workflow/execute.md b/.claude/commands/workflow/execute.md index 85098ba9..dc173a82 100644 --- a/.claude/commands/workflow/execute.md +++ b/.claude/commands/workflow/execute.md @@ -425,10 +425,28 @@ Task(subagent_type="{meta.agent}", "on_error": "skip_optional|fail|retry_once" } ], - "implementation_approach": { - "task_description": "Implement following consolidated synthesis specification...", - "modification_points": ["Apply synthesis specification requirements..."] - }, + "implementation_approach": [ + { + "step": 1, + "title": "Implement task following synthesis specification", + "description": "Implement '[title]' following synthesis specification. PRIORITY: Use synthesis-specification.md as primary requirement source. When implementation needs technical details (e.g., API schemas, caching configs, design tokens), refer to artifacts[] for detailed specifications from original role analyses.", + "modification_points": [ + "Apply consolidated requirements from synthesis-specification.md", + "Follow technical guidelines from synthesis", + "Consult artifacts for implementation details when needed", + "Integrate with existing patterns" + ], + "logic_flow": [ + "Load synthesis specification", + "Parse architecture and requirements", + "Implement following specification", + "Consult artifacts for technical details when needed", + "Validate against acceptance criteria" + ], + "depends_on": [], + "output": "implementation" + } + ], "target_files": ["file:function:lines", "path/to/NewFile.ts"] } } diff --git a/.claude/commands/workflow/plan.md b/.claude/commands/workflow/plan.md index 7e421fc3..7a22c990 100644 --- a/.claude/commands/workflow/plan.md +++ b/.claude/commands/workflow/plan.md @@ -1,7 +1,7 @@ --- name: plan description: Orchestrate 4-phase planning workflow by executing commands and passing context between phases -argument-hint: "[--agent] \"text description\"|file.md" +argument-hint: "[--agent] [--cli-execute] \"text description\"|file.md" allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*) --- @@ -30,6 +30,7 @@ This workflow runs **fully autonomously** once triggered. Each phase completes, **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 @@ -118,9 +119,23 @@ CONTEXT: Existing user database schema, REST API endpoints - **IMPL_PLAN.md defines "HOW"**: Executable task breakdown, dependencies, implementation sequence - Task generation translates high-level specifications into concrete, actionable work items -**Command**: +**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**: +```bash +# Manual with CLI execution +/workflow:tools:task-generate --session WFS-auth --cli-execute + +# Agent with CLI execution +/workflow:tools:task-generate-agent --session WFS-auth --cli-execute +``` **Input**: `sessionId` from Phase 1 @@ -254,7 +269,10 @@ Return summary to user ✅ Parse context path from Phase 2 output, store in memory ✅ Pass session ID and context path to Phase 3 command ✅ Verify ANALYSIS_RESULTS.md after Phase 3 -✅ Select correct Phase 4 command based on --agent flag +✅ **Build Phase 4 command** based on flags: + - Base command: `/workflow:tools:task-generate` (or `-agent` if `--agent` flag) + - Add `--session [sessionId]` + - Add `--cli-execute` if flag present ✅ Pass session ID to Phase 4 command ✅ Verify all Phase 4 outputs ✅ Update TodoWrite after each phase diff --git a/.claude/commands/workflow/test-gen.md b/.claude/commands/workflow/test-gen.md index f1888903..03801d0e 100644 --- a/.claude/commands/workflow/test-gen.md +++ b/.claude/commands/workflow/test-gen.md @@ -1,7 +1,7 @@ --- name: test-gen description: Create independent test-fix workflow session by analyzing completed implementation -argument-hint: "[--use-codex] source-session-id" +argument-hint: "[--use-codex] [--cli-execute] source-session-id" allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*) --- @@ -123,11 +123,12 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*) --- ### Phase 4: Generate Test Tasks -**Command**: `SlashCommand(command="/workflow:tools:test-task-generate [--use-codex] --session [testSessionId]")` +**Command**: `SlashCommand(command="/workflow:tools:test-task-generate [--use-codex] [--cli-execute] --session [testSessionId]")` **Input**: - `testSessionId` from Phase 1 -- `--use-codex` flag (if present in original command) +- `--use-codex` flag (if present in original command) - Controls IMPL-002 fix mode +- `--cli-execute` flag (if present in original command) - Controls IMPL-001 generation mode **Expected Behavior**: - Parse TEST_ANALYSIS_RESULTS.md from Phase 3 diff --git a/.claude/commands/workflow/tools/docs.md b/.claude/commands/workflow/tools/docs.md index 4edad148..c01c2350 100644 --- a/.claude/commands/workflow/tools/docs.md +++ b/.claude/commands/workflow/tools/docs.md @@ -6,117 +6,47 @@ examples: - /workflow:docs # Current directory (root: full docs, subdir: module only) - /workflow:docs src/modules # Module documentation only - /workflow:docs . --tool qwen # Root directory with Qwen - - /workflow:docs src/api --tool gemini # API module documentation - /workflow:docs --cli-generate # Use CLI for doc generation (not just analysis) --- -# Workflow Documentation Command +# Documentation Workflow (/workflow:docs) ## Overview +Lightweight planner that analyzes project structure, decomposes documentation work into tasks, and generates execution plans. Does NOT generate documentation content itself - delegates to doc-generator agent. -### Purpose +**Two Execution Modes**: +- **Default**: CLI analyzes in `pre_analysis` (MODE=analysis), agent writes docs in `implementation_approach` +- **--cli-generate**: CLI generates docs in `implementation_approach` (MODE=write) -**`/workflow:docs` is a lightweight planner/orchestrator** - it analyzes project structure using metadata tools, decomposes documentation work into tasks, and generates execution plans. It does **NOT** generate any documentation content itself. - -**Key Principle**: Lightweight Planning + Targeted Execution -- **docs.md** → Collect metadata (paths, structure), generate task JSONs with path references -- **doc-generator agent** → Execute targeted analysis on focus_paths, generate content - -**Optimization Philosophy**: -- **Planning phase**: Minimal context - only metadata (module paths, file lists) -- **Task JSON**: Store path references, not content -- **Execution phase**: Targeted deep analysis within focus_paths scope - -### Key Features - -**CLI Generation Control** -- Two execution modes: Analysis mode (default) vs Generation mode (--cli-generate) -- Analysis mode: CLI tools analyze in `pre_analysis`, agent writes docs in `implementation_approach` -- Generation mode: CLI tools generate docs directly in `implementation_approach` with MODE=write -- Flexible workflow: Choose between agent-driven or CLI-driven documentation generation - -**Path-Based Control** -- Flexible path specification: Document entire project (root) or specific subdirectories -- Automatic root detection: Uses git repository root to determine scope -- Smart task generation: Root paths get full docs, subdirectories get module docs only - -**Update Mode** -- Automatic detection: Recognizes existing documentation files -- Content preservation: Maintains user modifications when updating -- Incremental improvements: Add new sections without losing existing content -- Safe regeneration: Can safely re-run command to update stale docs - -**Bottom-Up Strategy** -- Self-contained modules first: Each module gets complete documentation (API.md + README.md) -- Project-level aggregation: README, Architecture, Examples synthesize from completed modules -- No premature aggregation: Project docs wait for all module docs to complete -- Conditional project docs: Only generated when running from project root - -**Dynamic Recognition** -- No hardcoded paths: Automatically discovers all project directories -- Intelligent type detection: Code folders get API.md + README.md, navigation folders get README.md only -- Respects project structure: Works with any directory layout - -**Correct Dependencies** -- Level 1 (Module trees): Always generated, can execute in parallel -- Level 2 (Project README): Only if root, must wait for all module docs -- Level 3 (Architecture/Examples): Only if root, must wait for project README - -### Usage +## Parameters ```bash /workflow:docs [path] [--tool ] [--cli-generate] ``` -**Parameters**: +- **path**: Target directory (default: current directory) + - Project root → Full documentation (modules + project-level docs) + - Subdirectory → Module documentation only (API.md + README.md) -- **path**: Target directory path (optional, default: current directory) - - If path is project root: Generate full documentation (modules + project-level docs) - - If path is subdirectory: Generate module documentation only (API.md + README.md) - - Path can be relative (e.g., `src/modules`) or absolute - -- **--tool**: `gemini` | `qwen` | `codex` (optional, default: gemini) - - `gemini`: Comprehensive documentation, pattern recognition (default) +- **--tool**: CLI tool selection (default: gemini) + - `gemini`: Comprehensive documentation, pattern recognition - `qwen`: Architecture analysis, system design focus - `codex`: Implementation validation, code quality - **--cli-generate**: Enable CLI-based documentation generation (optional) - - When enabled: CLI tools generate documentation content in implementation_approach - - When disabled (default): CLI tools only used for analysis in pre_analysis - - Requires MODE=write in CLI commands for file generation + - When enabled: CLI generates docs with MODE=write in implementation_approach + - When disabled (default): CLI analyzes with MODE=analysis in pre_analysis -## Workflow - -### Planning Phases - -``` -/workflow:docs [path] [--tool] [--cli-generate] - ↓ -Phase 1: Initialize Session → Create session dir, detect root status, record cli_generate flag - ↓ -Phase 2: Analyze Structure → Run get_modules_by_depth.sh, classify folders - ↓ -Phase 3: Detect Update Mode → Check existing docs, determine create/update - ↓ -Phase 4: Decompose Tasks → Generate Level 1-3 tasks based on root status - ↓ -Phase 5: Generate Task JSONs → Build IMPL-*.json with flow_control - - cli_generate=false: CLI in pre_analysis (MODE=analysis) - - cli_generate=true: CLI in implementation_approach (MODE=write) - ↓ -✅ Planning Complete → Show TodoWrite status -``` +## Planning Workflow ### Phase 1: Initialize Session - ```bash # Parse arguments -path="${1:-.}" # Target path (default: current directory) -tool="gemini" # gemini|qwen|codex (default: gemini) -cli_generate=false # CLI-based generation flag +path="${1:-.}" +tool="gemini" +cli_generate=false # Parse options -shift while [[ $# -gt 0 ]]; do case "$1" in --tool) tool="$2"; shift 2 ;; @@ -125,8 +55,9 @@ while [[ $# -gt 0 ]]; do esac done -# Detect project root and determine if target is root -project_root=$(git rev-parse --show-toplevel 2>/dev/null || pwd) +# Detect project root +bash(git rev-parse --show-toplevel) +project_root=$(pwd) target_path=$(cd "$path" && pwd) is_root=false [[ "$target_path" == "$project_root" ]] && is_root=true @@ -134,78 +65,79 @@ is_root=false # Create session structure timestamp=$(date +%Y%m%d-%H%M%S) session_dir=".workflow/WFS-docs-${timestamp}" -mkdir -p "${session_dir}"/{.task,.process,.summaries} -touch ".workflow/.active-WFS-docs-${timestamp}" + +bash(mkdir -p "${session_dir}"/{.task,.process,.summaries}) +bash(touch ".workflow/.active-WFS-docs-${timestamp}") # Record configuration -echo "path=$path" >> "${session_dir}/.process/config.txt" -echo "target_path=$target_path" >> "${session_dir}/.process/config.txt" -echo "is_root=$is_root" >> "${session_dir}/.process/config.txt" -echo "tool=$tool" >> "${session_dir}/.process/config.txt" -echo "cli_generate=$cli_generate" >> "${session_dir}/.process/config.txt" +bash(cat > "${session_dir}/.process/config.txt" <|files:N|size:N|has_claude:yes/no - -# Step 2: Classify each folder by type -mkdir -p "${session_dir}/.process" -> "${session_dir}/.process/folder-analysis.txt" +bash(~/.claude/scripts/get_modules_by_depth.sh) +# Output: depth:N|path:|files:N|size:N|has_claude:yes/no +# Step 2: Classify folders by type +bash(cat > "${session_dir}/.process/classify-folders.sh" <<'SCRIPT' while IFS='|' read -r depth_info path_info files_info size_info claude_info; do folder_path=$(echo "$path_info" | cut -d':' -f2-) - depth=$(echo "$depth_info" | cut -d':' -f2) # Count code files (maxdepth 1) - code_files=$(find "$folder_path" -maxdepth 1 -type f \( -name "*.ts" -o -name "*.js" -o -name "*.py" -o -name "*.go" -o -name "*.java" -o -name "*.rs" \) 2>/dev/null | wc -l) + code_files=$(find "$folder_path" -maxdepth 1 -type f \ + \( -name "*.ts" -o -name "*.js" -o -name "*.py" \ + -o -name "*.go" -o -name "*.java" -o -name "*.rs" \) \ + 2>/dev/null | wc -l) - # Count immediate subfolders - subfolders=$(find "$folder_path" -maxdepth 1 -type d -not -path "$folder_path" 2>/dev/null | wc -l) + # Count subfolders + subfolders=$(find "$folder_path" -maxdepth 1 -type d \ + -not -path "$folder_path" 2>/dev/null | wc -l) - # Determine folder type + # Determine type if [[ $code_files -gt 0 ]]; then - folder_type="code" # Has code files → needs API.md + README.md + folder_type="code" # API.md + README.md elif [[ $subfolders -gt 0 ]]; then - folder_type="navigation" # Only subfolders → needs README.md (navigation) + folder_type="navigation" # README.md only else - folder_type="skip" # Empty folder → skip + folder_type="skip" # Empty fi - # Record the analysis - echo "${folder_path}|${folder_type}|depth:${depth}|code_files:${code_files}|subfolders:${subfolders}" >> "${session_dir}/.process/folder-analysis.txt" -done <<< "$module_data" + echo "${folder_path}|${folder_type}|code:${code_files}|dirs:${subfolders}" +done +SCRIPT +) -# Step 3: Group folders by top-level directories -awk -F'|' '{ - split($1, parts, "/"); - if (length(parts) >= 2) { - top_dir = parts[1] "/" parts[2]; - print top_dir; - } -}' "${session_dir}/.process/folder-analysis.txt" | sort -u > "${session_dir}/.process/top-level-dirs.txt" +bash(~/.claude/scripts/get_modules_by_depth.sh | bash "${session_dir}/.process/classify-folders.sh" > "${session_dir}/.process/folder-analysis.txt") + +# Step 3: Group by top-level directories +bash(awk -F'|' '{split($1, parts, "/"); if (length(parts) >= 2) print parts[1] "/" parts[2]}' \ + "${session_dir}/.process/folder-analysis.txt" | sort -u > "${session_dir}/.process/top-level-dirs.txt") ``` ### Phase 3: Detect Update Mode - ```bash -# Detect existing documentation -existing_docs=$(find "$target_path" -name "API.md" -o -name "README.md" -o -name "ARCHITECTURE.md" -o -name "EXAMPLES.md" 2>/dev/null | grep -v ".workflow" | wc -l) +# Check existing documentation +bash(find "$target_path" -name "API.md" -o -name "README.md" -o -name "ARCHITECTURE.md" -o -name "EXAMPLES.md" 2>/dev/null | grep -v ".workflow" | wc -l) + +existing_docs=$(...) -# List existing documentation for update mode if [[ $existing_docs -gt 0 ]]; then - echo "Update mode: Found $existing_docs existing documentation files" - find "$target_path" -name "API.md" -o -name "README.md" -o -name "ARCHITECTURE.md" -o -name "EXAMPLES.md" 2>/dev/null | grep -v ".workflow" > "${session_dir}/.process/existing-docs.txt" - echo "mode=update" >> "${session_dir}/.process/config.txt" + bash(find "$target_path" -name "*.md" 2>/dev/null | grep -v ".workflow" > "${session_dir}/.process/existing-docs.txt") + echo "mode=update" >> "${session_dir}/.process/config.txt" else - echo "mode=create" >> "${session_dir}/.process/config.txt" + echo "mode=create" >> "${session_dir}/.process/config.txt" fi # Record strategy -cat > "${session_dir}/.process/strategy.md" < "${session_dir}/.process/strategy.md" < "${session_dir}/.process/strategy.md" </dev/null | xargs cat || echo 'No existing docs')", + "output_to": "existing_module_docs" + }, + { + "step": "load_folder_analysis", + "command": "bash(grep '^src/modules' ${session_dir}/.process/folder-analysis.txt)", + "output_to": "target_folders" + }, + { + "step": "analyze_module_tree", + "command": "bash(cd src/modules && ~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Analyze module structure\\nTASK: Generate documentation outline\\nMODE: analysis\\nCONTEXT: @{**/*} [target_folders]\\nEXPECTED: Structure outline\\nRULES: Analyze only\")", + "output_to": "tree_outline", + "note": "CLI for analysis only" + } + ], + "implementation_approach": [ + { + "step": 1, + "title": "Generate module tree documentation", + "description": "Process target folders and generate appropriate documentation files based on folder types", + "modification_points": ["Parse folder types from [target_folders]", "Parse structure from [tree_outline]", "Generate API.md for code folders", "Generate README.md for all folders"], + "logic_flow": ["Parse [target_folders] to get folder types", "Parse [tree_outline] for structure", "For each folder: if type == 'code': Generate API.md + README.md; elif type == 'navigation': Generate README.md only"], + "depends_on": [], + "output": "module_docs" + } + ], + "target_files": [ + ".workflow/docs/modules/*/API.md", + ".workflow/docs/modules/*/README.md" + ] + } +} ``` -### Task Examples - -**Example 1: Root Directory (Full Documentation)** -``` -Path: /d/Claude_dms3 (project root) -Tasks: IMPL-001~003 (modules) + IMPL-004~007 (project-level) - -IMPL-001: Document tree 'src/modules/' (Level 1) -IMPL-002: Document tree 'src/utils/' (Level 1) -IMPL-003: Document tree 'lib/' (Level 1) -IMPL-004: Project README.md (Level 2, depends_on: [001,002,003]) -IMPL-005: ARCHITECTURE.md (Level 3, depends_on: [004]) -IMPL-006: EXAMPLES.md (Level 3, depends_on: [004]) +**CLI Generate Mode (cli_generate=true)**: +```json +{ + "id": "IMPL-001", + "title": "Document Module Tree: 'src/modules/'", + "status": "pending", + "meta": { + "type": "docs-tree", + "agent": "@doc-generator", + "tool": "gemini", + "cli_generate": true + }, + "context": { + "requirements": [ + "Recursively process all folders in src/modules/", + "CLI generates documentation files directly" + ], + "focus_paths": ["src/modules"] + }, + "flow_control": { + "pre_analysis": [ + { + "step": "load_existing_docs", + "command": "bash(find src/modules -name '*.md' 2>/dev/null | xargs cat || echo 'No existing docs')", + "output_to": "existing_module_docs" + }, + { + "step": "load_folder_analysis", + "command": "bash(grep '^src/modules' ${session_dir}/.process/folder-analysis.txt)", + "output_to": "target_folders" + } + ], + "implementation_approach": [ + { + "step": 1, + "title": "Parse folder analysis", + "description": "Parse [target_folders] to get folder types and structure", + "modification_points": ["Extract folder types", "Identify code vs navigation folders"], + "logic_flow": ["Parse [target_folders] to get folder types", "Prepare folder list for CLI generation"], + "depends_on": [], + "output": "folder_types" + }, + { + "step": 2, + "title": "Generate documentation via CLI", + "description": "Call CLI to generate documentation files for each folder using MODE=write", + "modification_points": ["Execute CLI generation command", "Generate API.md and README.md files"], + "logic_flow": ["Call CLI to generate documentation files for each folder"], + "command": "bash(cd src/modules && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p \"PURPOSE: Generate module docs\\nTASK: Create documentation files\\nMODE: write\\nCONTEXT: @{**/*} [target_folders] [existing_module_docs]\\nEXPECTED: API.md and README.md files\\nRULES: Generate complete docs\")", + "depends_on": [1], + "output": "generated_docs" + } + ], + "target_files": [ + ".workflow/docs/modules/*/API.md", + ".workflow/docs/modules/*/README.md" + ] + } +} ``` -**Example 2: Subdirectory (Module Documentation Only)** -``` -Path: /d/Claude_dms3/src/modules (subdirectory) -Tasks: IMPL-001 only (module docs) +### Level 2: Project README Task -IMPL-001: Document tree 'src/modules/' (Level 1 only) -# No Level 2-3 tasks generated (not root) +**Default Mode**: +```json +{ + "id": "IMPL-004", + "title": "Generate Project README", + "status": "pending", + "depends_on": ["IMPL-001", "IMPL-002", "IMPL-003"], + "meta": { + "type": "docs", + "agent": "@doc-generator", + "tool": "gemini", + "cli_generate": false + }, + "flow_control": { + "pre_analysis": [ + { + "step": "load_existing_readme", + "command": "bash(cat .workflow/docs/README.md 2>/dev/null || echo 'No existing README')", + "output_to": "existing_readme" + }, + { + "step": "load_module_docs", + "command": "bash(find .workflow/docs/modules -name '*.md' | xargs cat)", + "output_to": "all_module_docs" + }, + { + "step": "analyze_project", + "command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Analyze project structure\\nTASK: Extract overview from modules\\nMODE: analysis\\nCONTEXT: [all_module_docs]\\nEXPECTED: Project outline\")", + "output_to": "project_outline" + } + ], + "implementation_approach": [ + { + "step": 1, + "title": "Generate project README", + "description": "Generate project README with navigation links while preserving existing user modifications", + "modification_points": ["Parse [project_outline] and [all_module_docs]", "Generate project README structure", "Add navigation links to modules", "Preserve [existing_readme] user modifications"], + "logic_flow": ["Parse [project_outline] and [all_module_docs]", "Generate project README with navigation links", "Preserve [existing_readme] user modifications"], + "depends_on": [], + "output": "project_readme" + } + ], + "target_files": [".workflow/docs/README.md"] + } +} ``` -### Dependency Rules +### Level 3: Architecture Documentation Task -1. **Level 1 tasks**: No dependencies, can execute in parallel -2. **Level 2 tasks**: Depend on ALL Level 1 tasks completing -3. **Level 3 tasks**: Depend on Level 2 task completing, can parallelize within level -4. **Update mode**: All tasks include `load_existing_docs` step to preserve content - -## Execution - -### Execution Flow - -``` -┌──────────────────────────────────────────┐ -│ Planning Phase │ -│ /workflow:docs [path] [--tool] │ -└───────────────┬──────────────────────────┘ - │ - ↓ -┌───────────────────────────────────────────┐ -│ Level 1: Module Trees (Parallel) │ -│ /workflow:execute IMPL-001 │ -│ /workflow:execute IMPL-002 │ -│ /workflow:execute IMPL-003 │ -└───────────────┬───────────────────────────┘ - │ (all complete) - ↓ -┌───────────────────────────────────────────┐ -│ Level 2: Project README (Sequential) │ (Only if root) -│ /workflow:execute IMPL-004 │ -└───────────────┬───────────────────────────┘ - │ (complete) - ↓ -┌───────────────────────────────────────────┐ -│ Level 3: Architecture & Examples │ (Only if root) -│ /workflow:execute IMPL-005 │ -│ /workflow:execute IMPL-006 │ -│ /workflow:execute IMPL-007 (optional) │ -└───────────────────────────────────────────┘ +**Default Mode**: +```json +{ + "id": "IMPL-005", + "title": "Generate Architecture Documentation", + "status": "pending", + "depends_on": ["IMPL-004"], + "meta": { + "type": "docs", + "agent": "@doc-generator", + "tool": "gemini", + "cli_generate": false + }, + "flow_control": { + "pre_analysis": [ + { + "step": "load_existing_arch", + "command": "bash(cat .workflow/docs/ARCHITECTURE.md 2>/dev/null || echo 'No existing ARCHITECTURE')", + "output_to": "existing_architecture" + }, + { + "step": "load_all_docs", + "command": "bash(cat .workflow/docs/README.md && find .workflow/docs/modules -name '*.md' | xargs cat)", + "output_to": "all_docs" + }, + { + "step": "analyze_architecture", + "command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Analyze system architecture\\nTASK: Synthesize architectural overview\\nMODE: analysis\\nCONTEXT: [all_docs]\\nEXPECTED: Architecture outline\")", + "output_to": "arch_outline" + } + ], + "implementation_approach": [ + { + "step": 1, + "title": "Generate architecture documentation", + "description": "Generate ARCHITECTURE.md while preserving existing user modifications", + "modification_points": ["Parse [arch_outline] and [all_docs]", "Generate ARCHITECTURE.md structure", "Document system design and patterns", "Preserve [existing_architecture] modifications"], + "logic_flow": ["Parse [arch_outline] and [all_docs]", "Generate ARCHITECTURE.md", "Preserve [existing_architecture] modifications"], + "depends_on": [], + "output": "architecture_doc" + } + ], + "target_files": [".workflow/docs/ARCHITECTURE.md"] + } +} ``` -### Command Examples +### Level 3: Examples Documentation Task -**Root Directory (Full Documentation)**: -```bash -# Level 1 - Module documentation (parallel) -/workflow:execute IMPL-001 -/workflow:execute IMPL-002 -/workflow:execute IMPL-003 - -# Level 2 - Project README (after Level 1) -/workflow:execute IMPL-004 - -# Level 3 - Architecture & Examples (after Level 2) -/workflow:execute IMPL-005 -/workflow:execute IMPL-006 -/workflow:execute IMPL-007 # if HTTP API present +**Default Mode**: +```json +{ + "id": "IMPL-006", + "title": "Generate Examples Documentation", + "status": "pending", + "depends_on": ["IMPL-004"], + "meta": { + "type": "docs", + "agent": "@doc-generator", + "tool": "gemini", + "cli_generate": false + }, + "flow_control": { + "pre_analysis": [ + { + "step": "load_existing_examples", + "command": "bash(cat .workflow/docs/EXAMPLES.md 2>/dev/null || echo 'No existing EXAMPLES')", + "output_to": "existing_examples" + }, + { + "step": "load_project_readme", + "command": "bash(cat .workflow/docs/README.md)", + "output_to": "project_readme" + }, + { + "step": "generate_examples_outline", + "command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Generate usage examples\\nTASK: Extract example patterns\\nMODE: analysis\\nCONTEXT: [project_readme]\\nEXPECTED: Examples outline\")", + "output_to": "examples_outline" + } + ], + "implementation_approach": [ + { + "step": 1, + "title": "Generate examples documentation", + "description": "Generate EXAMPLES.md with code snippets while preserving existing user modifications", + "modification_points": ["Parse [examples_outline] and [project_readme]", "Generate EXAMPLES.md structure", "Add code snippets and usage examples", "Preserve [existing_examples] modifications"], + "logic_flow": ["Parse [examples_outline] and [project_readme]", "Generate EXAMPLES.md with code snippets", "Preserve [existing_examples] modifications"], + "depends_on": [], + "output": "examples_doc" + } + ], + "target_files": [".workflow/docs/EXAMPLES.md"] + } +} ``` -**Subdirectory (Module Only)**: -```bash -# Only Level 1 task generated -/workflow:execute IMPL-001 +### Level 3: HTTP API Documentation Task (Optional) + +**Default Mode**: +```json +{ + "id": "IMPL-007", + "title": "Generate HTTP API Documentation", + "status": "pending", + "depends_on": ["IMPL-004"], + "meta": { + "type": "docs", + "agent": "@doc-generator", + "tool": "gemini", + "cli_generate": false + }, + "flow_control": { + "pre_analysis": [ + { + "step": "discover_api_endpoints", + "command": "mcp__code-index__search_code_advanced(pattern='router\\.|@(Get|Post)', file_pattern='*.{ts,js}')", + "output_to": "endpoint_discovery" + }, + { + "step": "load_existing_api_docs", + "command": "bash(cat .workflow/docs/api/README.md 2>/dev/null || echo 'No existing API docs')", + "output_to": "existing_api_docs" + }, + { + "step": "analyze_api", + "command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Document HTTP API\\nTASK: Analyze API endpoints\\nMODE: analysis\\nCONTEXT: @{src/api/**/*} [endpoint_discovery]\\nEXPECTED: API outline\")", + "output_to": "api_outline" + } + ], + "implementation_approach": [ + { + "step": 1, + "title": "Generate HTTP API documentation", + "description": "Generate HTTP API documentation while preserving existing user modifications", + "modification_points": ["Parse [api_outline] and [endpoint_discovery]", "Generate HTTP API documentation", "Document endpoints and request/response formats", "Preserve [existing_api_docs] modifications"], + "logic_flow": ["Parse [api_outline] and [endpoint_discovery]", "Generate HTTP API documentation", "Preserve [existing_api_docs] modifications"], + "depends_on": [], + "output": "api_docs" + } + ], + "target_files": [".workflow/docs/api/README.md"] + } +} ``` -### Progress Tracking - -**TodoWrite Status**: - -Planning Phase: -``` -✅ Session initialization (completed) -⏳ IMPL-001: Document tree 'src/modules/' (pending) -⏳ IMPL-002: Document tree 'src/utils/' (pending) -⏳ IMPL-003: Document tree 'lib/' (pending) -⏳ IMPL-004: Project README (pending, depends on IMPL-001~003) -⏳ IMPL-005: Architecture Documentation (pending, depends on IMPL-004) -⏳ IMPL-006: Examples Documentation (pending, depends on IMPL-004) -``` - -Execution Phase: -``` -✅ Session initialization -🔄 IMPL-001: Document tree 'src/modules/' (in_progress) -⏳ IMPL-002: Document tree 'src/utils/' -⏳ IMPL-003: Document tree 'lib/' -... -``` - -## Output - -### Session Structure +## Session Structure ``` .workflow/ @@ -439,8 +541,8 @@ Execution Phase: ├── IMPL_PLAN.md # Implementation plan ├── TODO_LIST.md # Progress tracker ├── .process/ - │ ├── config.txt # Path, root status, tool, mode - │ ├── strategy.md # Doc strategy summary + │ ├── config.txt # path, is_root, tool, cli_generate, mode + │ ├── strategy.md # Documentation strategy summary │ ├── folder-analysis.txt # Folder type classification │ ├── top-level-dirs.txt # Top-level directory list │ └── existing-docs.txt # Existing documentation files @@ -450,10 +552,11 @@ Execution Phase: ├── IMPL-003.json # Module tree task ├── IMPL-004.json # Project README (if root) ├── IMPL-005.json # Architecture (if root) - └── IMPL-006.json # Examples (if root) + ├── IMPL-006.json # Examples (if root) + └── IMPL-007.json # HTTP API (if root, optional) ``` -### Generated Documentation +## Generated Documentation ``` .workflow/docs/ @@ -475,391 +578,88 @@ Execution Phase: └── README.md # HTTP API reference ``` -### IMPL_PLAN.md Format - -```markdown -# Documentation Implementation Plan - -**Session**: WFS-docs-[timestamp] -**Path**: [target_path] -**Is Root**: [true|false] -**Tool**: [gemini|qwen|codex] -**CLI Generate**: [true|false] -**Mode**: [create|update] -**Strategy**: Bottom-up, layered approach - -## CLI Generation Mode - -**CLI Generate Flag**: [true|false] - -- **false (default)**: CLI tools used for analysis in `pre_analysis`, agent generates docs in `implementation_approach` -- **true**: CLI tools generate documentation files directly in `implementation_approach` with MODE=write - -## Task Breakdown - -### Level 1: Module Tree Tasks (Always Generated) -- **IMPL-001**: Document tree 'src/modules/' - - Output: modules/*/{API.md,README.md} - - Templates: api.txt (Part A), module-readme.txt, folder-navigation.txt - - Update mode: Preserves existing content - - CLI placement: [pre_analysis | implementation_approach] based on cli_generate flag - -### Level 2: Project README (Only if is_root=true) -- **IMPL-004**: Generate Project README - - Output: README.md - - Template: project-readme.txt - - Dependencies: IMPL-001, IMPL-002, IMPL-003 - - CLI placement: [pre_analysis | implementation_approach] based on cli_generate flag - -### Level 3: Architecture & Examples (Only if is_root=true) -- **IMPL-005**: Generate Architecture Documentation -- **IMPL-006**: Generate Examples Documentation -- **IMPL-007**: Generate HTTP API Documentation (Optional) -- CLI placement: [pre_analysis | implementation_approach] based on cli_generate flag - -## Execution Order -1. Level 1 (Parallel): IMPL-001, IMPL-002, IMPL-003 -2. Level 2 (After Level 1): IMPL-004 (if root) -3. Level 3 (After Level 2): IMPL-005, IMPL-006, IMPL-007 (if root) -``` - -## Reference - -### Task JSON Templates - -#### 1. Module Tree Task (Level 1) - -**Default Mode (--cli-generate not specified)**: -```json -{ - "id": "IMPL-001", - "title": "Document Module Tree: 'src/modules/'", - "status": "pending", - "meta": { - "type": "docs-tree", - "agent": "@doc-generator", - "tool": "gemini", - "template": "api + module-readme + folder-navigation", - "cli_generate": false - }, - "context": { - "requirements": [ - "Recursively process all folders in src/modules/", - "For folders with code files: generate API.md + README.md", - "For folders with only subfolders: generate README.md (navigation)", - "Use folder-analysis.txt to determine folder types" - ], - "focus_paths": ["src/modules"], - "folder_analysis_file": "${session_dir}/.process/folder-analysis.txt", - "acceptance": [ - "All code-containing folders have both API.md and README.md", - "All navigation folders have README.md", - "Documents follow their respective templates" - ] - }, - "flow_control": { - "pre_analysis": [ - { - "step": "load_existing_docs", - "command": "bash(find src/modules -name 'API.md' -o -name 'README.md' 2>/dev/null | xargs cat 2>/dev/null || echo 'No existing docs')", - "output_to": "existing_module_docs", - "note": "Update mode: preserve existing content" - }, - { - "step": "load_folder_analysis", - "command": "bash(grep '^src/modules' ${session_dir}/.process/folder-analysis.txt)", - "output_to": "target_folders" - }, - { - "step": "analyze_module_tree_content", - "command": "bash(cd src/modules && ~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Document module tree\\nTASK: Analyze module structure and generate documentation outline\\nMODE: analysis\\nCONTEXT: @{**/*} [target_folders] [existing_module_docs]\\nEXPECTED: Documentation content outline\\nRULES: $(cat ~/.claude/workflows/cli-templates/prompts/documentation/api.txt) | Analyze structure only\")", - "output_to": "tree_documentation", - "note": "CLI for analysis only, agent generates final docs" - } - ], - "implementation_approach": { - "logic_flow": [ - "Parse [target_folders] to get list of folders and their types", - "Parse [tree_documentation] for structure outline", - "For each folder in tree:", - " if type == 'code': Generate API.md + README.md using [tree_documentation]", - " elif type == 'navigation': Generate README.md only" - ] - }, - "target_files": [ - ".workflow/docs/modules/*/API.md", - ".workflow/docs/modules/*/README.md" - ] - } -} -``` - -**CLI Generate Mode (--cli-generate specified)**: -```json -{ - "id": "IMPL-001", - "title": "Document Module Tree: 'src/modules/'", - "status": "pending", - "meta": { - "type": "docs-tree", - "agent": "@doc-generator", - "tool": "gemini", - "template": "api + module-readme + folder-navigation", - "cli_generate": true - }, - "context": { - "requirements": [ - "Recursively process all folders in src/modules/", - "For folders with code files: generate API.md + README.md", - "For folders with only subfolders: generate README.md (navigation)", - "Use folder-analysis.txt to determine folder types" - ], - "focus_paths": ["src/modules"], - "folder_analysis_file": "${session_dir}/.process/folder-analysis.txt", - "acceptance": [ - "All code-containing folders have both API.md and README.md", - "All navigation folders have README.md", - "Documents follow their respective templates" - ] - }, - "flow_control": { - "pre_analysis": [ - { - "step": "load_existing_docs", - "command": "bash(find src/modules -name 'API.md' -o -name 'README.md' 2>/dev/null | xargs cat 2>/dev/null || echo 'No existing docs')", - "output_to": "existing_module_docs", - "note": "Update mode: preserve existing content" - }, - { - "step": "load_folder_analysis", - "command": "bash(grep '^src/modules' ${session_dir}/.process/folder-analysis.txt)", - "output_to": "target_folders" - } - ], - "implementation_approach": { - "logic_flow": [ - "Parse [target_folders] to get list of folders and their types", - "For each folder in tree:", - " if type == 'code': Call CLI to generate API.md + README.md", - " elif type == 'navigation': Call CLI to generate README.md only" - ], - "cli_generation": [ - { - "step": "generate_module_tree_docs", - "command": "bash(cd src/modules && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p \"PURPOSE: Document module tree\\nTASK: Generate complete documentation files for each folder\\nMODE: write\\nCONTEXT: @{**/*} [target_folders] [existing_module_docs]\\nEXPECTED: Generated API.md and README.md files\\nRULES: $(cat ~/.claude/workflows/cli-templates/prompts/documentation/api.txt) | Update existing docs, preserve modifications\")", - "output_to": "generated_docs", - "note": "CLI generates documentation files with MODE=write" - } - ] - }, - "target_files": [ - ".workflow/docs/modules/*/API.md", - ".workflow/docs/modules/*/README.md" - ] - } -} -``` - -#### 2. Project README Task (Level 2) - -**Note**: Like Level 1 tasks, this task also has two modes based on `--cli-generate` flag: -- **Default mode**: CLI analysis in `pre_analysis`, agent generates docs -- **CLI generate mode**: CLI generation in `implementation_approach` with MODE=write - -**Default Mode Example**: -```json -{ - "id": "IMPL-004", - "title": "Generate Project README", - "status": "pending", - "depends_on": ["IMPL-001", "IMPL-002", "IMPL-003"], - "meta": { - "type": "docs", - "agent": "@doc-generator", - "tool": "gemini", - "template": "project-readme" - }, - "context": { - "requirements": [ - "Aggregate information from all module documentation", - "Generate navigation links to all modules" - ], - "focus_paths": ["."] - }, - "flow_control": { - "pre_analysis": [ - { - "step": "load_existing_project_readme", - "command": "bash(cat .workflow/docs/README.md 2>/dev/null || echo 'No existing README')", - "output_to": "existing_readme" - }, - { - "step": "load_all_module_docs", - "command": "bash(find .workflow/docs/modules -name 'README.md' -o -name 'API.md' | xargs cat)", - "output_to": "all_module_docs" - }, - { - "step": "analyze_project_structure", - "command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Generate project overview\\nTASK: Extract project structure from module docs\\nMODE: analysis\\nCONTEXT: [all_module_docs] [existing_readme]\\nRULES: $(cat ~/.claude/workflows/cli-templates/prompts/documentation/project-readme.txt) | Preserve user modifications\")", - "output_to": "project_overview" - } - ], - "target_files": [".workflow/docs/README.md"] - } -} -``` - -#### 3. Architecture Documentation Task (Level 3) - -**Note**: Level 3 tasks also support both modes based on `--cli-generate` flag. - -**Default Mode Example**: -```json -{ - "id": "IMPL-005", - "title": "Generate Architecture Documentation", - "status": "pending", - "depends_on": ["IMPL-004"], - "meta": { - "type": "docs", - "agent": "@doc-generator", - "tool": "gemini", - "template": "project-architecture" - }, - "flow_control": { - "pre_analysis": [ - { - "step": "load_existing_architecture", - "command": "bash(cat .workflow/docs/ARCHITECTURE.md 2>/dev/null || echo 'No existing ARCHITECTURE')", - "output_to": "existing_architecture" - }, - { - "step": "load_all_docs", - "command": "bash(cat .workflow/docs/README.md && find .workflow/docs/modules -name '*.md' | xargs cat)", - "output_to": "all_docs" - }, - { - "step": "synthesize_architecture", - "command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Synthesize architecture\\nCONTEXT: [all_docs] [existing_architecture]\\nRULES: $(cat ~/.claude/workflows/cli-templates/prompts/documentation/project-architecture.txt)\")", - "output_to": "architecture_content" - } - ], - "target_files": [".workflow/docs/ARCHITECTURE.md"] - } -} -``` - -#### 4. Examples Documentation Task (Level 3) - -**Note**: Same dual-mode support as other tasks. - -**Default Mode Example**: -```json -{ - "id": "IMPL-006", - "title": "Generate Examples Documentation", - "status": "pending", - "depends_on": ["IMPL-004"], - "meta": { - "type": "docs", - "agent": "@doc-generator", - "tool": "gemini", - "template": "project-examples" - }, - "flow_control": { - "pre_analysis": [ - { - "step": "load_existing_examples", - "command": "bash(cat .workflow/docs/EXAMPLES.md 2>/dev/null || echo 'No existing EXAMPLES')", - "output_to": "existing_examples" - }, - { - "step": "load_project_readme", - "command": "bash(cat .workflow/docs/README.md)", - "output_to": "project_readme" - }, - { - "step": "generate_examples_content", - "command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Generate usage examples\\nCONTEXT: [project_readme] [existing_examples]\\nRULES: $(cat ~/.claude/workflows/cli-templates/prompts/documentation/project-examples.txt)\")", - "output_to": "examples_content" - } - ], - "target_files": [".workflow/docs/EXAMPLES.md"] - } -} -``` - -#### 5. HTTP API Documentation Task (Level 3, Optional) - -**Note**: Same dual-mode support as other tasks. - -**Default Mode Example**: -```json -{ - "id": "IMPL-007", - "title": "Generate HTTP API Documentation", - "status": "pending", - "depends_on": ["IMPL-004"], - "meta": { - "type": "docs", - "agent": "@doc-generator", - "tool": "gemini", - "template": "api" - }, - "flow_control": { - "pre_analysis": [ - { - "step": "load_existing_api_docs", - "command": "bash(cat .workflow/docs/api/README.md 2>/dev/null || echo 'No existing API docs')", - "output_to": "existing_api_docs" - }, - { - "step": "discover_api_endpoints", - "command": "mcp__code-index__search_code_advanced(pattern='router\\.|@(Get|Post)', file_pattern='*.{ts,js}')", - "output_to": "endpoint_discovery" - }, - { - "step": "analyze_api_structure", - "command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Document HTTP API\\nCONTEXT: @{src/api/**/*} [existing_api_docs]\\nRULES: $(cat ~/.claude/workflows/cli-templates/prompts/documentation/api.txt) | Use Part B: HTTP API\")", - "output_to": "api_analysis" - } - ], - "target_files": [".workflow/docs/api/README.md"] - } -} -``` - -### Template Reference - -**5 Specialized Templates**: -- **api.txt**: Unified template for Code API (Part A) and HTTP API (Part B) -- **module-readme.txt**: Module purpose, usage, dependencies -- **folder-navigation.txt**: Navigation README for folders with only subdirectories -- **project-readme.txt**: Project overview, getting started, module navigation -- **project-architecture.txt**: System structure, module map, design patterns -- **project-examples.txt**: End-to-end usage examples - -### Error Handling - -- **No modules found**: Create only IMPL-001 (system overview) -- **Invalid path**: Show error and exit -- **Active session exists**: Prompt to complete or pause -- **Tool unavailable**: Fall back to gemini - -### Next Steps +## Execution Commands +### Root Directory (Full Documentation) ```bash -# 1. Review planning output -cat .workflow/WFS-docs-*/IMPL_PLAN.md -cat .workflow/WFS-docs-*/TODO_LIST.md - -# 2. Execute tasks (respects dependencies) +# Level 1 - Module documentation (parallel) /workflow:execute IMPL-001 /workflow:execute IMPL-002 /workflow:execute IMPL-003 -# ... then Level 2 and 3 if root -# 3. Review generated documentation -ls -lah .workflow/docs/ -cat .workflow/docs/README.md +# Level 2 - Project README (after Level 1) +/workflow:execute IMPL-004 + +# Level 3 - Architecture & Examples (after Level 2, parallel) +/workflow:execute IMPL-005 +/workflow:execute IMPL-006 +/workflow:execute IMPL-007 # if HTTP API present ``` + +### Subdirectory (Module Only) +```bash +# Only Level 1 task generated +/workflow:execute IMPL-001 +``` + +## Simple Bash Commands + +### Check Documentation Status +```bash +# List existing documentation +bash(find . -name "API.md" -o -name "README.md" -o -name "ARCHITECTURE.md" 2>/dev/null | grep -v ".workflow") + +# Count documentation files +bash(find . -name "*.md" 2>/dev/null | grep -v ".workflow" | wc -l) +``` + +### Analyze Module Structure +```bash +# Discover modules +bash(~/.claude/scripts/get_modules_by_depth.sh) + +# Count code files in directory +bash(find src/modules -maxdepth 1 -type f \( -name "*.ts" -o -name "*.js" \) | wc -l) + +# Count subdirectories +bash(find src/modules -maxdepth 1 -type d -not -path "src/modules" | wc -l) +``` + +### Session Management +```bash +# Create session directories +bash(mkdir -p .workflow/WFS-docs-20240120/.{task,process,summaries}) + +# Mark session as active +bash(touch .workflow/.active-WFS-docs-20240120) + +# Read session configuration +bash(cat .workflow/WFS-docs-20240120/.process/config.txt) + +# List session tasks +bash(ls .workflow/WFS-docs-20240120/.task/*.json) +``` + +## Template Reference + +**Available Templates**: +- `api.txt`: Unified template for Code API (Part A) and HTTP API (Part B) +- `module-readme.txt`: Module purpose, usage, dependencies +- `folder-navigation.txt`: Navigation README for folders with subdirectories +- `project-readme.txt`: Project overview, getting started, module navigation +- `project-architecture.txt`: System structure, module map, design patterns +- `project-examples.txt`: End-to-end usage examples + +**Template Location**: `~/.claude/workflows/cli-templates/prompts/documentation/` + +## CLI Generate Mode Summary + +| Mode | CLI Placement | CLI MODE | Agent Role | +|------|---------------|----------|------------| +| **Default** | pre_analysis | analysis | Generates documentation files | +| **--cli-generate** | implementation_approach | write | Validates and coordinates CLI output | + +## Related Commands +- `/workflow:execute` - Execute documentation tasks +- `/workflow:status` - View task progress +- `/workflow:session:complete` - Mark session complete diff --git a/.claude/commands/workflow/tools/task-generate-agent.md b/.claude/commands/workflow/tools/task-generate-agent.md index c425610c..3cd2a60c 100644 --- a/.claude/commands/workflow/tools/task-generate-agent.md +++ b/.claude/commands/workflow/tools/task-generate-agent.md @@ -215,17 +215,29 @@ Task( "on_error": "fail" } ], - "implementation_approach": { - "task_description": "Implement '[title]' following synthesis specification. PRIORITY: Use synthesis-specification.md as primary requirement source. When implementation needs technical details (e.g., API schemas, caching configs, design tokens), refer to artifacts[] for detailed specifications from original role analyses.", - "modification_points": ["Apply requirements from synthesis"], - "logic_flow": [ - "Load synthesis specification", - "Analyze existing patterns", - "Implement following specification", - "Consult artifacts for technical details when needed", - "Validate against acceptance criteria" - ] - }, + "implementation_approach": [ + { + "step": 1, + "title": "Implement task following synthesis specification", + "description": "Implement '[title]' following synthesis specification. PRIORITY: Use synthesis-specification.md as primary requirement source. When implementation needs technical details (e.g., API schemas, caching configs, design tokens), refer to artifacts[] for detailed specifications from original role analyses.", + "modification_points": [ + "Apply consolidated requirements from synthesis-specification.md", + "Follow technical guidelines from synthesis", + "Consult artifacts for implementation details when needed", + "Integrate with existing patterns" + ], + "logic_flow": [ + "Load synthesis specification and relevant role artifacts", + "Execute MCP code-index discovery for relevant files", + "Analyze existing patterns and identify modification targets", + "Implement following specification", + "Consult artifacts for technical details when needed", + "Validate against acceptance criteria" + ], + "depends_on": [], + "output": "implementation" + } + ], "target_files": ["file:function:lines", "path/to/NewFile.ts"] } } diff --git a/.claude/commands/workflow/tools/task-generate-tdd.md b/.claude/commands/workflow/tools/task-generate-tdd.md index 4f48e3da..296eb632 100644 --- a/.claude/commands/workflow/tools/task-generate-tdd.md +++ b/.claude/commands/workflow/tools/task-generate-tdd.md @@ -174,51 +174,53 @@ For each feature, generate 3 tasks with ID format: "on_error": "skip_optional" } ], - "implementation_approach": { - "task_description": "Write minimal code to pass tests, then enter iterative fix cycle if they still fail", - "initial_implementation": [ - "Write minimal code based on test requirements", - "Execute test suite: bash(npm test -- tests/auth/login.test.ts)", - "If tests pass → Complete task", - "If tests fail → Capture failure logs and proceed to test-fix cycle" - ], - "test_fix_cycle": { - "max_iterations": 3, - "cycle_pattern": "gemini_diagnose → manual_fix (or codex if meta.use_codex=true) → retest", - "tools": { - "diagnosis": "gemini-wrapper (MODE: analysis, uses bug-fix template)", - "fix_application": "manual (default) or codex if meta.use_codex=true", - "verification": "bash(npm test -- tests/auth/login.test.ts)" - }, - "exit_conditions": { - "success": "all_tests_pass", - "failure": "max_iterations_reached" - }, - "steps": [ - "ITERATION LOOP (max 3):", - " 1. Gemini Diagnosis:", - " bash(cd .workflow/WFS-xxx/.process && ~/.claude/scripts/gemini-wrapper --all-files -p \"", - " PURPOSE: Diagnose TDD Green phase test failure iteration [N]", - " TASK: Systematic bug analysis and fix recommendations", - " MODE: analysis", - " CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}", - " Test output: [test_failures]", - " Test requirements: [test_requirements]", - " Implementation: [focus_paths]", - " EXPECTED: Root cause analysis, code path tracing, targeted fixes", - " RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: [test_failure_description]", - " Minimal surgical fixes only - stay in Green phase", - " \" > green-fix-iteration-[N]-diagnosis.md)", - " 2. Apply Fix (check meta.use_codex):", - " IF meta.use_codex=false (default): Present diagnosis to user for manual fix", - " IF meta.use_codex=true: Codex applies fix automatically", - " 3. Retest: bash(npm test -- tests/auth/login.test.ts)", - " 4. If pass → Exit loop, complete task", - " If fail → Continue to next iteration", - "IF max_iterations reached: Revert changes, report failure" - ] + "implementation_approach": [ + { + "step": 1, + "title": "Implement minimal code to pass tests", + "description": "Write minimal code based on test requirements following TDD principles - no over-engineering", + "modification_points": [ + "Load test requirements from TEST phase", + "Create/modify implementation files", + "Implement only what tests require", + "Focus on passing tests, not perfection" + ], + "logic_flow": [ + "Load test requirements from [test_requirements]", + "Parse test expectations and edge cases", + "Write minimal implementation code", + "Avoid premature optimization or abstraction" + ], + "depends_on": [], + "output": "initial_implementation" + }, + { + "step": 2, + "title": "Test and iteratively fix until passing", + "description": "Run tests and enter iterative fix cycle if needed (max 3 iterations with auto-revert on failure)", + "modification_points": [ + "Execute test suite", + "If tests fail: diagnose with Gemini", + "Apply fixes (manual or Codex if meta.use_codex=true)", + "Retest and iterate" + ], + "logic_flow": [ + "Run test suite", + "If all tests pass → Complete", + "If tests fail → Enter iteration loop (max 3):", + " Extract failure messages and stack traces", + " Use Gemini bug-fix template for diagnosis", + " Generate targeted fix recommendations", + " Apply fixes (manual or Codex)", + " Rerun tests", + " If pass → Complete, if fail → Continue iteration", + "If max_iterations reached → Trigger auto-revert" + ], + "command": "bash(npm test -- tests/auth/login.test.ts)", + "depends_on": [1], + "output": "test_results" } - }, + ], "post_completion": [ { "step": "verify_tests_passing", diff --git a/.claude/commands/workflow/tools/task-generate.md b/.claude/commands/workflow/tools/task-generate.md index cdc6b698..993e70d3 100644 --- a/.claude/commands/workflow/tools/task-generate.md +++ b/.claude/commands/workflow/tools/task-generate.md @@ -1,9 +1,10 @@ --- name: task-generate description: Generate task JSON files and IMPL_PLAN.md from analysis results with artifacts integration -argument-hint: "--session WFS-session-id" +argument-hint: "--session WFS-session-id [--cli-execute]" examples: - /workflow:tools:task-generate --session WFS-auth + - /workflow:tools:task-generate --session WFS-auth --cli-execute --- # Task Generation Command @@ -11,12 +12,30 @@ examples: ## Overview Generate task JSON files and IMPL_PLAN.md from analysis results with automatic artifact detection and integration. +## Execution Modes + +### Agent Mode (Default) +Tasks execute within agent context using agent's capabilities: +- Agent reads synthesis specifications +- Agent implements following requirements +- Agent validates implementation +- **Benefit**: Seamless context within single agent execution + +### CLI Execute Mode (`--cli-execute`) +Tasks execute using Codex CLI with resume mechanism: +- Each task uses `codex exec` command in `implementation_approach` +- First task establishes Codex session +- Subsequent tasks use `codex exec "..." resume --last` for context continuity +- **Benefit**: Codex's autonomous development capabilities with persistent context +- **Use Case**: Complex implementation requiring Codex's reasoning and iteration + ## Core Philosophy - **Analysis-Driven**: Generate from ANALYSIS_RESULTS.md - **Artifact-Aware**: Auto-detect brainstorming outputs - **Context-Rich**: Embed comprehensive context in task JSON - **Flow-Control Ready**: Pre-define implementation steps - **Memory-First**: Reuse loaded documents from memory +- **CLI-Aware**: Support Codex resume mechanism for persistent context ## Core Responsibilities - Parse analysis results and extract tasks @@ -153,23 +172,52 @@ Generate task JSON files and IMPL_PLAN.md from analysis results with automatic a "on_error": "fail" } ], - "implementation_approach": { - "task_description": "Implement '[title]' following synthesis specification. PRIORITY: Use synthesis-specification.md as primary requirement source. When implementation needs technical details (e.g., API schemas, caching configs, design tokens), refer to artifacts[] for detailed specifications from original role analyses.", - "modification_points": [ - "Apply consolidated requirements from synthesis-specification.md", - "Follow technical guidelines from synthesis", - "Consult artifacts for implementation details when needed", - "Integrate with existing patterns" - ], - "logic_flow": [ - "Load synthesis specification", - "Extract requirements and design", - "Analyze existing patterns", - "Implement following specification", - "Consult artifacts for technical details when needed", - "Validate against acceptance criteria" - ] - }, + "implementation_approach": [ + { + "step": 1, + "title": "Implement task following synthesis specification", + "description": "Implement '[title]' following synthesis specification. PRIORITY: Use synthesis-specification.md as primary requirement source. When implementation needs technical details (e.g., API schemas, caching configs, design tokens), refer to artifacts[] for detailed specifications from original role analyses.", + "modification_points": [ + "Apply consolidated requirements from synthesis-specification.md", + "Follow technical guidelines from synthesis", + "Consult artifacts for implementation details when needed", + "Integrate with existing patterns" + ], + "logic_flow": [ + "Load synthesis specification", + "Extract requirements and design", + "Analyze existing patterns", + "Implement following specification", + "Consult artifacts for technical details when needed", + "Validate against acceptance criteria" + ], + "depends_on": [], + "output": "implementation" + } + ], + + // CLI Execute Mode: Use Codex command (when --cli-execute flag present) + "implementation_approach": [ + { + "step": 1, + "title": "Execute implementation with Codex", + "description": "Use Codex CLI to implement '[title]' following synthesis specification with autonomous development capabilities", + "modification_points": [ + "Codex loads synthesis specification and artifacts", + "Codex implements following requirements", + "Codex validates and tests implementation" + ], + "logic_flow": [ + "Establish or resume Codex session", + "Pass synthesis specification to Codex", + "Codex performs autonomous implementation", + "Codex validates against acceptance criteria" + ], + "command": "bash(codex -C [focus_paths] --full-auto exec \"PURPOSE: [title] TASK: [requirements] MODE: auto CONTEXT: @{[synthesis_path],[artifacts_paths]} EXPECTED: [acceptance] RULES: Follow synthesis-specification.md\" [resume_flag] --skip-git-repo-check -s danger-full-access)", + "depends_on": [], + "output": "implementation" + } + ], "target_files": ["file:function:lines"] } } @@ -181,7 +229,37 @@ Generate task JSON files and IMPL_PLAN.md from analysis results with automatic a 3. Generate task context (requirements, focus_paths, acceptance) 4. **Determine modification targets**: Extract specific code locations from analysis 5. Build flow_control with artifact loading steps and target_files -6. Create individual task JSON files in `.task/` +6. **CLI Execute Mode**: If `--cli-execute` flag present, generate Codex commands +7. Create individual task JSON files in `.task/` + +#### Codex Resume Mechanism (CLI Execute Mode) + +**Session Continuity Strategy**: +- **First Task** (no depends_on or depends_on=[]): Establish new Codex session + - Command: `codex -C [path] --full-auto exec "[prompt]" --skip-git-repo-check -s danger-full-access` + - Creates new session context + +- **Subsequent Tasks** (has depends_on): Resume previous Codex session + - Command: `codex --full-auto exec "[prompt]" resume --last --skip-git-repo-check -s danger-full-access` + - Maintains context from previous implementation + - **Critical**: `resume --last` flag enables context continuity + +**Resume Flag Logic**: +```javascript +// Determine resume flag based on task dependencies +const resumeFlag = task.context.depends_on && task.context.depends_on.length > 0 + ? "resume --last" + : ""; + +// First task (IMPL-001): no resume flag +// Later tasks (IMPL-002, IMPL-003): use "resume --last" +``` + +**Benefits**: +- ✅ Shared context across related tasks +- ✅ Codex learns from previous implementations +- ✅ Consistent patterns and conventions +- ✅ Reduced redundant analysis #### Target Files Generation (Critical) **Purpose**: Identify specific code locations for modification AND new files to create @@ -542,8 +620,82 @@ Core requirements, objectives, technical approach summary (2-3 paragraphs max). /workflow:tools:task-generate --session WFS-auth ``` +## CLI Execute Mode Examples + +### Example 1: First Task (Establish Session) +```json +{ + "id": "IMPL-001", + "title": "Implement user authentication module", + "context": { + "depends_on": [], + "focus_paths": ["src/auth"], + "requirements": ["JWT-based authentication", "Login and registration endpoints"] + }, + "flow_control": { + "implementation_approach": [{ + "step": 1, + "title": "Execute implementation with Codex", + "command": "bash(codex -C src/auth --full-auto exec \"PURPOSE: Implement user authentication module TASK: JWT-based authentication with login and registration MODE: auto CONTEXT: @{.workflow/WFS-session/.brainstorming/synthesis-specification.md} EXPECTED: Complete auth module with tests RULES: Follow synthesis specification\" --skip-git-repo-check -s danger-full-access)", + "depends_on": [], + "output": "implementation" + }] + } +} +``` + +### Example 2: Subsequent Task (Resume Session) +```json +{ + "id": "IMPL-002", + "title": "Add password reset functionality", + "context": { + "depends_on": ["IMPL-001"], + "focus_paths": ["src/auth"], + "requirements": ["Password reset via email", "Token validation"] + }, + "flow_control": { + "implementation_approach": [{ + "step": 1, + "title": "Execute implementation with Codex", + "command": "bash(codex --full-auto exec \"PURPOSE: Add password reset functionality TASK: Password reset via email with token validation MODE: auto CONTEXT: Previous auth implementation from session EXPECTED: Password reset endpoints with email integration RULES: Maintain consistency with existing auth patterns\" resume --last --skip-git-repo-check -s danger-full-access)", + "depends_on": [], + "output": "implementation" + }] + } +} +``` + +### Example 3: Third Task (Continue Session) +```json +{ + "id": "IMPL-003", + "title": "Implement role-based access control", + "context": { + "depends_on": ["IMPL-001", "IMPL-002"], + "focus_paths": ["src/auth"], + "requirements": ["User roles and permissions", "Middleware for route protection"] + }, + "flow_control": { + "implementation_approach": [{ + "step": 1, + "title": "Execute implementation with Codex", + "command": "bash(codex --full-auto exec \"PURPOSE: Implement role-based access control TASK: User roles, permissions, and route protection middleware MODE: auto CONTEXT: Existing auth system from session EXPECTED: RBAC system integrated with current auth RULES: Use established patterns from session context\" resume --last --skip-git-repo-check -s danger-full-access)", + "depends_on": [], + "output": "implementation" + }] + } +} +``` + +**Pattern Summary**: +- IMPL-001: Fresh start with `-C src/auth` and full prompt +- IMPL-002: Resume with `resume --last`, references "previous auth implementation" +- IMPL-003: Resume with `resume --last`, references "existing auth system" + ## 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:concept-enhanced` - Provides analysis results - `/workflow:execute` - Executes generated tasks \ No newline at end of file diff --git a/.claude/commands/workflow/tools/test-task-generate.md b/.claude/commands/workflow/tools/test-task-generate.md index 31c9f74a..ec9bd956 100644 --- a/.claude/commands/workflow/tools/test-task-generate.md +++ b/.claude/commands/workflow/tools/test-task-generate.md @@ -1,10 +1,12 @@ --- name: test-task-generate description: Generate test-fix task JSON with iterative test-fix-retest cycle specification -argument-hint: "[--use-codex] --session WFS-test-session-id" +argument-hint: "[--use-codex] [--cli-execute] --session WFS-test-session-id" examples: - /workflow:tools:test-task-generate --session WFS-test-auth - /workflow:tools:test-task-generate --use-codex --session WFS-test-auth + - /workflow:tools:test-task-generate --cli-execute --session WFS-test-auth + - /workflow:tools:test-task-generate --cli-execute --use-codex --session WFS-test-auth --- # Test Task Generation Command @@ -12,6 +14,16 @@ examples: ## 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). +## Execution Modes + +### Test Generation (IMPL-001) +- **Agent Mode (Default)**: @code-developer generates tests within agent context +- **CLI Execute Mode (`--cli-execute`)**: Use Codex CLI for autonomous test generation + +### Test Fix (IMPL-002) +- **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 @@ -37,8 +49,9 @@ Generate specialized test-fix task JSON with comprehensive test-fix-retest cycle ### Phase 1: Input Validation & Discovery 1. **Parameter Parsing** - - Parse `--use-codex` flag from command arguments - - Store flag value for IMPL-002.json generation + - 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` @@ -142,31 +155,53 @@ Generate **TWO task JSON files**: "on_error": "skip_optional" } ], - "implementation_approach": { - "task_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).", - "generation_steps": [ - "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" + // 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" ], - "quality_criteria": [ - "All test scenarios from analysis are implemented", - "Test structure matches existing patterns", - "Clear test descriptions and assertions", - "Proper setup/teardown and fixtures", - "Dependencies properly mocked", - "Tests follow project coding standards" - ] - }, + "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}", @@ -278,24 +313,27 @@ Generate **TWO task JSON files**: "on_error": "skip_optional" } ], - "implementation_approach": { - "task_description": "Execute iterative test-fix-retest cycle using Gemini diagnosis (bug-fix template) and manual fixes (Codex only if explicitly needed)", - "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-wrapper (MODE: analysis, uses bug-fix template)", - "fix_application": "manual (default) or codex exec resume --last (if explicitly needed)", - "verification": "bash(test_command) + regression_check" + "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-wrapper (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" + } }, - "exit_conditions": { - "success": "all_tests_pass", - "failure": "max_iterations_reached", - "error": "test_command_not_found" - } - }, - "modification_points": [ + "modification_points": [ "PHASE 1: Initial Test Execution", " 1.1. Discover test command from framework detection", " 1.2. Execute initial test run: bash([test_command])", @@ -427,33 +465,36 @@ Generate **TWO task JSON files**: " 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" + "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" + } }, - "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", diff --git a/.claude/workflows/task-core.md b/.claude/workflows/task-core.md index c497e95f..dce31ec2 100644 --- a/.claude/workflows/task-core.md +++ b/.claude/workflows/task-core.md @@ -42,11 +42,17 @@ All task files use this simplified 5-field schema (aligned with workflow-archite "on_error": "skip_optional" } ], - "implementation_approach": { - "task_description": "Implement comprehensive JWT authentication system...", - "modification_points": ["Add JWT token generation...", "..."], - "logic_flow": ["User login request → validate credentials...", "..."] - }, + "implementation_approach": [ + { + "step": 1, + "title": "Implement JWT authentication system", + "description": "Implement comprehensive JWT authentication system with token generation, validation, and refresh logic", + "modification_points": ["Add JWT token generation", "Implement token validation middleware", "Create refresh token logic"], + "logic_flow": ["User login request → validate credentials", "Generate JWT access and refresh tokens", "Store refresh token securely", "Return tokens to client"], + "depends_on": [], + "output": "jwt_implementation" + } + ], "target_files": [ "src/auth/login.ts:handleLogin:75-120", "src/middleware/auth.ts:validateToken", diff --git a/.claude/workflows/workflow-architecture.md b/.claude/workflows/workflow-architecture.md index 0ed7f85c..4a31a02a 100644 --- a/.claude/workflows/workflow-architecture.md +++ b/.claude/workflows/workflow-architecture.md @@ -162,17 +162,61 @@ All task files use this unified 5-field schema with optional artifacts enhanceme "output_to": "context" } ], - "implementation_approach": { - "task_description": "Implement JWT authentication following [design]", - "modification_points": [ - "Add JWT generation using [parent] patterns", - "Implement validation middleware from [context]" - ], - "logic_flow": [ - "User login → validate with [inherited] → generate JWT", - "Protected route → extract JWT → validate using [shared] rules" - ] - }, + "implementation_approach": [ + { + "step": 1, + "title": "Set up authentication infrastructure", + "description": "Install JWT library and create auth config following [design] patterns from [parent]", + "modification_points": [ + "Add JWT library dependencies to package.json", + "Create auth configuration file using [parent] patterns" + ], + "logic_flow": [ + "Install jsonwebtoken library via npm", + "Configure JWT secret and expiration from [inherited]", + "Export auth config for use by [jwt_generator]" + ], + "depends_on": [], + "output": "auth_config" + }, + { + "step": 2, + "title": "Implement JWT generation", + "description": "Create JWT token generation logic using [auth_config] and [inherited] validation patterns", + "modification_points": [ + "Add JWT generation function in auth service", + "Implement token signing with [auth_config]" + ], + "logic_flow": [ + "User login → validate credentials with [inherited]", + "Generate JWT payload with user data", + "Sign JWT using secret from [auth_config]", + "Return signed token" + ], + "depends_on": [1], + "output": "jwt_generator" + }, + { + "step": 3, + "title": "Implement JWT validation middleware", + "description": "Create middleware to validate JWT tokens using [auth_config] and [shared] rules", + "modification_points": [ + "Create validation middleware using [jwt_generator]", + "Add token verification using [shared] rules", + "Implement user attachment to request object" + ], + "logic_flow": [ + "Protected route → extract JWT from Authorization header", + "Validate token signature using [auth_config]", + "Check token expiration and [shared] rules", + "Decode payload and attach user to request", + "Call next() or return 401 error" + ], + "command": "bash(npm test -- middleware.test.ts)", + "depends_on": [1, 2], + "output": "auth_middleware" + } + ], "target_files": [ "src/auth/login.ts:handleLogin:75-120", "src/middleware/auth.ts:validateToken", @@ -208,33 +252,329 @@ Optional field referencing brainstorming outputs for task execution: **Types & Priority**: synthesis_specification (highest) → topic_framework (medium) → individual_role_analysis (low) #### Flow Control Configuration -The **flow_control** field manages task execution with two main components: +The **flow_control** field manages task execution through structured sequential steps. For complete format specifications and usage guidelines, see [Flow Control Format Guide](#flow-control-format-guide) below. -**pre_analysis** - Context gathering phase: -- **Flexible commands**: Supports multiple tool types (see Tool Reference below) -- **Step structure**: Each step has `step`, `action`, `command` fields -- **Variable accumulation**: Steps can reference previous outputs via `[variable_name]` -- **Error handling**: `skip_optional`, `fail`, `retry_once`, `manual_intervention` +**Quick Reference**: +- **pre_analysis**: Context gathering steps (supports multiple command types) +- **implementation_approach**: Implementation steps array with dependency management +- **target_files**: Target files for modification (file:function:lines format) +- **Variable references**: Use `[variable_name]` to reference step outputs +- **Tool integration**: Supports Gemini, Codex, Bash commands, and MCP tools -**implementation_approach** - Implementation definition: -- **task_description**: Comprehensive implementation description -- **modification_points**: Specific code modification targets -- **logic_flow**: Business logic execution sequence -- **target_files**: Target file list - existing files in `file:function:lines` format, new files as `file` only +## Flow Control Format Guide -#### Tool Reference -**Command Types Available**: -- **Gemini CLI**: `~/.claude/scripts/gemini-wrapper -p "prompt"` -- **Codex CLI**: `codex --full-auto exec "task" -s danger-full-access` -- **Built-in Tools**: `grep(pattern)`, `glob(pattern)`, `search(query)` -- **Bash Commands**: `bash(rg 'pattern' src/)`, `bash(find . -name "*.ts")` +The `[FLOW_CONTROL]` marker indicates that a task or prompt contains flow control steps for sequential execution. There are **two distinct formats** used in different scenarios: -#### Variable System & Context Flow -**Flow Control Variables**: Use `[variable_name]` format for dynamic content: +### Format Comparison Matrix + +| Aspect | Inline Format | JSON Format | +|--------|--------------|-------------| +| **Used In** | Brainstorm workflows | Implementation tasks | +| **Agent** | conceptual-planning-agent | code-developer, test-fix-agent, doc-generator | +| **Location** | Task() prompt (markdown) | .task/IMPL-*.json file | +| **Persistence** | Temporary (prompt-only) | Persistent (file storage) | +| **Complexity** | Simple (3-5 steps) | Complex (10+ steps) | +| **Dependencies** | None | Full `depends_on` support | +| **Purpose** | Load brainstorming context | Implement task with preparation | + +### Inline Format (Brainstorm) + +**Marker**: `[FLOW_CONTROL]` written directly in Task() prompt + +**Structure**: Markdown list format + +**Used By**: Brainstorm commands (`auto-parallel.md`, role commands) + +**Agent**: `conceptual-planning-agent` + +**Example**: +```markdown +[FLOW_CONTROL] + +### Flow Control Steps +**AGENT RESPONSIBILITY**: Execute these pre_analysis steps sequentially with context accumulation: + +1. **load_topic_framework** + - Action: Load structured topic discussion framework + - Command: Read(.workflow/WFS-{session}/.brainstorming/topic-framework.md) + - Output: topic_framework + +2. **load_role_template** + - Action: Load role-specific planning template + - Command: bash($(cat "~/.claude/workflows/cli-templates/planning-roles/{role}.md")) + - Output: role_template + +3. **load_session_metadata** + - Action: Load session metadata and topic description + - Command: bash(cat .workflow/WFS-{session}/workflow-session.json 2>/dev/null || echo '{}') + - Output: session_metadata +``` + +**Characteristics**: +- 3-5 simple context loading steps +- Written directly in prompt (not persistent) +- No dependency management between steps +- Used for temporary context preparation +- Variables: `[variable_name]` for output references + +### JSON Format (Implementation) + +**Marker**: `[FLOW_CONTROL]` used in TodoWrite or documentation to indicate task has flow control + +**Structure**: Complete JSON structure in task file + +**Used By**: Implementation tasks (IMPL-*.json) + +**Agents**: `code-developer`, `test-fix-agent`, `doc-generator` + +**Example**: +```json +"flow_control": { + "pre_analysis": [ + { + "step": "load_synthesis_specification", + "action": "Load consolidated synthesis specification", + "commands": [ + "bash(ls .workflow/WFS-{session}/.brainstorming/synthesis-specification.md 2>/dev/null || echo 'not found')", + "Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md)" + ], + "output_to": "synthesis_specification", + "on_error": "skip_optional" + }, + { + "step": "mcp_codebase_exploration", + "action": "Explore codebase using MCP", + "command": "mcp__code-index__find_files(pattern=\"*.ts\") && mcp__code-index__search_code_advanced(pattern=\"auth\")", + "output_to": "codebase_structure" + } + ], + "implementation_approach": [ + { + "step": 1, + "title": "Setup infrastructure", + "description": "Install JWT library and create config following [synthesis_specification]", + "modification_points": [ + "Add JWT library dependencies to package.json", + "Create auth configuration file" + ], + "logic_flow": [ + "Install jsonwebtoken library via npm", + "Configure JWT secret from [synthesis_specification]", + "Export auth config for use by [jwt_generator]" + ], + "depends_on": [], + "output": "auth_config" + }, + { + "step": 2, + "title": "Implement JWT generation", + "description": "Create JWT token generation logic using [auth_config]", + "modification_points": [ + "Add JWT generation function in auth service", + "Implement token signing with [auth_config]" + ], + "logic_flow": [ + "User login → validate credentials", + "Generate JWT payload with user data", + "Sign JWT using secret from [auth_config]", + "Return signed token" + ], + "depends_on": [1], + "output": "jwt_generator" + } + ], + "target_files": [ + "src/auth/login.ts:handleLogin:75-120", + "src/middleware/auth.ts:validateToken" + ] +} +``` + +**Characteristics**: +- Persistent storage in .task/IMPL-*.json files +- Complete dependency management (`depends_on` arrays) +- Two-phase structure: `pre_analysis` + `implementation_approach` +- Error handling strategies (`on_error` field) +- Target file specifications +- Variables: `[variable_name]` for cross-step references + +### JSON Format Field Specifications + +#### pre_analysis Field +**Purpose**: Context gathering phase before implementation + +**Structure**: Array of step objects with sequential execution + +**Step Fields**: +- **step**: Step identifier (string, e.g., "load_synthesis_specification") +- **action**: Human-readable description of the step +- **command** or **commands**: Single command string or array of command strings +- **output_to**: Variable name for storing step output +- **on_error**: Error handling strategy (`skip_optional`, `fail`, `retry_once`, `manual_intervention`) + +**Command Types Supported**: +- **Bash commands**: `bash(command)` - Any shell command +- **Tool calls**: `Read(file)`, `Glob(pattern)`, `Grep(pattern)` +- **MCP tools**: `mcp__code-index__find_files()`, `mcp__exa__get_code_context_exa()` +- **CLI wrappers**: `~/.claude/scripts/gemini-wrapper`, `codex --full-auto exec` + +**Example**: +```json +{ + "step": "load_context", + "action": "Load project context and patterns", + "commands": [ + "bash(~/.claude/scripts/get_modules_by_depth.sh)", + "Read(CLAUDE.md)" + ], + "output_to": "project_structure", + "on_error": "skip_optional" +} +``` + +#### implementation_approach Field +**Purpose**: Define implementation steps with dependency management + +**Structure**: Array of step objects (NOT object format) + +**Step Fields (All Required)**: +- **step**: Unique step number (1, 2, 3, ...) - serves as step identifier +- **title**: Brief step title +- **description**: Comprehensive implementation description with context variable references +- **modification_points**: Array of specific code modification targets +- **logic_flow**: Array describing business logic execution sequence +- **depends_on**: Array of step numbers this step depends on (e.g., `[1]`, `[1, 2]`) - empty array `[]` for independent steps +- **output**: Output variable name that can be referenced by subsequent steps via `[output_name]` + +**Optional Fields**: +- **command**: Command for step execution (supports any shell command or CLI tool) + - When omitted: Agent interprets modification_points and logic_flow to execute + - When specified: Command executes the step directly + +**Execution Modes**: +- **Default (without command)**: Agent executes based on modification_points and logic_flow +- **With command**: Specified command handles execution + +**Command Field Usage**: +- **Default approach**: Omit command field - let agent execute autonomously +- **CLI tools (codex/gemini/qwen)**: Add ONLY when user explicitly requests CLI tool usage +- **Simple commands**: Can include bash commands, test commands, validation scripts +- **Complex workflows**: Use command for multi-step operations or tool coordination + +**Command Format Examples** (only when explicitly needed): +```json +// Simple Bash +"command": "bash(npm install package)" +"command": "bash(npm test)" + +// Validation +"command": "bash(test -f config.ts && grep -q 'JWT_SECRET' config.ts)" + +// Codex (user requested) +"command": "codex -C path --full-auto exec \"task\" --skip-git-repo-check -s danger-full-access" + +// Codex Resume (user requested, maintains context) +"command": "codex --full-auto exec \"task\" resume --last --skip-git-repo-check -s danger-full-access" + +// Gemini (user requested) +"command": "~/.claude/scripts/gemini-wrapper -p \"analyze [context]\"" + +// Qwen (fallback for Gemini) +"command": "~/.claude/scripts/qwen-wrapper -p \"analyze [context]\"" +``` + +**Example Step**: +```json +{ + "step": 2, + "title": "Implement JWT generation", + "description": "Create JWT token generation logic using [auth_config]", + "modification_points": [ + "Add JWT generation function in auth service", + "Implement token signing with [auth_config]" + ], + "logic_flow": [ + "User login → validate credentials", + "Generate JWT payload with user data", + "Sign JWT using secret from [auth_config]", + "Return signed token" + ], + "depends_on": [1], + "output": "jwt_generator" +} +``` + +#### target_files Field +**Purpose**: Specify files to be modified or created + +**Format**: Array of strings +- **Existing files**: `"file:function:lines"` (e.g., `"src/auth/login.ts:handleLogin:75-120"`) +- **New files**: `"path/to/NewFile.ts"` (file path only) + +### Tool Reference + +**Available Command Types**: + +**Gemini CLI**: +```bash +~/.claude/scripts/gemini-wrapper -p "prompt" +~/.claude/scripts/gemini-wrapper --approval-mode yolo -p "prompt" # For write mode +``` + +**Qwen CLI** (Gemini fallback): +```bash +~/.claude/scripts/qwen-wrapper -p "prompt" +~/.claude/scripts/qwen-wrapper --approval-mode yolo -p "prompt" # For write mode +``` + +**Codex CLI**: +```bash +codex -C directory --full-auto exec "task" --skip-git-repo-check -s danger-full-access +codex --full-auto exec "task" resume --last --skip-git-repo-check -s danger-full-access +``` + +**Built-in Tools**: +- `Read(file_path)` - Read file contents +- `Glob(pattern)` - Find files by pattern +- `Grep(pattern)` - Search content with regex +- `bash(command)` - Execute bash command + +**MCP Tools**: +- `mcp__code-index__find_files(pattern="*.ts")` - Find files using code index +- `mcp__code-index__search_code_advanced(pattern="auth")` - Search code patterns +- `mcp__exa__get_code_context_exa(query="...")` - Get code context from Exa +- `mcp__exa__web_search_exa(query="...")` - Web search via Exa + +**Bash Commands**: +```bash +bash(rg 'pattern' src/) +bash(find . -name "*.ts") +bash(npm test) +bash(git log --oneline | head -5) +``` + +### Variable System & Context Flow + +**Variable Reference Syntax**: +Both formats use `[variable_name]` syntax for referencing outputs from previous steps. + +**Variable Types**: - **Step outputs**: `[step_output_name]` - Reference any pre_analysis step output - **Task properties**: `[task_property]` - Reference any task context field - **Previous results**: `[analysis_result]` - Reference accumulated context -- **Commands**: All commands wrapped with appropriate error handling +- **Implementation outputs**: Reference outputs from previous implementation steps + +**Examples**: +```json +// Reference pre_analysis output +"description": "Install JWT library following [synthesis_specification]" + +// Reference previous step output +"description": "Create middleware using [auth_config] and [jwt_generator]" + +// Reference task context +"command": "bash(cd [focus_paths] && npm test)" +``` **Context Accumulation Process**: 1. **Structure Analysis**: `get_modules_by_depth.sh` → project hierarchy @@ -248,16 +588,76 @@ The **flow_control** field manages task execution with two main components: - **Session → Task**: Global session context included in all tasks - **Module → Feature**: Module patterns inform feature implementation +### Agent Processing Rules + +**conceptual-planning-agent** (Inline Format): +- Parses markdown list from prompt +- Executes 3-5 simple loading steps +- No dependency resolution needed +- Accumulates context in variables +- Used only in brainstorm workflows + +**code-developer, test-fix-agent** (JSON Format): +- Loads complete task JSON from file +- Executes `pre_analysis` steps sequentially +- Processes `implementation_approach` with dependency resolution +- Handles complex variable substitution +- Updates task status in JSON file + +### Usage Guidelines + +**Use Inline Format When**: +- Running brainstorm workflows +- Need 3-5 simple context loading steps +- No persistence required +- No dependencies between steps +- Temporary context preparation + +**Use JSON Format When**: +- Implementing features or tasks +- Need 10+ complex execution steps +- Require dependency management +- Need persistent task definitions +- Complex variable flow between steps +- Error handling strategies needed + +### Variable Reference Syntax + +Both formats use `[variable_name]` syntax for referencing outputs: + +**Inline Format**: +```markdown +2. **analyze_context** + - Action: Analyze using [topic_framework] and [role_template] + - Output: analysis_results +``` + +**JSON Format**: +```json +{ + "step": 2, + "description": "Implement following [synthesis_specification] and [codebase_structure]", + "depends_on": [1], + "output": "implementation" +} +``` + ### Task Validation Rules 1. **ID Uniqueness**: All task IDs must be unique 2. **Hierarchical Format**: Must follow IMPL-N[.M] pattern (maximum 2 levels) 3. **Parent References**: All parent IDs must exist as JSON files 4. **Status Consistency**: Status values from defined enumeration -5. **Required Fields**: All 5 core fields must be present +5. **Required Fields**: All 5 core fields must be present (id, title, status, meta, context, flow_control) 6. **Focus Paths Structure**: context.focus_paths must contain concrete paths (no wildcards) 7. **Flow Control Format**: pre_analysis must be array with required fields -8. **Dependency Integrity**: All depends_on task IDs must exist as JSON files +8. **Dependency Integrity**: All task-level depends_on references must exist as JSON files 9. **Artifacts Structure**: context.artifacts (optional) must use valid type, priority, and path format +10. **Implementation Steps Array**: implementation_approach must be array of step objects +11. **Step Number Uniqueness**: All step numbers within a task must be unique and sequential (1, 2, 3, ...) +12. **Step Dependencies**: All step-level depends_on numbers must reference valid steps within same task +13. **Step Sequence**: Step numbers should match array order (first item step=1, second item step=2, etc.) +14. **Step Required Fields**: Each step must have step, title, description, modification_points, logic_flow, depends_on, output +15. **Step Optional Fields**: command field is optional - when omitted, agent executes based on modification_points and logic_flow ## Workflow Structure