feat: Add comprehensive test generation and evaluation commands

- Introduced `/workflow:test-gen` command to automate test workflow generation based on completed implementation tasks, including detailed lifecycle phases, task decomposition, and agent assignment.
- Implemented `/workflow:concept-eval` command for pre-planning evaluation of concepts, assessing feasibility, risks, and optimization recommendations using strategic and technical analysis tools.
- Added `/workflow:docs` command for generating hierarchical architecture and API documentation, with structured task creation and session management.
- Developed `/workflow:status` command to provide on-demand views of workflow state, supporting multiple formats and validation checks for task integrity and relationships.
This commit is contained in:
catlog22
2025-09-29 19:27:57 +08:00
parent c7ec9dd040
commit 84f4e47a50
14 changed files with 1150 additions and 1404 deletions

View File

@@ -0,0 +1,237 @@
# Workflow 命令模块化重构方案
## 📋 重构概览
### 目标
将现有workflow命令中的智能分析能力抽象为独立的、可复用的模块提升系统的模块化程度、可维护性和可扩展性。
### 核心原则
- **单一职责**:每个模块只负责一个核心功能
- **高内聚低耦合**:模块内部逻辑紧密,模块间接口清晰
- **可复用性**:智能模块可在多个场景下复用
- **向后兼容**:保持现有工作流程的功能完整性
## 🎯 模块化设计
### 1. 智能上下文模块 (`/context`)
**职责**:智能收集项目相关上下文信息
**核心命令**`/context:gather`
- **功能**:根据任务描述,从代码库、文档、历史记录中智能收集相关信息
- **输入**:任务描述字符串
- **输出**标准化的context-package.json文件
- **特性**
- 关键字分析和文档智能加载
- 代码结构分析使用get_modules_by_depth.sh
- 依赖关系发现
- MCP工具集成code-index, exa
**输出格式**
```json
{
"metadata": {
"task_description": "实现用户认证系统",
"timestamp": "2025-09-29T10:00:00Z",
"keywords": ["用户", "认证", "系统"]
},
"assets": [
{
"type": "documentation|source_code|config",
"path": "相对路径",
"relevance": "相关性描述"
}
]
}
```
### 2. 智能分析模块 (`/analysis`)
**职责**:基于上下文进行深度智能分析
**核心命令**`/analysis:run`
- **功能**:接收上下文包,执行深度分析,生成结构化报告
- **输入**context-package.json文件路径
- **输出**ANALYSIS_RESULTS.md文件
- **特性**
- 智能工具选择Gemini/Qwen/Codex
- 动态Prompt构建
- 结构化分析输出
### 3. 重构的协调器 (`/workflow:plan`)
**新职责**:编排智能模块,生成最终实施计划
**执行流程**
```
用户输入 → 创建会话 → context:gather → analysis:run → 生成IMPL_PLAN.md
```
## 📁 目录结构重组
### 当前结构问题
```
.claude/commands/workflow/
├── plan.md # 复杂混合逻辑
├── execute.md # 代理协调
├── status.md # 状态查看
├── docs.md # 文档生成
├── concept-eval.md # 概念评估
├── session/ # 会话管理 ✓
├── issue/ # 问题跟踪 ✓
└── brainstorm/ # 头脑风暴 ✓
```
### 重构后结构
```
.claude/commands/
├── workflow/
│ ├── pipeline/ # 核心流程
│ │ ├── plan.md # 重构为协调器
│ │ ├── verify.md # 计划验证
│ │ ├── execute.md # 执行协调
│ │ ├── resume.md # 恢复执行
│ │ ├── review.md # 代码审查
│ │ └── test-gen.md # 测试生成
│ ├── session/ # 会话管理(保持)
│ ├── issue/ # 问题跟踪(保持)
│ ├── brainstorm/ # 头脑风暴(保持)
│ └── tools/ # 辅助工具
│ ├── status.md
│ ├── docs.md
│ └── concept-eval.md
├── context/ # 新增:智能上下文
│ └── gather.md
├── analysis/ # 新增:智能分析
│ └── run.md
└── task/ # 任务管理(保持)
```
## 🔧 实施计划
### 阶段1创建新模块 (步骤1-4)
1. **创建模块目录**
- 创建 `.claude/commands/context/`
- 创建 `.claude/commands/analysis/`
2. **实现context:gather命令**
- 从workflow/plan.md提取上下文收集逻辑
- 实现标准化的context-package.json输出
3. **实现analysis:run命令**
- 从workflow/plan.md提取分析逻辑
- 实现ANALYSIS_RESULTS.md生成
4. **定义模块接口**
- 标准化输入输出格式
- 定义错误处理策略
### 阶段2重构现有命令 (步骤5-6)
5. **重构workflow:plan**
- 简化为协调器角色
- 调用新的智能模块
- 保持最终输出兼容性
6. **重组workflow目录**
- 创建pipeline/和tools/子目录
- 移动相应命令文件
- 更新命令路径引用
### 阶段3测试与优化 (步骤7)
7. **集成测试**
- 验证新模块功能
- 测试模块间协调
- 确保向后兼容
## 📋 详细实施清单
### 文件操作清单
**新建文件**
- `.claude/commands/context/gather.md`
- `.claude/commands/analysis/run.md`
- `.claude/commands/workflow/pipeline/` (目录)
- `.claude/commands/workflow/tools/` (目录)
**移动文件**
- `workflow/plan.md``workflow/pipeline/plan.md` (内容重构)
- `workflow/plan-verify.md``workflow/pipeline/verify.md`
- `workflow/execute.md``workflow/pipeline/execute.md`
- `workflow/resume.md``workflow/pipeline/resume.md`
- `workflow/review.md``workflow/pipeline/review.md`
- `workflow/test-gen.md``workflow/pipeline/test-gen.md`
- `workflow/status.md``workflow/tools/status.md`
- `workflow/docs.md``workflow/tools/docs.md`
- `workflow/concept-eval.md``workflow/tools/concept-eval.md`
**保持不变**
- `workflow/session/` (所有文件)
- `workflow/issue/` (所有文件)
- `workflow/brainstorm/` (所有文件)
- `task/` (所有文件)
## 🎯 预期收益
### 可复用性提升
- **context:gather** 可用于快速分析、调试诊断等场景
- **analysis:run** 可服务于不同类型的分析需求
### 可维护性提升
- 单一职责,逻辑清晰
- 独立测试和调试
- 更容易定位问题
### 可扩展性提升
- 新增分析引擎无需修改协调器
- 支持不同的上下文源
- 便于添加缓存、并行等优化
### 开发体验提升
- 命令职责更清晰
- 调试更容易
- 功能扩展更简单
## ⚠️ 风险管控
### 兼容性风险
- **缓解措施**:保持最终输出格式不变
- **验证方案**对比重构前后的IMPL_PLAN.md输出
### 性能风险
- **潜在影响**:模块调用可能增加执行时间
- **缓解措施**:优化模块间数据传递,避免重复读取
### 维护风险
- **潜在影响**:增加了命令间的依赖关系
- **缓解措施**:清晰的接口定义和错误处理
## 📈 成功标准
1. **功能完整性**所有原有workflow功能正常工作
2. **输出一致性**IMPL_PLAN.md等输出文件格式保持兼容
3. **性能可接受**执行时间增幅不超过20%
4. **可维护性**:新模块代码清晰,易于理解和修改
5. **可复用性**:智能模块可在其他场景成功复用
---
## 📝 更新日志
### v1.1 - 2025-09-29
- **✅ 完成**: Session管理逻辑模块化
- **改进**: 将Session Discovery & Selection从pipeline/plan.md移动到session/start.md
- **增强**: pipeline/plan.md现在调用专用的session管理命令
- **优化**: 实现了更清晰的职责分离
### v1.0 - 2025-09-29
- **✅ 完成**: 基础模块化架构实施
- **✅ 完成**: 智能上下文和分析模块创建
- **✅ 完成**: 目录结构重组
---
**文档版本**: v1.1
**创建日期**: 2025-09-29
**最后更新**: 2025-09-29
**负责人**: Claude Code Assistant
**状态**: 已实施并优化

View File

@@ -0,0 +1,345 @@
---
name: run
description: Analyze context packages using intelligent tools and generate structured analysis reports
usage: /analysis:run --session <session_id> --context <context_package_path>
argument-hint: "--session WFS-session-id --context path/to/context-package.json"
examples:
- /analysis:run --session WFS-auth --context .workflow/WFS-auth/.process/context-package.json
- /analysis:run --session WFS-payment --context .workflow/WFS-payment/.process/context-package.json
---
# Analysis Run Command (/analysis:run)
## Overview
Intelligent analysis engine that processes standardized context packages, executes deep analysis using multiple AI tools, and generates structured analysis reports.
## Core Philosophy
- **Context-Driven**: Precise analysis based on comprehensive context
- **Intelligent Tool Selection**: Choose optimal analysis tools based on task characteristics
- **Structured Output**: Generate standardized analysis reports
- **Configurable Analysis**: Support different depth and focus levels
## Core Responsibilities
- **Context Package Parsing**: Read and validate context-package.json
- **Multi-Tool Orchestration**: Execute parallel analysis using Gemini/Qwen/Codex
- **Perspective Synthesis**: Collect and organize different tool viewpoints
- **Consensus Analysis**: Identify agreements and conflicts between tools
- **Analysis Report Generation**: Output multi-perspective ANALYSIS_RESULTS.md (NOT implementation plan)
## Analysis Strategy Selection
### Tool Selection by Task Complexity
**Simple Tasks (≤3 modules)**:
- **Primary Tool**: Gemini (rapid understanding and pattern recognition)
- **Support Tool**: Code-index (structural analysis)
- **Execution Mode**: Single-round analysis, focus on existing patterns
**Medium Tasks (4-6 modules)**:
- **Primary Tool**: Qwen (architecture analysis and code generation)
- **Support Tools**: Gemini (pattern recognition) + Exa (external best practices)
- **Execution Mode**: Two-round analysis, architecture design + implementation strategy
**Complex Tasks (>6 modules)**:
- **Primary Tools**: Multi-tool collaboration (Gemini+Qwen+Codex)
- **Analysis Strategy**: Layered analysis with progressive refinement
- **Execution Mode**: Three-round analysis, understand + design + validate
### Tool Preferences by Tech Stack
```json
{
"frontend": {
"primary": "qwen",
"secondary": "gemini",
"focus": ["component_design", "state_management", "ui_patterns"]
},
"backend": {
"primary": "codex",
"secondary": "qwen",
"focus": ["api_design", "data_flow", "security", "performance"]
},
"fullstack": {
"primary": "gemini",
"secondary": "qwen+codex",
"focus": ["system_architecture", "integration", "data_consistency"]
}
}
```
## Execution Process
### Phase 1: Session & Context Package Analysis
1. **Session Validation**
```bash
# Validate session exists
if [ ! -d ".workflow/${session_id}" ]; then
echo "❌ Session ${session_id} not found"
exit 1
fi
# Load session metadata
session_metadata=".workflow/${session_id}/workflow-session.json"
```
2. **Package Validation**
```bash
# Validate context-package.json format
jq empty {context_package_path} || error "Invalid JSON format"
```
3. **Task Feature Extraction**
- Parse task description and keywords
- Load session task summaries for context
- Identify tech stack and complexity
- Determine analysis focus and objectives
4. **Resource Inventory**
- Count files by type
- Assess context size
- Define analysis scope
### Phase 2: Analysis Tool Selection & Preparation
1. **Intelligent Tool Selection**
```bash
# Select analysis tools based on complexity and tech stack
if [ "$complexity" = "simple" ]; then
analysis_tools=("gemini")
elif [ "$complexity" = "medium" ]; then
analysis_tools=("qwen" "gemini")
else
analysis_tools=("gemini" "qwen" "codex")
fi
```
2. **Prompt Template Selection**
- Choose analysis templates based on task type
- Customize prompts with context information
- Optimize token usage efficiency
### Phase 3: Multi-Tool Analysis Execution
1. **Gemini Analysis** (Understanding & Pattern Recognition)
```bash
cd "$project_root" && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Deep understanding of project architecture and existing patterns
TASK: Analyze ${task_description}
CONTEXT: $(cat ${context_package_path} | jq -r '.assets[] | select(.priority=="high") | .path' | head -10)
EXPECTED:
- Existing architecture pattern analysis
- Relevant code component identification
- Technical risk assessment
- Implementation complexity evaluation
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt) | Focus on existing patterns and integration points
"
```
2. **Qwen Analysis** (Architecture Design & Code Generation Strategy)
```bash
cd "$project_root" && ~/.claude/scripts/qwen-wrapper -p "
PURPOSE: Design implementation architecture and code structure
TASK: Design technical implementation plan for ${task_description}
CONTEXT: $(cat ${context_package_path} | jq -r '.assets[].path') + Gemini analysis results
EXPECTED:
- Detailed technical implementation architecture
- Code organization structure recommendations
- Interface design and data flow
- Specific implementation steps
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/feature.txt) | Design based on existing architecture
"
```
3. **Codex Analysis** (Implementation Feasibility & Technical Validation)
```bash
# Only used for complex tasks
if [ "$complexity" = "complex" ]; then
codex -C "$project_root" --full-auto exec "
PURPOSE: Validate technical implementation feasibility
TASK: Assess implementation risks and technical challenges for ${task_description}
CONTEXT: Project codebase + Gemini and Qwen analysis results
EXPECTED: Technical feasibility report and risk assessment
RULES: Focus on technical risks, performance impact, and maintenance costs
" -s danger-full-access
fi
```
### Phase 4: Multi-Perspective Analysis Integration
1. **Tool-Specific Result Organization**
- Organize Gemini analysis (understanding & patterns)
- Organize Qwen analysis (architecture & design)
- Organize Codex analysis (feasibility & validation)
2. **Perspective Synthesis**
- Identify consensus points across tools
- Document conflicting viewpoints
- Provide synthesis recommendations
3. **Analysis Report Generation**
- Generate multi-tool perspective ANALYSIS_RESULTS.md
- Preserve individual tool insights
- Provide consolidated recommendations (NOT detailed implementation plan)
## Analysis Results Format
Generated ANALYSIS_RESULTS.md format (Multi-Tool Perspective Analysis):
```markdown
# Multi-Tool Analysis Results
## Task Overview
- **Description**: {task_description}
- **Context Package**: {context_package_path}
- **Analysis Tools**: {tools_used}
- **Analysis Timestamp**: {timestamp}
## Tool-Specific Analysis
### 🧠 Gemini Analysis (Understanding & Pattern Recognition)
**Focus**: Existing codebase understanding and pattern identification
#### Current Architecture Assessment
- **Existing Patterns**: {identified_patterns}
- **Code Structure**: {current_structure}
- **Integration Points**: {integration_analysis}
- **Technical Debt**: {debt_assessment}
#### Compatibility Analysis
- **Framework Compatibility**: {framework_analysis}
- **Dependency Impact**: {dependency_analysis}
- **Migration Considerations**: {migration_notes}
### 🏗️ Qwen Analysis (Architecture Design & Code Generation)
**Focus**: Technical architecture and implementation design
#### Proposed Architecture
- **System Design**: {architectural_design}
- **Component Structure**: {component_design}
- **Data Flow**: {data_flow_design}
- **Interface Design**: {api_interface_design}
#### Implementation Strategy
- **Code Organization**: {code_structure_plan}
- **Module Dependencies**: {module_dependencies}
- **Testing Strategy**: {testing_approach}
### 🔧 Codex Analysis (Implementation & Technical Validation)
**Focus**: Implementation feasibility and technical validation
#### Feasibility Assessment
- **Technical Risks**: {implementation_risks}
- **Performance Impact**: {performance_analysis}
- **Resource Requirements**: {resource_assessment}
- **Maintenance Complexity**: {maintenance_analysis}
#### Implementation Recommendations
- **Tool Selection**: {recommended_tools}
- **Development Approach**: {development_strategy}
- **Quality Assurance**: {qa_recommendations}
## Synthesis & Consensus
### Consolidated Recommendations
- **Architecture Approach**: {consensus_architecture}
- **Implementation Priority**: {priority_recommendations}
- **Risk Mitigation**: {risk_mitigation_strategy}
### Tool Agreement Analysis
- **Consensus Points**: {agreed_recommendations}
- **Conflicting Views**: {conflicting_opinions}
- **Resolution Strategy**: {conflict_resolution}
### Task Decomposition Suggestions
1. **Primary Tasks**: {major_task_suggestions}
2. **Task Dependencies**: {dependency_mapping}
3. **Complexity Assessment**: {complexity_evaluation}
## Analysis Quality Metrics
- **Context Coverage**: {coverage_percentage}
- **Tool Consensus**: {consensus_level}
- **Analysis Depth**: {depth_assessment}
- **Confidence Score**: {overall_confidence}
```
## Error Handling & Fallbacks
### Common Error Handling
1. **Context Package Not Found**
```bash
if [ ! -f "$context_package_path" ]; then
echo "❌ Context package not found: $context_package_path"
echo "→ Run /context:gather first to generate context package"
exit 1
fi
```
2. **Tool Unavailability Handling**
```bash
# Use Qwen when Gemini is unavailable
if ! command -v ~/.claude/scripts/gemini-wrapper; then
echo "⚠️ Gemini not available, falling back to Qwen"
analysis_tools=("qwen")
fi
```
3. **Large Context Handling**
```bash
# Batch processing for large contexts
context_size=$(jq '.assets | length' "$context_package_path")
if [ "$context_size" -gt 50 ]; then
echo "⚠️ Large context detected, using batch analysis"
# Batch analysis logic
fi
```
## Performance Optimization
### Analysis Optimization Strategies
- **Parallel Analysis**: Execute multiple tools in parallel to reduce total time
- **Context Sharding**: Analyze large projects by module shards
- **Caching Mechanism**: Reuse analysis results for similar contexts
- **Incremental Analysis**: Perform incremental analysis based on changes
### Resource Management
```bash
# Set analysis timeout
timeout 600s analysis_command || {
echo "⚠️ Analysis timeout, generating partial results"
# Generate partial results
}
# Memory usage monitoring
memory_usage=$(ps -o pid,vsz,rss,comm -p $$)
if [ "$memory_usage" -gt "$memory_limit" ]; then
echo "⚠️ High memory usage detected, optimizing..."
fi
```
## Integration Points
### Input Interface
- **Required**: `--session` parameter specifying session ID (e.g., WFS-auth)
- **Required**: `--context` parameter specifying context package path
- **Optional**: `--depth` specify analysis depth (quick|full|deep)
- **Optional**: `--focus` specify analysis focus areas
### Output Interface
- **Primary**: ANALYSIS_RESULTS.md file
- **Location**: .workflow/{session_id}/.process/ANALYSIS_RESULTS.md
- **Secondary**: analysis-summary.json (machine-readable format)
## Quality Assurance
### Analysis Quality Checks
- **Completeness Check**: Ensure all required analysis sections are completed
- **Consistency Check**: Verify consistency of multi-tool analysis results
- **Feasibility Validation**: Ensure recommended implementation plans are feasible
### Success Criteria
- Generate complete ANALYSIS_RESULTS.md file
- Include specific feasible task decomposition recommendations
- Analysis results highly relevant to context
- Execution time within reasonable range (<10 minutes)
## Related Commands
- `/context:gather` - Generate context packages required by this command
- `/workflow:plan` - Call this command for analysis
- `/task:create` - Create specific tasks based on analysis results

View File

@@ -0,0 +1,263 @@
---
name: gather
description: Intelligently collect project context based on task description and package into standardized JSON
usage: /context:gather --session <session_id> "<task_description>"
argument-hint: "--session WFS-session-id \"task description\""
examples:
- /context:gather --session WFS-user-auth "Implement user authentication system"
- /context:gather --session WFS-payment "Refactor payment module API"
- /context:gather --session WFS-bugfix "Fix login validation error"
---
# Context Gather Command (/context:gather)
## Overview
Intelligent context collector that gathers relevant information from project codebase, documentation, and dependencies based on task descriptions, generating standardized context packages.
## Core Philosophy
- **Intelligent Collection**: Auto-identify relevant resources based on keyword analysis
- **Comprehensive Coverage**: Collect code, documentation, configurations, and dependencies
- **Standardized Output**: Generate unified format context-package.json
- **Efficient Execution**: Optimize collection strategies to avoid irrelevant information
## Core Responsibilities
- **Keyword Extraction**: Extract core keywords from task descriptions
- **Smart Documentation Loading**: Load relevant project documentation based on keywords
- **Code Structure Analysis**: Analyze project structure to locate relevant code files
- **Dependency Discovery**: Identify tech stack and dependency relationships
- **MCP Tools Integration**: Leverage code-index and exa tools for enhanced collection
- **Context Packaging**: Generate standardized JSON context packages
## Execution Process
### Phase 1: Task Analysis
1. **Keyword Extraction**
- Parse task description to extract core keywords
- Identify technical domain (auth, API, frontend, backend, etc.)
- Determine complexity level (simple, medium, complex)
2. **Scope Determination**
- Define collection scope based on keywords
- Identify potentially involved modules and components
- Set file type filters
### Phase 2: Project Structure Exploration
1. **Architecture Analysis**
```bash
# Get project structure
~/.claude/scripts/get_modules_by_depth.sh
```
2. **Code File Location**
```bash
# Use MCP tools for precise search
mcp__code-index__find_files(pattern="*{keywords}*")
mcp__code-index__search_code_advanced(pattern="{keywords}", file_pattern="*.{ts,js,py,go}")
```
3. **Documentation Collection**
- Load CLAUDE.md and README.md
- Load relevant documentation from .workflow/docs/ based on keywords
- Collect configuration files (package.json, requirements.txt, etc.)
### Phase 3: Intelligent Filtering & Association
1. **Relevance Scoring**
- Score based on keyword match degree
- Score based on file path relevance
- Score based on code content relevance
2. **Dependency Analysis**
- Analyze import/require statements
- Identify inter-module dependencies
- Determine core and optional dependencies
### Phase 4: External Context Enhancement (Optional)
1. **MCP Exa Integration**
```bash
# Get external best practices and examples
mcp__exa__get_code_context_exa(query="{task_type} {tech_stack} examples", tokensNum="dynamic")
```
2. **Tech Stack Analysis**
- Identify frameworks and libraries in use
- Gather relevant best practices
- Collect common patterns and examples
### Phase 5: Context Packaging
1. **Standardized Output**
- Generate context-package.json
- Organize resources by type and importance
- Add relevance descriptions and usage recommendations
## Context Package Format
Generated context package format:
```json
{
"metadata": {
"task_description": "Implement user authentication system",
"timestamp": "2025-09-29T10:30:00Z",
"keywords": ["user", "authentication", "JWT", "login"],
"complexity": "medium",
"tech_stack": ["typescript", "node.js", "express"],
"session_id": "WFS-user-auth"
},
"assets": [
{
"type": "documentation",
"path": "CLAUDE.md",
"relevance": "Project development standards and conventions",
"priority": "high"
},
{
"type": "documentation",
"path": ".workflow/docs/architecture/security.md",
"relevance": "Security architecture design guidance",
"priority": "high"
},
{
"type": "source_code",
"path": "src/auth/AuthService.ts",
"relevance": "Existing authentication service implementation",
"priority": "high"
},
{
"type": "source_code",
"path": "src/models/User.ts",
"relevance": "User data model definition",
"priority": "medium"
},
{
"type": "config",
"path": "package.json",
"relevance": "Project dependencies and tech stack",
"priority": "medium"
},
{
"type": "test",
"path": "tests/auth/*.test.ts",
"relevance": "Authentication related test cases",
"priority": "medium"
}
],
"external_context": {
"best_practices": "Best practices retrieved from exa",
"examples": "Relevant code examples and patterns",
"frameworks": "Recommended frameworks and libraries"
},
"statistics": {
"total_files": 15,
"source_files": 8,
"docs_files": 4,
"config_files": 2,
"test_files": 1
}
}
```
## Integration with MCP Tools
### Code Index Integration
```bash
# Set project path
mcp__code-index__set_project_path(path="{current_project_path}")
# Refresh index to ensure latest
mcp__code-index__refresh_index()
# Search relevant files
mcp__code-index__find_files(pattern="*{keyword}*")
# Search code content
mcp__code-index__search_code_advanced(
pattern="{keyword_patterns}",
file_pattern="*.{ts,js,py,go,md}",
context_lines=3
)
```
### Exa Integration
```bash
# Get external code context
mcp__exa__get_code_context_exa(
query="{task_type} {tech_stack} implementation examples",
tokensNum="dynamic"
)
# Get best practices
mcp__exa__get_code_context_exa(
query="{task_domain} best practices patterns",
tokensNum="dynamic"
)
```
## Session ID Integration
### Session ID Usage
- **Required Parameter**: `--session WFS-session-id`
- **Session Context Loading**: Load existing session state and task summaries
- **Session Continuity**: Maintain context across pipeline phases
### Session State Management
```bash
# Validate session exists
if [ ! -d ".workflow/${session_id}" ]; then
echo "❌ Session ${session_id} not found"
exit 1
fi
# Load session metadata
session_metadata=".workflow/${session_id}/workflow-session.json"
```
## Output Location
Context package output location:
```
.workflow/{session_id}/.process/context-package.json
```
## Error Handling
### Common Error Handling
1. **No Active Session**: Create temporary session directory
2. **MCP Tools Unavailable**: Fallback to traditional bash commands
3. **Permission Errors**: Prompt user to check file permissions
4. **Large Project Optimization**: Limit file count, prioritize high-relevance files
### Graceful Degradation Strategy
```bash
# Fallback when MCP unavailable
if ! command -v mcp__code-index__find_files; then
# Use find command
find . -name "*{keyword}*" -type f
fi
# Use ripgrep instead of MCP search
rg "{keywords}" --type-add 'source:*.{ts,js,py,go}' -t source
```
## Performance Optimization
### Large Project Optimization Strategy
- **File Count Limit**: Maximum 50 files per type
- **Size Filtering**: Skip oversized files (>10MB)
- **Depth Limit**: Maximum search depth of 3 levels
- **Caching Strategy**: Cache project structure analysis results
### Parallel Processing
- Documentation collection and code search in parallel
- MCP tool calls and traditional commands in parallel
- Reduce I/O wait time
## Success Criteria
- Generate valid context-package.json file
- Contains sufficient relevant information for subsequent analysis
- Execution time controlled within 30 seconds
- File relevance accuracy rate >80%
## Related Commands
- `/analysis:run` - Consumes output of this command for analysis
- `/workflow:plan` - Calls this command to gather context
- `/workflow:status` - Can display context collection status

View File

@@ -1,453 +0,0 @@
---
name: execute
description: Coordinate agents for existing workflow tasks with automatic discovery
usage: /workflow:execute
argument-hint: none
examples:
- /workflow:execute
---
# Workflow Execute Command
## Overview
Orchestrates autonomous workflow execution through systematic task discovery, agent coordination, and progress tracking. **Executes entire workflow without user interruption**, providing complete context to agents and ensuring proper flow control execution with comprehensive TodoWrite tracking.
## Core Rules
**Complete entire workflow autonomously without user interruption, using TodoWrite for comprehensive progress tracking.**
**Execute all discovered pending tasks sequentially until workflow completion or blocking dependency.**
## Core Responsibilities
- **Session Discovery**: Identify and select active workflow sessions
- **Task Dependency Resolution**: Analyze task relationships and execution order
- **TodoWrite Progress Tracking**: Maintain real-time execution status throughout entire workflow
- **Agent Orchestration**: Coordinate specialized agents with complete context
- **Flow Control Execution**: Execute pre-analysis steps and context accumulation
- **Status Synchronization**: Update task JSON files and workflow state
- **Autonomous Completion**: Continue execution until all tasks complete or reach blocking state
## Execution Philosophy
- **Discovery-first**: Auto-discover existing plans and tasks
- **Status-aware**: Execute only ready tasks with resolved dependencies
- **Context-rich**: Provide complete task JSON and accumulated context to agents
- **Progress tracking**: **Continuous TodoWrite updates throughout entire workflow execution**
- **Flow control**: Sequential step execution with variable passing
- **Autonomous completion**: **Execute all tasks without user interruption until workflow complete**
## Flow Control Execution
**[FLOW_CONTROL]** marker indicates sequential step execution required for context gathering and preparation. **These steps are executed BY THE AGENT, not by the workflow:execute command.**
### Flow Control Rules
1. **Auto-trigger**: When `task.flow_control.pre_analysis` array exists in task JSON, agents execute these steps
2. **Sequential Processing**: Agents execute steps in order, accumulating context
3. **Variable Passing**: Agents use `[variable_name]` syntax to reference step outputs
4. **Error Handling**: Agents follow step-specific error strategies (`fail`, `skip_optional`, `retry_once`)
### Execution Pattern
```
Step 1: load_dependencies → dependency_context
Step 2: analyze_patterns [dependency_context] → pattern_analysis
Step 3: implement_solution [pattern_analysis] [dependency_context] → implementation
```
### Context Accumulation Process (Executed by Agents)
- **Load Dependencies**: Agents retrieve summaries from `context.depends_on` tasks
- **Execute Analysis**: Agents run CLI tools with accumulated context
- **Prepare Implementation**: Agents build comprehensive context for implementation
- **Continue Implementation**: Agents use all accumulated context for task execution
## Execution Lifecycle
### Phase 1: Discovery
1. **Check Active Sessions**: Find `.workflow/.active-*` markers
2. **Select Session**: If multiple found, prompt user selection
3. **Load Session State**: Read `workflow-session.json` and `IMPL_PLAN.md`
4. **Scan Tasks**: Analyze `.task/*.json` files for ready tasks
### Phase 2: Analysis
1. **Dependency Resolution**: Build execution order based on `depends_on`
2. **Status Validation**: Filter tasks with `status: "pending"` and met dependencies
3. **Agent Assignment**: Determine agent type from `meta.agent` or `meta.type`
4. **Context Preparation**: Load dependency summaries and inherited context
### Phase 3: Planning
1. **Create TodoWrite List**: Generate task list with status markers
2. **Mark Initial Status**: Set first task as `in_progress`
3. **Prepare Session Context**: Inject workflow paths for agent use
4. **Prepare Complete Task JSON**: Include pre_analysis and flow control steps for agent consumption
5. **Validate Prerequisites**: Ensure all required context is available
### Phase 4: Execution
1. **Pass Task with Flow Control**: Include complete task JSON with `pre_analysis` steps for agent execution
2. **Launch Agent**: Invoke specialized agent with complete context including flow control steps
3. **Monitor Progress**: Track agent execution and handle errors without user interruption
4. **Collect Results**: Gather implementation results and outputs
5. **Continue Workflow**: Automatically proceed to next pending task until completion
### Phase 5: Completion
1. **Update Task Status**: Mark completed tasks in JSON files
2. **Generate Summary**: Create task summary in `.summaries/`
3. **Update TodoWrite**: Mark current task complete, advance to next
4. **Synchronize State**: Update session state and workflow status
## Task Discovery & Queue Building
### Session Discovery Process
```
├── Check for .active-* markers in .workflow/
├── If multiple active sessions found → Prompt user to select
├── Locate selected session's workflow folder
├── Load selected session's workflow-session.json and IMPL_PLAN.md
├── Scan selected session's .task/ directory for task JSON files
├── Analyze task statuses and dependencies for selected session only
└── Build execution queue of ready tasks from selected session
```
### Task Status Logic
```
pending + dependencies_met → executable
completed → skip
blocked → skip until dependencies clear
```
## TodoWrite Coordination
**Comprehensive workflow tracking** with immediate status updates throughout entire execution without user interruption:
#### TodoWrite Workflow Rules
1. **Initial Creation**: Generate TodoWrite from discovered pending tasks for entire workflow
2. **Single In-Progress**: Mark ONLY ONE task as `in_progress` at a time
3. **Immediate Updates**: Update status after each task completion without user interruption
4. **Status Synchronization**: Sync with JSON task files after updates
5. **Continuous Tracking**: Maintain TodoWrite throughout entire workflow execution until completion
#### TodoWrite Tool Usage
**Use Claude Code's built-in TodoWrite tool** to track workflow progress in real-time:
```javascript
// Create initial todo list from discovered pending tasks
TodoWrite({
todos: [
{
content: "Execute IMPL-1.1: Design auth schema [code-developer] [FLOW_CONTROL]",
status: "pending",
activeForm: "Executing IMPL-1.1: Design auth schema"
},
{
content: "Execute IMPL-1.2: Implement auth logic [code-developer] [FLOW_CONTROL]",
status: "pending",
activeForm: "Executing IMPL-1.2: Implement auth logic"
},
{
content: "Execute IMPL-2: Review implementations [code-review-agent]",
status: "pending",
activeForm: "Executing IMPL-2: Review implementations"
}
]
});
// Update status as tasks progress - ONLY ONE task should be in_progress at a time
TodoWrite({
todos: [
{
content: "Execute IMPL-1.1: Design auth schema [code-developer] [FLOW_CONTROL]",
status: "in_progress", // Mark current task as in_progress
activeForm: "Executing IMPL-1.1: Design auth schema"
},
// ... other tasks remain pending
]
});
```
**TodoWrite Integration Rules**:
- **Continuous Workflow Tracking**: Use TodoWrite tool throughout entire workflow execution
- **Real-time Updates**: Immediate progress tracking without user interruption
- **Single Active Task**: Only ONE task marked as `in_progress` at any time
- **Immediate Completion**: Mark tasks `completed` immediately after finishing
- **Status Sync**: Sync TodoWrite status with JSON task files after each update
- **Full Execution**: Continue TodoWrite tracking until all workflow tasks complete
#### TODO_LIST.md Update Timing
- **Before Agent Launch**: Update TODO_LIST.md to mark task as `in_progress` (⚠️)
- **After Task Complete**: Update TODO_LIST.md to mark as `completed` (✅), advance to next
- **On Error**: Keep as `in_progress` in TODO_LIST.md, add error note
- **Session End**: Sync all TODO_LIST.md statuses with JSON task files
### 3. Agent Context Management
**Comprehensive context preparation** for autonomous agent execution:
#### Context Sources (Priority Order)
1. **Complete Task JSON**: Full task definition including all fields
2. **Flow Control Context**: Accumulated outputs from pre_analysis steps
3. **Dependency Summaries**: Previous task completion summaries
4. **Session Context**: Workflow paths and session metadata
5. **Inherited Context**: Parent task context and shared variables
#### Context Assembly Process
```
1. Load Task JSON → Base context
2. Execute Flow Control → Accumulated context
3. Load Dependencies → Dependency context
4. Prepare Session Paths → Session context
5. Combine All → Complete agent context
```
#### Agent Context Package Structure
```json
{
"task": { /* Complete task JSON */ },
"flow_context": {
"step_outputs": { "pattern_analysis": "...", "dependency_context": "..." }
},
"session": {
"workflow_dir": ".workflow/WFS-session/",
"todo_list_path": ".workflow/WFS-session/TODO_LIST.md",
"summaries_dir": ".workflow/WFS-session/.summaries/",
"task_json_path": ".workflow/WFS-session/.task/IMPL-1.1.json"
},
"dependencies": [ /* Task summaries from depends_on */ ],
"inherited": { /* Parent task context */ }
}
```
#### Context Validation Rules
- **Task JSON Complete**: All 5 fields present and valid
- **Flow Control Ready**: All pre_analysis steps completed if present
- **Dependencies Loaded**: All depends_on summaries available
- **Session Paths Valid**: All workflow paths exist and accessible
- **Agent Assignment**: Valid agent type specified in meta.agent
### 4. Agent Execution Pattern
**Structured agent invocation** with complete context and clear instructions:
#### Agent Prompt Template
```bash
Task(subagent_type="{meta.agent}",
prompt="**TASK EXECUTION WITH FULL JSON LOADING**
## STEP 1: Load Complete Task JSON
**MANDATORY**: First load the complete task JSON from: {session.task_json_path}
cat {session.task_json_path}
**CRITICAL**: Validate all 5 required fields are present:
- id, title, status, meta, context, flow_control
## STEP 2: Task Definition (From Loaded JSON)
**ID**: Use id field from JSON
**Title**: Use title field from JSON
**Type**: Use meta.type field from JSON
**Agent**: Use meta.agent field from JSON
**Status**: Verify status is pending or active
## STEP 3: Flow Control Execution (if flow_control.pre_analysis exists)
**AGENT RESPONSIBILITY**: Execute pre_analysis steps sequentially from loaded JSON:
For each step in flow_control.pre_analysis array:
1. Execute step.command with variable substitution
2. Store output to step.output_to variable
3. Handle errors per step.on_error strategy
4. Pass accumulated variables to next step
## STEP 4: Implementation Context (From JSON context field)
**Requirements**: Use context.requirements array from JSON
**Focus Paths**: Use context.focus_paths array from JSON
**Acceptance Criteria**: Use context.acceptance array from JSON
**Dependencies**: Use context.depends_on array from JSON
**Parent Context**: Use context.inherited object from JSON
**Target Files**: Use flow_control.target_files array from JSON
**Implementation Approach**: Use flow_control.implementation_approach object from JSON
## STEP 5: Session Context (Provided by workflow:execute)
**Workflow Directory**: {session.workflow_dir}
**TODO List Path**: {session.todo_list_path}
**Summaries Directory**: {session.summaries_dir}
**Task JSON Path**: {session.task_json_path}
**Flow Context**: {flow_context.step_outputs}
## STEP 6: Agent Completion Requirements
1. **Load Task JSON**: Read and validate complete task structure
2. **Execute Flow Control**: Run all pre_analysis steps if present
3. **Implement Solution**: Follow implementation_approach from JSON
4. **Update Progress**: Mark task status in JSON as completed
5. **Update TODO List**: Update TODO_LIST.md at provided path
6. **Generate Summary**: Create completion summary in summaries directory
**JSON UPDATE COMMAND**:
Update task status to completed using jq:
jq '.status = \"completed\"' {session.task_json_path} > temp.json && mv temp.json {session.task_json_path}"),
description="Execute task with full JSON loading and validation")
```
#### Agent JSON Loading Specification
**MANDATORY AGENT PROTOCOL**: All agents must follow this exact loading sequence:
1. **JSON Loading**: First action must be `cat {session.task_json_path}`
2. **Field Validation**: Verify all 5 required fields exist: `id`, `title`, `status`, `meta`, `context`, `flow_control`
3. **Structure Parsing**: Parse nested fields correctly:
- `meta.type` and `meta.agent` (NOT flat `task_type`)
- `context.requirements`, `context.focus_paths`, `context.acceptance`
- `context.depends_on`, `context.inherited`
- `flow_control.pre_analysis` array, `flow_control.target_files`
4. **Flow Control Execution**: If `flow_control.pre_analysis` exists, execute steps sequentially
5. **Status Management**: Update JSON status upon completion
**JSON Field Reference**:
```json
{
"id": "IMPL-1.2",
"title": "Task title",
"status": "pending|active|completed|blocked",
"meta": {
"type": "feature|bugfix|refactor|test|docs",
"agent": "@code-developer|@planning-agent|@code-review-test-agent"
},
"context": {
"requirements": ["req1", "req2"],
"focus_paths": ["src/path1", "src/path2"],
"acceptance": ["criteria1", "criteria2"],
"depends_on": ["IMPL-1.1"],
"inherited": { "from": "parent", "context": ["info"] }
},
"flow_control": {
"pre_analysis": [
{
"step": "step_name",
"command": "bash_command",
"output_to": "variable",
"on_error": "skip_optional|fail|retry_once"
}
],
"implementation_approach": { "task_description": "...", "modification_points": ["..."] },
"target_files": ["file:function:lines"]
}
}
```
#### Execution Flow
1. **Load Task JSON**: Agent reads and validates complete JSON structure
2. **Execute Flow Control**: Agent runs pre_analysis steps if present
3. **Prepare Implementation**: Agent uses implementation_approach from JSON
4. **Launch Implementation**: Agent follows focus_paths and target_files
5. **Update Status**: Agent marks JSON status as completed
6. **Generate Summary**: Agent creates completion summary
#### Agent Assignment Rules
```
meta.agent specified → Use specified agent
meta.agent missing → Infer from meta.type:
- "feature" → @code-developer
- "test" → @code-review-test-agent
- "review" → @code-review-agent
- "docs" → @doc-generator
```
#### Error Handling During Execution
- **Agent Failure**: Retry once with adjusted context
- **Flow Control Error**: Skip optional steps, fail on critical
- **Context Missing**: Reload from JSON files and retry
- **Timeout**: Mark as blocked, continue with next task
## Workflow File Structure Reference
```
.workflow/WFS-[topic-slug]/
├── workflow-session.json # Session state and metadata
├── IMPL_PLAN.md # Planning document and requirements
├── TODO_LIST.md # Progress tracking (auto-updated)
├── .task/ # Task definitions (JSON only)
│ ├── IMPL-1.json # Main task definitions
│ └── IMPL-1.1.json # Subtask definitions
├── .summaries/ # Task completion summaries
│ ├── IMPL-1-summary.md # Task completion details
│ └── IMPL-1.1-summary.md # Subtask completion details
└── .process/ # Planning artifacts
└── ANALYSIS_RESULTS.md # Planning analysis results
```
## Error Handling & Recovery
### Discovery Phase Errors
| Error | Cause | Resolution | Command |
|-------|-------|------------|---------|
| No active session | No `.active-*` markers found | Create or resume session | `/workflow:plan "project"` |
| Multiple sessions | Multiple `.active-*` markers | Select specific session | Manual choice prompt |
| Corrupted session | Invalid JSON files | Recreate session structure | `/workflow:status --validate` |
| Missing task files | Broken task references | Regenerate tasks | `/task:create` or repair |
### Execution Phase Errors
| Error | Cause | Recovery Strategy | Max Attempts |
|-------|-------|------------------|--------------|
| Agent failure | Agent crash/timeout | Retry with simplified context | 2 |
| Flow control error | Command failure | Skip optional, fail critical | 1 per step |
| Context loading error | Missing dependencies | Reload from JSON, use defaults | 3 |
| JSON file corruption | File system issues | Restore from backup/recreate | 1 |
### Recovery Procedures
#### Session Recovery
```bash
# Check session integrity
find .workflow -name ".active-*" | while read marker; do
session=$(basename "$marker" | sed 's/^\.active-//')
if [ ! -d ".workflow/$session" ]; then
echo "Removing orphaned marker: $marker"
rm "$marker"
fi
done
# Recreate corrupted session files
if [ ! -f ".workflow/$session/workflow-session.json" ]; then
echo '{"session_id":"'$session'","status":"active"}' > ".workflow/$session/workflow-session.json"
fi
```
#### Task Recovery
```bash
# Validate task JSON integrity
for task_file in .workflow/$session/.task/*.json; do
if ! jq empty "$task_file" 2>/dev/null; then
echo "Corrupted task file: $task_file"
# Backup and regenerate or restore from backup
fi
done
# Fix missing dependencies
missing_deps=$(jq -r '.context.depends_on[]?' .workflow/$session/.task/*.json | sort -u)
for dep in $missing_deps; do
if [ ! -f ".workflow/$session/.task/$dep.json" ]; then
echo "Missing dependency: $dep - creating placeholder"
fi
done
```
#### Context Recovery
```bash
# Reload context from available sources
if [ -f ".workflow/$session/.process/ANALYSIS_RESULTS.md" ]; then
echo "Reloading planning context..."
fi
# Restore from documentation if available
if [ -d ".workflow/docs/" ]; then
echo "Using documentation context as fallback..."
fi
```
### Error Prevention
- **Pre-flight Checks**: Validate session integrity before execution
- **Backup Strategy**: Create task snapshots before major operations
- **Atomic Updates**: Update JSON files atomically to prevent corruption
- **Dependency Validation**: Check all depends_on references exist
- **Context Verification**: Ensure all required context is available
## Usage Examples
### Basic Usage
```bash
/workflow:execute # Execute all pending tasks autonomously
/workflow:status # Check progress
/task:execute IMPL-1.2 # Execute specific task
```
### Integration
- **Planning**: `/workflow:plan``/workflow:execute``/workflow:review`
- **Recovery**: `/workflow:status --validate``/workflow:execute`

View File

@@ -0,0 +1,245 @@
---
name: plan
description: Create implementation plans by orchestrating intelligent context gathering and analysis modules
usage: /workflow:plan <input>
argument-hint: "text description"|file.md|ISS-001
examples:
- /workflow:plan "Build authentication system"
- /workflow:plan requirements.md
- /workflow:plan ISS-001
---
# Workflow Plan Command (/workflow:plan)
## Overview
Creates implementation plans by orchestrating intelligent context gathering and analysis modules.
## Core Principles
### Task Decomposition Standards
**Core Principle: Task Merging Over Decomposition**
- **Merge Rule**: Tasks that can be executed together should not be separated - avoid unnecessary decomposition
- **Decomposition Criteria**: Only decompose tasks in the following situations:
- **Excessive Workload**: Code exceeds 2500 lines or modifies more than 6 files
- **Context Separation**: Involves completely different tech stacks or business domains
- **Dependency Blocking**: Subsequent tasks must wait for prerequisite task completion
- **Parallel Execution**: Independent features that can be developed simultaneously by different developers
**Rules**:
- **Maximum 10 tasks**: Hard limit - exceeding requires re-scoping
- **Function-based**: Complete functional units with related files (logic + UI + tests + config)
- **File cohesion**: Group tightly coupled components in same task
- **Hierarchy**: Flat (≤5 tasks) | Two-level (6-10 tasks) | Re-scope (>10 tasks)
**Task Patterns**:
-**Correct (Function-based)**: `IMPL-001: User authentication system` (models + routes + components + middleware + tests)
-**Wrong (File/step-based)**: `IMPL-001: Create database model`, `IMPL-002: Create API endpoint`
### Task JSON Creation Process
**Task JSON Generation Philosophy**:
1. **Analysis-Driven**: Task definitions generated from intelligent analysis results
2. **Context-Rich**: Each task includes comprehensive context for autonomous execution
3. **Flow-Control Ready**: Pre-analysis steps and implementation approach pre-defined
4. **Agent-Optimized**: Complete context provided for specialized agent execution
**Automatic Task Generation Workflow**:
1. **Parse Analysis Results**: Extract task recommendations from ANALYSIS_RESULTS.md
2. **Extract Task Details**: Parse task ID, title, scope, complexity from structured analysis
3. **Generate Context**: Create requirements, focus_paths, and acceptance criteria
4. **Build Flow Control**: Define pre_analysis steps and implementation approach
5. **Create JSON Files**: Generate individual .task/IMPL-*.json files with 5-field schema
### Session Management ⚠️ CRITICAL
- **Command**: Uses `/workflow:session:start` command for intelligent session discovery and creation
- **⚡ FIRST ACTION**: Check for all `.workflow/.active-*` markers before any planning
- **Relevance Analysis**: Automatically analyzes task relevance with existing sessions
- **Auto-session creation**: `WFS-[topic-slug]` only if no active session exists or task is unrelated
- **Session continuity**: MUST use selected active session to maintain context
- **⚠️ Dependency context**: MUST read ALL previous task summary documents from selected session before planning
- **Session isolation**: Each session maintains independent context and state
### Session ID Transmission Guidelines ⚠️ CRITICAL
- **Format**: `WFS-[topic-slug]` from active session markers
- **Usage**: `/context:gather --session WFS-[id]` and `/analysis:run --session WFS-[id]`
- **Rule**: ALL modular commands MUST receive current session ID for context continuity
## Execution Lifecycle
### Phase 1: Session Management
1. **Session Discovery**: Use `/workflow:session:start` command for intelligent session discovery
2. **Relevance Analysis**: Automatically analyze task relevance with existing sessions
3. **Session Selection**: Auto-select or create session based on relevance analysis
4. **Context Preparation**: Load session state and prepare for planning
### Phase 2: Context Gathering
1. **Context Collection**: Execute `/context:gather` with task description and session ID
2. **Asset Discovery**: Gather relevant documentation, code, and configuration files
3. **Context Packaging**: Generate standardized context-package.json
4. **Validation**: Ensure context package contains sufficient information
### Phase 3: Intelligent Analysis
1. **Analysis Execution**: Run `/analysis:run` with context package and session ID
2. **Tool Selection**: Automatically select optimal analysis tools (Gemini/Qwen/Codex)
3. **Result Generation**: Produce structured ANALYSIS_RESULTS.md
4. **Validation**: Verify analysis completeness and task recommendations
### Phase 4: Plan Assembly & Document Generation
1. **Plan Generation**: Create IMPL_PLAN.md from analysis results
2. **Task JSON Creation**: Generate individual task JSON files with 5-field schema
3. **TODO List Creation**: Generate TODO_LIST.md with document format
4. **Session Update**: Mark session as ready for execution
## TodoWrite Progress Tracking
**Comprehensive planning tracking** with real-time status updates throughout entire planning lifecycle:
### TodoWrite Planning Rules
1. **Initial Creation**: Generate TodoWrite from planning phases
2. **Single In-Progress**: Mark ONLY ONE phase as `in_progress` at a time
3. **Immediate Updates**: Update status after each phase completion
4. **Continuous Tracking**: Maintain TodoWrite throughout entire planning workflow
### TodoWrite Tool Usage
```javascript
// Initialize planning workflow tracking
TodoWrite({
todos: [
{"content": "Initialize session management", "status": "pending", "activeForm": "Initializing session management"},
{"content": "Gather intelligent context", "status": "pending", "activeForm": "Gathering intelligent context"},
{"content": "Execute intelligent analysis", "status": "pending", "activeForm": "Executing intelligent analysis"},
{"content": "Generate implementation plan and tasks", "status": "pending", "activeForm": "Generating implementation plan and tasks"}
]
})
```
### IMPL_PLAN.md Structure ⚠️ REQUIRED FORMAT
**File Header** (required)
- **Identifier**: Unique project identifier and session ID, format WFS-[topic]
- **Source**: Input type, e.g. "User requirements analysis"
- **Analysis**: Analysis document reference
**Summary** (execution overview)
- Concise description of core requirements and objectives
- Technical direction and implementation approach
**Context Analysis** (context analysis)
- **Project** - Project type and architectural patterns
- **Modules** - Involved modules and component list
- **Dependencies** - Dependency mapping and constraints
- **Patterns** - Identified code patterns and conventions
**Task Breakdown** (task decomposition)
- **Task Count** - Total task count and complexity level
- **Hierarchy** - Task organization structure (flat/hierarchical)
- **Dependencies** - Inter-task dependency graph
**Implementation Plan** (implementation plan)
- **Execution Strategy** - Execution strategy and methodology
- **Resource Requirements** - Required resources and tool selection
- **Success Criteria** - Success criteria and acceptance conditions
## Reference Information
### Task JSON Schema (5-Field Architecture)
Each task.json uses the workflow-architecture.md 5-field schema:
- **id**: IMPL-N[.M] format (max 2 levels)
- **title**: Descriptive task name
- **status**: pending|active|completed|blocked|container
- **meta**: { type, agent }
- **context**: { requirements, focus_paths, acceptance, parent, depends_on, inherited, shared_context }
- **flow_control**: { pre_analysis[], implementation_approach, target_files[] }
**MCP Tools Integration**: Enhanced with optional MCP servers for advanced analysis:
- **Code Index MCP**: `mcp__code-index__find_files()`, `mcp__code-index__search_code_advanced()`
- **Exa MCP**: `mcp__exa__get_code_context_exa()` for external patterns
### Context Management & Agent Execution
**Agent Context Loading** ⚠️ CRITICAL
The following pre_analysis steps are generated for agent execution:
```json
// Example pre_analysis steps generated by /workflow:plan for agent execution
"flow_control": {
"pre_analysis": [
{
"step": "load_planning_context",
"action": "Load plan-generated analysis and context",
"commands": [
"Read(.workflow/WFS-[session]/.process/ANALYSIS_RESULTS.md)",
"Read(.workflow/WFS-[session]/.process/context-package.json)"
],
"output_to": "planning_context"
},
{
"step": "load_context_assets",
"action": "Load structured assets from context package",
"command": "Read(.workflow/WFS-[session]/.process/context-package.json)",
"output_to": "context_assets"
},
{
"step": "mcp_codebase_exploration",
"action": "Explore codebase structure and patterns using MCP tools",
"command": "mcp__code-index__find_files(pattern=\"[task_focus_patterns]\") && mcp__code-index__search_code_advanced(pattern=\"[relevant_patterns]\", file_pattern=\"[target_extensions]\")",
"output_to": "codebase_structure"
},
{
"step": "mcp_external_context",
"action": "Get external API examples and best practices",
"command": "mcp__exa__get_code_context_exa(query=\"[task_technology] [task_patterns]\", tokensNum=\"dynamic\")",
"output_to": "external_context"
},
{
"step": "load_dependencies",
"action": "Retrieve dependency task summaries",
"command": "bash(cat .workflow/WFS-[session]/.summaries/IMPL-[dependency_id]-summary.md 2>/dev/null || echo 'dependency summary not found')",
"output_to": "dependency_context"
},
{
"step": "load_base_documentation",
"action": "Load core documentation files",
"commands": [
"bash(cat .workflow/docs/README.md 2>/dev/null || echo 'base docs not found')",
"bash(cat CLAUDE.md README.md 2>/dev/null || echo 'project docs not found')"
],
"output_to": "base_docs"
},
{
"step": "load_task_specific_docs",
"action": "Load documentation relevant to task type",
"commands": [
"bash(cat .workflow/docs/architecture/*.md 2>/dev/null || echo 'architecture docs not found')",
"bash(cat .workflow/docs/api/*.md 2>/dev/null || echo 'api docs not found')"
],
"output_to": "task_docs"
},
{
"step": "analyze_task_patterns",
"action": "Analyze existing code patterns for task context",
"commands": [
"bash(cd \"[task_focus_paths]\")",
"bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Analyze task patterns TASK: Review '[task_title]' patterns CONTEXT: Task [task_id] in [task_focus_paths] EXPECTED: Pattern analysis RULES: Focus on existing patterns\")"
],
"output_to": "task_context",
"on_error": "fail"
}
]
}
```
### File Structure Reference
**Architecture**: @~/.claude/workflows/workflow-architecture.md
### Execution Integration
Documents created for `/workflow:execute`:
- **IMPL_PLAN.md**: Context loading and requirements
- **.task/*.json**: Agent implementation context
- **TODO_LIST.md**: Status tracking (container tasks with ▸, leaf tasks with checkboxes)

View File

@@ -1,550 +0,0 @@
---
name: plan-verify
description: Cross-validate action plans using gemini and codex analysis before execution
usage: /workflow:plan-verify
argument-hint: none
examples:
- /workflow:plan-verify
allowed-tools: Task(*), TodoWrite(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*)
---
# Workflow Plan Verify Command
## Overview
Cross-validates existing workflow plans using gemini and codex analysis to ensure plan quality, feasibility, and completeness before execution. **Works between `/workflow:plan` and `/workflow:execute`** to catch potential issues early and suggest improvements.
## Core Responsibilities
- **Session Discovery**: Identify active workflow sessions with completed plans
- **Dual Analysis**: Independent gemini and codex plan evaluation
- **Cross-Validation**: Compare analyses to identify consensus and conflicts
- **Modification Suggestions**: Generate actionable improvement recommendations
- **User Approval**: Interactive approval process for suggested changes
- **Plan Updates**: Apply approved modifications to workflow documents
## Execution Philosophy
- **Quality Assurance**: Comprehensive plan validation before implementation
- **Dual Perspective**: Technical feasibility (codex) + strategic assessment (gemini)
- **User Control**: All modifications require explicit user approval
- **Non-Destructive**: Original plans preserved with versioned updates
- **Context-Rich**: Full workflow context provided to both analysis tools
## Core Workflow
### Verification Process
The command performs comprehensive cross-validation through:
**0. Session Management** ⚠️ FIRST STEP
- **Active session detection**: Check `.workflow/.active-*` markers
- **Session validation**: Ensure session has completed IMPL_PLAN.md
- **Plan readiness check**: Verify tasks exist in `.task/` directory
- **Context availability**: Confirm analysis artifacts are present
**1. Context Preparation & Analysis Setup**
- **Plan context loading**: Load IMPL_PLAN.md, task definitions, and analysis results
- **Documentation gathering**: Collect relevant CLAUDE.md, README.md, and workflow docs
- **Dependency mapping**: Analyze task relationships and constraints
- **Validation criteria setup**: Establish evaluation framework
**2. Parallel Dual Analysis** ⚠️ CRITICAL ARCHITECTURE
- **Gemini Analysis**: Strategic and architectural plan evaluation
- **Codex Analysis**: Technical feasibility and implementation assessment
- **Independent execution**: Both tools analyze simultaneously with full context
- **Comprehensive evaluation**: Each tool evaluates different aspects
**3. Cross-Validation & Synthesis**
- **Consensus identification**: Areas where both analyses agree
- **Conflict analysis**: Discrepancies between gemini and codex evaluations
- **Risk assessment**: Combined evaluation of potential issues
- **Improvement opportunities**: Synthesized recommendations
**4. Interactive Approval Process**
- **Results presentation**: Clear display of findings and suggestions
- **User decision points**: Approval/rejection of each modification category
- **Selective application**: User controls which changes to implement
- **Confirmation workflow**: Multi-step approval for significant changes
## Implementation Standards
### Dual Analysis Architecture ⚠️ CRITICAL
Both tools receive identical context but focus on different validation aspects:
```json
{
"gemini_analysis": {
"focus": "strategic_validation",
"aspects": [
"architectural_soundness",
"task_decomposition_logic",
"dependency_coherence",
"business_alignment",
"risk_identification"
],
"context_sources": [
"IMPL_PLAN.md",
".process/ANALYSIS_RESULTS.md",
"CLAUDE.md",
".workflow/docs/"
]
},
"codex_analysis": {
"focus": "technical_feasibility",
"aspects": [
"implementation_complexity",
"technical_dependencies",
"code_structure_assessment",
"testing_completeness",
"execution_readiness"
],
"context_sources": [
".task/*.json",
"target_files from flow_control",
"existing codebase patterns",
"technical documentation"
]
}
}
```
### Analysis Execution Pattern
**Gemini Strategic Analysis**:
```bash
~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Strategic validation of workflow implementation plan
TASK: Evaluate plan architecture, task decomposition, and business alignment
CONTEXT: @{.workflow/WFS-*/IMPL_PLAN.md,.workflow/WFS-*/.process/ANALYSIS_RESULTS.md,CLAUDE.md}
EXPECTED: Strategic assessment with architectural recommendations
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/verification/gemini-strategic.txt) | Focus on strategic soundness and risk identification
"
```
**Codex Technical Analysis**:
```bash
codex --full-auto exec "
PURPOSE: Technical feasibility assessment of workflow implementation plan
TASK: Evaluate implementation complexity, dependencies, and execution readiness
CONTEXT: @{.workflow/WFS-*/.task/*.json,CLAUDE.md,README.md} Target files and flow control definitions
EXPECTED: Technical assessment with implementation recommendations
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/verification/codex-technical.txt) | Focus on technical feasibility and code quality
" -s danger-full-access
```
**Cross-Validation Analysis**:
```bash
~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Cross-validate and synthesize strategic and technical assessments
TASK: Compare analyses, resolve conflicts, and generate integrated recommendations
CONTEXT: @{.workflow/WFS-*/.verification/gemini-analysis.md,.workflow/WFS-*/.verification/codex-analysis.md}
EXPECTED: Synthesized recommendations with user approval framework
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/verification/cross-validation.txt) | Focus on balanced integration and user decision points
"
```
### Cross-Validation Matrix
**Validation Categories**:
1. **Task Decomposition**: Is breakdown logical and complete?
2. **Dependency Management**: Are task relationships correctly modeled?
3. **Implementation Scope**: Is each task appropriately sized?
4. **Technical Feasibility**: Are implementation approaches viable?
5. **Context Completeness**: Do tasks have adequate context?
6. **Testing Coverage**: Are testing requirements sufficient?
7. **Documentation Quality**: Are requirements clear and complete?
**Consensus Analysis**:
- **Agreement Areas**: Both tools identify same strengths/issues
- **Divergent Views**: Different perspectives requiring user decision
- **Risk Levels**: Combined assessment of implementation risks
- **Priority Recommendations**: Most critical improvements identified
### User Approval Workflow
**Interactive Approval Process**:
1. **Results Presentation**: Show analysis summary and key findings
2. **Category-based Approval**: Present modifications grouped by type
3. **Impact Assessment**: Explain consequences of each change
4. **Selective Implementation**: User chooses which changes to apply
5. **Confirmation Steps**: Final review before plan modification
**Step-by-Step User Interaction**:
**Step 1: Present Analysis Summary**
```
## Verification Results for WFS-[session-name]
### Analysis Summary
- **Gemini Strategic Grade**: B+ (Strong architecture, minor business alignment issues)
- **Codex Technical Grade**: A- (High implementation feasibility, good code structure)
- **Combined Risk Level**: Medium (Dependency complexity, timeline concerns)
- **Overall Recommendation**: Proceed with modifications
### Key Findings
✅ **Strengths Identified**: Task decomposition logical, technical approach sound
⚠️ **Areas for Improvement**: Missing error handling, unclear success criteria
❌ **Critical Issues**: Circular dependency in IMPL-3 → IMPL-1 chain
```
**Step 2: Category-based Modification Approval**
```bash
# Interactive prompts for each category
echo "Review the following modification categories:"
echo ""
echo "=== CRITICAL CHANGES (Must be addressed) ==="
read -p "1. Fix circular dependency IMPL-3 → IMPL-1? [Y/n]: " fix_dependency
read -p "2. Add missing error handling context to IMPL-2? [Y/n]: " add_error_handling
echo ""
echo "=== IMPORTANT IMPROVEMENTS (Recommended) ==="
read -p "3. Merge granular tasks IMPL-1.1 + IMPL-1.2? [Y/n]: " merge_tasks
read -p "4. Enhance success criteria for IMPL-4? [Y/n]: " enhance_criteria
echo ""
echo "=== OPTIONAL ENHANCEMENTS (Nice to have) ==="
read -p "5. Add API documentation task? [y/N]: " add_docs_task
read -p "6. Include performance testing in IMPL-3? [y/N]: " add_perf_tests
```
**Step 3: Impact Assessment Display**
For each approved change, show detailed impact:
```
Change: Merge tasks IMPL-1.1 + IMPL-1.2
Impact:
- Files affected: .task/IMPL-1.1.json, .task/IMPL-1.2.json → .task/IMPL-1.json
- Dependencies: IMPL-2.depends_on changes from ["IMPL-1.1", "IMPL-1.2"] to ["IMPL-1"]
- Estimated time: Reduces from 8h to 6h (reduced coordination overhead)
- Risk: Low (combining related functionality)
```
**Step 4: Modification Confirmation**
```bash
echo "Summary of approved changes:"
echo "✓ Fix circular dependency IMPL-3 → IMPL-1"
echo "✓ Add error handling context to IMPL-2"
echo "✓ Merge tasks IMPL-1.1 + IMPL-1.2"
echo "✗ Enhance success criteria for IMPL-4 (user declined)"
echo ""
read -p "Apply these modifications to the workflow plan? [Y/n]: " final_approval
if [[ "$final_approval" =~ ^[Yy]$ ]] || [[ -z "$final_approval" ]]; then
echo "Creating backups and applying modifications..."
else
echo "Modifications cancelled. Original plan preserved."
fi
```
**Approval Categories**:
```markdown
## Verification Results Summary
### ✅ Consensus Recommendations (Both gemini and codex agree)
- [ ] **Task Decomposition**: Merge IMPL-1.1 and IMPL-1.2 (too granular)
- [ ] **Dependencies**: Add missing dependency IMPL-3 → IMPL-4
- [ ] **Context**: Enhance context.requirements for IMPL-2
### ⚠️ Conflicting Assessments (gemini vs codex differ)
- [ ] **Scope**: gemini suggests splitting IMPL-5, codex suggests keeping merged
- [ ] **Testing**: gemini prioritizes integration tests, codex emphasizes unit tests
### 🔍 Individual Tool Recommendations
#### Gemini (Strategic)
- [ ] **Architecture**: Consider API versioning strategy
- [ ] **Risk**: Add rollback plan for database migrations
#### Codex (Technical)
- [ ] **Implementation**: Use existing auth patterns in /src/auth/
- [ ] **Dependencies**: Update package.json dependencies first
```
## Document Generation & Modification
**Verification Workflow**: Analysis → Cross-Validation → User Approval → Plan Updates → Versioning
**Always Created**:
- **VERIFICATION_RESULTS.md**: Complete analysis results and recommendations
- **verification-session.json**: Analysis metadata and user decisions
- **PLAN_MODIFICATIONS.md**: Record of approved changes
**Auto-Created (if modifications approved)**:
- **IMPL_PLAN.md.backup**: Original plan backup before modifications
- **Updated task JSONs**: Modified .task/*.json files with improvements
- **MODIFICATION_LOG.md**: Detailed change log with timestamps
**Document Structure**:
```
.workflow/WFS-[topic]/.verification/
├── verification-session.json # Analysis session metadata
├── VERIFICATION_RESULTS.md # Complete analysis results
├── PLAN_MODIFICATIONS.md # Approved changes record
├── gemini-analysis.md # Gemini strategic analysis
├── codex-analysis.md # Codex technical analysis
├── cross-validation-matrix.md # Comparison analysis
└── backups/
├── IMPL_PLAN.md.backup # Original plan backup
└── task-backups/ # Original task JSON backups
```
### Modification Implementation
**Safe Modification Process**:
1. **Backup Creation**: Save original files before any changes
2. **Atomic Updates**: Apply all approved changes together
3. **Validation**: Verify modified plans are still valid
4. **Rollback Capability**: Easy restoration if issues arise
**Implementation Commands**:
**Step 1: Create Backups**
```bash
# Create backup directory with timestamp
backup_dir=".workflow/WFS-$session/.verification/backups/$(date +%Y%m%d_%H%M%S)"
mkdir -p "$backup_dir/task-backups"
# Backup main plan and task files
cp IMPL_PLAN.md "$backup_dir/IMPL_PLAN.md.backup"
cp -r .task/ "$backup_dir/task-backups/"
# Create backup manifest
echo "Backup created at $(date)" > "$backup_dir/backup-manifest.txt"
echo "Session: $session" >> "$backup_dir/backup-manifest.txt"
echo "Files backed up:" >> "$backup_dir/backup-manifest.txt"
ls -la IMPL_PLAN.md .task/*.json >> "$backup_dir/backup-manifest.txt"
```
**Step 2: Apply Approved Modifications**
```bash
# Example: Merge tasks IMPL-1.1 + IMPL-1.2
if [[ "$merge_tasks" =~ ^[Yy]$ ]]; then
echo "Merging IMPL-1.1 and IMPL-1.2..."
# Combine task contexts
jq -s '
{
"id": "IMPL-1",
"title": (.[0].title + " and " + .[1].title),
"status": "pending",
"meta": .[0].meta,
"context": {
"requirements": (.[0].context.requirements + " " + .[1].context.requirements),
"focus_paths": (.[0].context.focus_paths + .[1].context.focus_paths | unique),
"acceptance": (.[0].context.acceptance + .[1].context.acceptance),
"depends_on": (.[0].context.depends_on + .[1].context.depends_on | unique)
},
"flow_control": {
"target_files": (.[0].flow_control.target_files + .[1].flow_control.target_files | unique),
"implementation_approach": .[0].flow_control.implementation_approach
}
}
' .task/IMPL-1.1.json .task/IMPL-1.2.json > .task/IMPL-1.json
# Remove old task files
rm .task/IMPL-1.1.json .task/IMPL-1.2.json
# Update dependent tasks
for task_file in .task/*.json; do
jq '
if .context.depends_on then
.context.depends_on = [
.context.depends_on[] |
if . == "IMPL-1.1" or . == "IMPL-1.2" then "IMPL-1"
else .
end
] | unique
else . end
' "$task_file" > "$task_file.tmp" && mv "$task_file.tmp" "$task_file"
done
fi
# Example: Fix circular dependency
if [[ "$fix_dependency" =~ ^[Yy]$ ]]; then
echo "Fixing circular dependency IMPL-3 → IMPL-1..."
# Remove problematic dependency
jq 'if .id == "IMPL-3" then .context.depends_on = (.context.depends_on - ["IMPL-1"]) else . end' \
.task/IMPL-3.json > .task/IMPL-3.json.tmp && mv .task/IMPL-3.json.tmp .task/IMPL-3.json
fi
# Example: Add error handling context
if [[ "$add_error_handling" =~ ^[Yy]$ ]]; then
echo "Adding error handling context to IMPL-2..."
jq '.context.requirements += " Include comprehensive error handling and user feedback for all failure scenarios."' \
.task/IMPL-2.json > .task/IMPL-2.json.tmp && mv .task/IMPL-2.json.tmp .task/IMPL-2.json
fi
```
**Step 3: Validation and Cleanup**
```bash
# Validate modified JSON files
echo "Validating modified task files..."
for task_file in .task/*.json; do
if ! jq empty "$task_file" 2>/dev/null; then
echo "ERROR: Invalid JSON in $task_file - restoring backup"
cp "$backup_dir/task-backups/$(basename $task_file)" "$task_file"
else
echo "$task_file is valid"
fi
done
# Update IMPL_PLAN.md with modification summary
cat >> IMPL_PLAN.md << EOF
## Plan Verification and Modifications
**Verification Date**: $(date)
**Modifications Applied**:
$(if [[ "$merge_tasks" =~ ^[Yy]$ ]]; then echo "- Merged IMPL-1.1 and IMPL-1.2 for better cohesion"; fi)
$(if [[ "$fix_dependency" =~ ^[Yy]$ ]]; then echo "- Fixed circular dependency in IMPL-3"; fi)
$(if [[ "$add_error_handling" =~ ^[Yy]$ ]]; then echo "- Enhanced error handling requirements in IMPL-2"; fi)
**Backup Location**: $backup_dir
**Analysis Reports**: .verification/VERIFICATION_RESULTS.md
EOF
# Generate modification log
cat > .verification/MODIFICATION_LOG.md << EOF
# Plan Modification Log
## Session: $session
## Date: $(date)
### Applied Modifications
$(echo "Changes applied based on cross-validation analysis")
### Backup Information
- Backup Directory: $backup_dir
- Original Files: IMPL_PLAN.md, .task/*.json
- Restore Command: cp $backup_dir/* ./
### Validation Results
$(echo "All modified files validated successfully")
EOF
echo "Modifications applied successfully!"
echo "Backup created at: $backup_dir"
echo "Modification log: .verification/MODIFICATION_LOG.md"
```
**Change Categories & Implementation**:
**Task Modifications**:
- **Task Merging**: Combine related tasks with dependency updates
- **Task Splitting**: Divide complex tasks with new dependencies
- **Context Enhancement**: Add missing requirements or acceptance criteria
- **Dependency Updates**: Add/remove/modify depends_on relationships
**Plan Enhancements**:
- **Requirements Clarification**: Improve requirement definitions
- **Success Criteria**: Add measurable acceptance criteria
- **Risk Mitigation**: Add risk assessment and mitigation steps
- **Documentation Updates**: Enhance context and documentation
## Session Management ⚠️ CRITICAL
- **⚡ FIRST ACTION**: Check for all `.workflow/.active-*` markers
- **Plan validation**: Ensure active session has completed IMPL_PLAN.md
- **Task readiness**: Verify .task/ directory contains valid task definitions
- **Analysis prerequisites**: Confirm planning analysis artifacts exist
- **Context isolation**: Each session maintains independent verification state
## Error Handling & Recovery
### Verification Phase Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| No active session | Missing `.active-*` markers | Run `/workflow:plan` first |
| Incomplete plan | Missing IMPL_PLAN.md | Complete planning phase |
| No task definitions | Empty .task/ directory | Regenerate tasks |
| Analysis tool failure | Tool execution error | Retry with fallback context |
### Recovery Procedures
**Session Recovery**:
```bash
# Validate session readiness
if [ ! -f ".workflow/$session/IMPL_PLAN.md" ]; then
echo "Plan incomplete - run /workflow:plan first"
exit 1
fi
# Check task definitions exist
if [ ! -d ".workflow/$session/.task/" ] || [ -z "$(ls .workflow/$session/.task/)" ]; then
echo "No task definitions found - regenerate tasks"
exit 1
fi
```
**Analysis Recovery**:
```bash
# Retry failed analysis with reduced context
if [ "$GEMINI_FAILED" = "true" ]; then
echo "Retrying gemini analysis with minimal context..."
fi
# Use fallback analysis if tools unavailable
if [ "$TOOLS_UNAVAILABLE" = "true" ]; then
echo "Using manual validation checklist..."
fi
```
## Usage Examples & Integration
### Complete Verification Workflow
```bash
# 1. After completing planning
/workflow:plan "Build authentication system"
# 2. Verify the plan before execution
/workflow:verify
# 3. Review and approve suggested modifications
# (Interactive prompts guide through approval process)
# 4. Execute verified plan
/workflow:execute
```
### Common Scenarios
#### Quick Verification Check
```bash
/workflow:verify --quick # Basic validation without modifications
```
#### Re-verification After Changes
```bash
/workflow:verify --recheck # Re-run after manual plan modifications
```
#### Verification with Custom Focus
```bash
/workflow:verify --focus=technical # Emphasize technical analysis
/workflow:verify --focus=strategic # Emphasize strategic analysis
```
### Integration Points
- **After Planning**: Use after `/workflow:plan` to validate created plans
- **Before Execution**: Use before `/workflow:execute` to ensure quality
- **Plan Iteration**: Use during iterative planning refinement
- **Quality Assurance**: Use as standard practice for complex workflows
### Key Benefits
- **Early Issue Detection**: Catch problems before implementation starts
- **Dual Perspective**: Both strategic and technical validation
- **Quality Assurance**: Systematic plan evaluation and improvement
- **Risk Mitigation**: Identify potential issues and dependencies
- **User Control**: All changes require explicit approval
- **Non-Destructive**: Original plans preserved with full rollback capability
## Quality Standards
### Analysis Excellence
- **Comprehensive Context**: Both tools receive complete workflow context
- **Independent Analysis**: Tools analyze separately to avoid bias
- **Focused Evaluation**: Each tool evaluates its domain expertise
- **Objective Assessment**: Clear criteria and measurable recommendations
### User Experience Excellence
- **Clear Presentation**: Results displayed in actionable format
- **Informed Decisions**: Impact assessment for all suggested changes
- **Selective Control**: Granular approval of individual modifications
- **Safe Operations**: Full backup and rollback capability
- **Transparent Process**: Complete audit trail of all changes

View File

@@ -1,354 +0,0 @@
---
name: plan
description: Create implementation plans with intelligent input detection
usage: /workflow:plan <input>
argument-hint: "text description"|file.md|ISS-001
examples:
- /workflow:plan "Build authentication system"
- /workflow:plan requirements.md
- /workflow:plan ISS-001
---
# Workflow Plan Command
## Usage
```bash
/workflow:plan <input>
```
## Input Detection
- **Files**: `.md/.txt/.json/.yaml/.yml` → Reads content and extracts requirements
- **Issues**: `ISS-*`, `ISSUE-*`, `*-request-*` → Loads issue data and acceptance criteria
- **Text**: Everything else → Parses natural language requirements
## Core Workflow
### Analysis & Planning Process
The command performs comprehensive analysis through:
**0. Pre-Analysis Documentation Check** ⚠️ FIRST STEP
- **Selective documentation loading based on task requirements**:
- **Always check**: `.workflow/docs/README.md` - System navigation and module index
- **For architecture tasks**: `.workflow/docs/architecture/system-design.md`, `module-map.md`
- **For specific modules**: `.workflow/docs/modules/[relevant-module]/overview.md`
- **For API tasks**: `.workflow/docs/api/unified-api.md`
- **Context-driven selection**: Only load documentation relevant to the specific task scope
- **Foundation for analysis**: Use relevant docs to understand affected components and dependencies
**1. Context Gathering & Intelligence Selection**
- Reading relevant CLAUDE.md documentation based on task requirements
- Automatic tool assignment based on complexity:
- **Simple tasks** (≤3 modules): Direct CLI tools with intelligent path navigation and multi-round analysis
```bash
# Analyze specific directory
cd "src/auth" && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Analyze authentication patterns
TASK: Review auth implementation for security patterns
CONTEXT: Focus on JWT handling and user validation
EXPECTED: Security assessment and recommendations
RULES: Focus on security vulnerabilities and best practices
"
# Implement in specific directory
codex -C src/components --full-auto exec "
PURPOSE: Create user profile component
TASK: Build responsive profile component with form validation
CONTEXT: Use existing component patterns
EXPECTED: Complete component with tests
RULES: Follow existing component architecture
" -s danger-full-access
```
- **Complex tasks** (>3 modules): Specialized general-purpose with autonomous CLI tool orchestration and cross-module coordination
- Flow control integration with automatic tool selection
**2. Project Structure Analysis** ⚠️ CRITICAL PRE-PLANNING STEP
- **Documentation Context First**: Reference existing documentation at `.workflow/docs/README.md`, `.workflow/docs/modules/*/overview.md`, `.workflow/docs/architecture/*.md` if available
- **Complexity assessment**: Count total saturated tasks
- **Decomposition strategy**: Flat (≤5) | Hierarchical (6-10) | Re-scope (>10)
- **Module boundaries**: Identify relationships and dependencies using existing documentation
- **File grouping**: Cohesive file sets and target_files generation
- **Pattern recognition**: Existing implementations and conventions
**3. Analysis Artifacts Generated**
- **ANALYSIS_RESULTS.md**: Context analysis, codebase structure, pattern identification, task decomposition
- **Context mapping**: Project structure, dependencies, cohesion groups
- **Implementation strategy**: Tool selection and execution approach
## Implementation Standards
### Context Management & Agent Execution
**Agent Context Loading** ⚠️ CRITICAL
The following pre_analysis steps are generated for agent execution:
```json
// Example pre_analysis steps generated by /workflow:plan for agent execution
"flow_control": {
"pre_analysis": [
{
"step": "load_planning_context",
"action": "Load plan-generated analysis and context",
"command": "bash(cat .workflow/WFS-[session]/.process/ANALYSIS_RESULTS.md 2>/dev/null || echo 'planning analysis not found')",
"output_to": "planning_context"
},
{
"step": "mcp_codebase_exploration",
"action": "Explore codebase structure and patterns using MCP tools",
"command": "mcp__code-index__find_files(pattern=\"[focus_paths_pattern]\") && mcp__code-index__search_code_advanced(pattern=\"[context_requirements_pattern]\", file_pattern=\"[target_extensions]\")",
"output_to": "codebase_structure"
},
{
"step": "mcp_external_context",
"action": "Get external API examples and best practices",
"command": "mcp__exa__get_code_context_exa(query=\"[meta_type] [context_requirements]\", tokensNum=\"dynamic\")",
"output_to": "external_context"
},
{
"step": "load_dependencies",
"action": "Retrieve dependency task summaries",
"command": "bash(cat .workflow/WFS-[session]/.summaries/IMPL-[dependency_id]-summary.md 2>/dev/null || echo 'dependency summary not found')",
"output_to": "dependency_context"
},
{
"step": "load_base_documentation",
"action": "Load core documentation files",
"commands": [
"bash(cat .workflow/docs/README.md 2>/dev/null || echo 'Base docs not found')",
"bash(cat CLAUDE.md README.md 2>/dev/null || echo 'Project docs not found')"
],
"output_to": "base_docs"
},
{
"step": "load_task_specific_docs",
"action": "Load documentation relevant to task type",
"commands": [
"bash(cat .workflow/docs/architecture/*.md 2>/dev/null || echo 'Architecture docs not found')",
"bash(cat .workflow/docs/api/*.md 2>/dev/null || echo 'API docs not found')"
],
"output_to": "task_docs"
},
{
"step": "analyze_task_patterns",
"action": "Analyze existing code patterns for task context",
"commands": [
"bash(cd \"[context.focus_paths]\")",
"bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Analyze task patterns for '[title]' TASK: Review existing patterns and dependencies CONTEXT: @{[session.task_json_path]} @{CLAUDE.md} @{[context.focus_paths]/**/*} EXPECTED: Pattern analysis with recommendations RULES: Focus on existing patterns and integration points\")"
],
"output_to": "task_context",
"on_error": "fail"
}
]
}
```
**Context Accumulation Guidelines**:
Flow_control design should follow these principles:
1. **Structure Analysis**: Project hierarchy and patterns
2. **Dependency Mapping**: Previous task summaries → inheritance context
3. **Task Context Generation**: Combined analysis → task.context fields
4. **CLI Tool Analysis**: Use Gemini/Codex appropriately for pattern analysis when needed
**MCP Integration Principles**:
- **Code Index First**: Use `mcp__code-index__` for internal codebase exploration before external tools
- **Exa for Context**: Use `mcp__exa__get_code_context_exa` to supplement with external API patterns and examples
- **Automatic Fallback**: If MCP tools unavailable, workflow uses traditional bash/CLI tools
- **Enhanced Analysis**: MCP tools provide deeper codebase understanding and external best practices
**Benefits of MCP Integration**:
- **Faster Analysis**: Direct codebase indexing vs. manual file searching
- **External Context**: Real-world API patterns and implementation examples
- **Pattern Recognition**: Advanced code pattern matching and similarity detection
- **Comprehensive Coverage**: Both internal code exploration and external best practice lookup
**Implementation Approach Planning**:
Each task's `flow_control.implementation_approach` defines execution strategy (planning phase):
1. **task_description**: Implementation strategy definition:
- Clear implementation goal to be executed later
- Planned reference to patterns from pre_analysis results
- Integration strategy with existing codebase
2. **modification_points**: Planned code modification targets:
- Specific code changes to be made during execution
- Planned use of parent task patterns via `[parent]` context
- Integration points with existing components via `[context]` from dependencies
3. **logic_flow**: Business logic execution plan:
- Step-by-step workflow to be implemented
- Planned data flow between components
- Integration points using `[inherited]` and `[shared]` context
4. **target_files**: Target file specifications for execution:
- `src/auth/login.ts:handleLogin:75-120` (planned function and line range)
- `src/middleware/auth.ts:validateToken` (planned function target)
- Must align with task's `context.focus_paths`
**Variable Reference System**:
- `[design]` - Results from pre_analysis steps
- `[parent]` - Context inherited from parent tasks
- `[context]` - Dependencies from related tasks
- `[inherited]` - Shared context from session
- `[shared]` - Global rules and patterns
**Content Sources**:
- Task summaries: `.workflow/WFS-[session]/.summaries/`
- Documentation: `.workflow/docs/`, `CLAUDE.md`, `README.md`, config files
- Analysis artifacts: `.workflow/WFS-[session]/.process/ANALYSIS_RESULTS.md`
- Dependency contexts: `.workflow/WFS-[session]/.task/IMPL-*.json`
### Task Decomposition Standards
**Core Principle: Task Merging Over Decomposition**
- **Merge Rule**: Tasks that can be executed together should not be separated - avoid unnecessary decomposition
- **Decomposition Criteria**: Only decompose tasks in the following situations:
- **Excessive Workload**: Code exceeds 2500 lines or modifies more than 6 files
- **Context Separation**: Involves completely different tech stacks or business domains
- **Dependency Blocking**: Subsequent tasks must wait for prerequisite task completion
- **Parallel Execution**: Independent features that can be developed simultaneously by different developers
**Rules**:
- **Maximum 10 tasks**: Hard limit - exceeding requires re-scoping
- **Function-based**: Complete functional units with related files (logic + UI + tests + config)
- **File cohesion**: Group tightly coupled components in same task
- **Hierarchy**: Flat (≤5 tasks) | Two-level (6-10 tasks) | Re-scope (>10 tasks)
### Session Management ⚠️ CRITICAL
- **⚡ FIRST ACTION**: Check for all `.workflow/.active-*` markers before any planning
- **Multiple sessions support**: Different Claude instances can have different active sessions
- **User selection**: If multiple active sessions found, prompt user to select which one to work with
- **Auto-session creation**: `WFS-[topic-slug]` only if no active session exists
- **Session continuity**: MUST use selected active session to maintain context
- **⚠️ Dependency context**: MUST read ALL previous task summary documents from selected session before planning
- **Session isolation**: Each session maintains independent context and state
**Task Patterns**:
- ✅ **Correct (Function-based)**: `IMPL-001: User authentication system` (models + routes + components + middleware + tests)
- ❌ **Wrong (File/step-based)**: `IMPL-001: Create database model`, `IMPL-002: Create API endpoint`
## Document Generation
**Workflow**: Identifier Creation → Folder Structure → IMPL_PLAN.md → .task/IMPL-NNN.json → TODO_LIST.md
**Always Created**:
- **IMPL_PLAN.md**: Requirements, task breakdown, success criteria
- **Session state**: Task references and paths
**Auto-Created (complexity > simple)**:
- **TODO_LIST.md**: Hierarchical progress tracking
- **.task/*.json**: Individual task definitions with flow_control
- **.process/ANALYSIS_RESULTS.md**: Analysis results and planning artifacts
**Document Structure**:
```
.workflow/WFS-[topic]/
├── IMPL_PLAN.md # Main planning document
├── TODO_LIST.md # Progress tracking (if complex)
├── .process/
│ └── ANALYSIS_RESULTS.md # Analysis results and planning artifacts
└── .task/
├── IMPL-001.json # Task definitions with flow_control
└── IMPL-002.json
```
### IMPL_PLAN.md Structure ⚠️ REQUIRED FORMAT
**File Header** (required)
- **Identifier**: Unique project identifier and session ID, format WFS-[topic]
- **Source**: Input type, e.g. "User requirements analysis"
- **Analysis**: Analysis document reference
**Summary** (execution overview)
- Concise description of core requirements and objectives
- Technical direction and implementation approach
**Context Analysis** (context analysis)
- **Project** - Project type and architectural patterns
- **Modules** - Involved modules and component list
- **Dependencies** - Dependency mapping and constraints
- **Patterns** - Identified code patterns and conventions
**Task Breakdown** (task decomposition)
- **Task Count** - Total task count and complexity level
- **Hierarchy** - Task organization structure (flat/hierarchical)
- **Dependencies** - Inter-task dependency graph
**Implementation Plan** (implementation plan)
- **Execution Strategy** - Execution strategy and methodology
- **Resource Requirements** - Required resources and tool selection
- **Success Criteria** - Success criteria and acceptance conditions
## Reference Information
### Task JSON Schema (5-Field Architecture)
Each task.json uses the standardized 5-field schema (aligned with task-core.md and execute.md):
```json
{
"id": "IMPL-N[.M]",
"title": "Descriptive task name",
"status": "pending|active|completed|blocked|container",
"meta": {
"type": "feature|bugfix|refactor|test|docs",
"agent": "@code-developer|@planning-agent|@code-review-test-agent"
},
"context": {
"requirements": ["requirement1", "requirement2"],
"focus_paths": ["src/path1", "src/path2", "specific_file.ts"],
"acceptance": ["criteria1", "criteria2"],
"parent": "IMPL-N",
"depends_on": ["IMPL-N.M"],
"inherited": {
"from": "parent_task_id",
"context": ["inherited_info"]
},
"shared_context": {
"key": "shared_value"
}
},
"flow_control": {
"pre_analysis": [
{
"step": "step_name",
"action": "description",
"command": "executable_command",
"output_to": "variable_name",
"on_error": "skip_optional|fail|retry_once"
}
],
"implementation_approach": {
"task_description": "detailed implementation strategy",
"modification_points": ["specific changes"],
"logic_flow": ["step by step process"]
},
"target_files": ["file:function:lines"]
}
}
```
**MCP Tools Integration**: Enhanced with optional MCP servers for advanced analysis:
- **Code Index MCP**: `mcp__code-index__find_files()`, `mcp__code-index__search_code_advanced()`
- **Exa MCP**: `mcp__exa__get_code_context_exa()` for external patterns
### File Structure Reference
**Architecture**: @~/.claude/workflows/workflow-architecture.md
### Execution Integration
Documents created for `/workflow:execute`:
- **IMPL_PLAN.md**: Context loading and requirements
- **.task/*.json**: Agent implementation context
- **TODO_LIST.md**: Status tracking (container tasks with ▸, leaf tasks with checkboxes)
## Error Handling
- **Vague input**: Auto-reject ("fix it", "make better", etc.)
- **File not found**: Clear suggestions
- **>10 tasks**: Force re-scoping into iterations
## Planning-Only Constraint
This command creates implementation plans but does not execute them.
Use `/workflow:execute` for actual implementation.

View File

@@ -1,69 +1,82 @@
---
name: start
description: Start a new workflow session
usage: /workflow:session:start "task description"
description: Discover existing sessions or start a new workflow session with intelligent session management
usage: /workflow:session:start [task_description]
argument-hint: [optional: task description for new session]
examples:
- /workflow:session:start "implement OAuth2 authentication"
- /workflow:session:start "fix login bug"
- /workflow:session:start
---
# Start Workflow Session (/workflow:session:start)
## Purpose
Initialize a new workflow session for the given task description.
## Overview
Manages workflow sessions - discovers existing active sessions or creates new ones.
## Usage
```bash
/workflow/session/start "task description"
/workflow:session:start # Discover/select existing sessions
/workflow:session:start "task description" # Create new session
```
## Automatic Behaviors
## Implementation Flow
### Session Creation
- Generates unique session ID: WFS-[topic-slug]
- Creates `.workflow/.active-[session-name]` marker file
- Deactivates any existing active session
### Complexity Detection
Automatically determines complexity based on task description:
- **Simple**: Single module, <5 tasks
- **Medium**: Multiple modules, 5-15 tasks
- **Complex**: Large scope, >15 tasks
### Directory Structure
Creates session directory with:
```
.workflow/WFS-[topic-slug]/
├── workflow-session.json # Session metadata
├── IMPL_PLAN.md # Initial planning template
├── .task/ # Task management
└── reports/ # Report generation
### Step 1: Check for Active Sessions
```bash
ls .workflow/.active-* 2>/dev/null
```
### Phase Initialization
- **Simple**: Ready for direct implementation
- **Medium/Complex**: Ready for planning phase
### Step 2: List Existing Sessions
```bash
ls -1 .workflow/WFS-* 2>/dev/null | head -5
```
## Session State
Creates `workflow-session.json` with:
- Session ID and description
- Current phase: INIT → PLAN
- Document tracking
- Task system configuration
- Active marker reference
### Step 3: Create New Session (if needed)
```bash
mkdir -p .workflow
echo "auth-system" | sed 's/[^a-zA-Z0-9]/-/g' | tr '[:upper:]' '[:lower:]'
```
## Next Steps
After starting a session:
- Use `/workflow/plan` to create implementation plan
- Use `/workflow/execute` to begin implementation
- Use `/context` to view session status
### Step 4: Create Session Directory Structure
```bash
mkdir -p .workflow/WFS-auth-system/.process
mkdir -p .workflow/WFS-auth-system/.task
mkdir -p .workflow/WFS-auth-system/.summaries
```
## Error Handling
- **Duplicate session**: Warns if similar session exists
- **Invalid description**: Prompts for valid task description
- **Directory conflicts**: Handles existing directories gracefully
### Step 5: Create Session Metadata
```bash
echo '{"session_id":"WFS-auth-system","project":"authentication system","status":"planning"}' > .workflow/WFS-auth-system/workflow-session.json
```
---
### Step 6: Mark Session as Active
```bash
touch .workflow/.active-WFS-auth-system
```
**Creates**: New active workflow session ready for planning and execution
### Step 7: Clean Old Active Markers (if creating new)
```bash
rm .workflow/.active-WFS-* 2>/dev/null
```
## Simple Bash Commands
### Basic Operations
- **Check sessions**: `ls .workflow/.active-*`
- **List sessions**: `ls .workflow/WFS-*`
- **Create directory**: `mkdir -p .workflow/WFS-session-name/.process`
- **Create file**: `echo 'content' > .workflow/session/file.json`
- **Mark active**: `touch .workflow/.active-WFS-session-name`
- **Clean markers**: `rm .workflow/.active-*`
### No Complex Logic
- No variables or functions
- No conditional statements
- No loops or pipes
- Direct bash commands only
## Related Commands
- `/workflow:plan` - Uses this for session management
- `/workflow:execute` - Uses this for session discovery
- `/workflow:session:status` - Shows session information