diff --git a/.claude/workflows/intelligent-tools-strategy.md b/.claude/workflows/intelligent-tools-strategy.md index e1b843aa..faf6530d 100644 --- a/.claude/workflows/intelligent-tools-strategy.md +++ b/.claude/workflows/intelligent-tools-strategy.md @@ -1,43 +1,17 @@ --- name: intelligent-tools-strategy -description: Strategic guide for intelligent tool selection - quick start and decision framework +description: Strategic decision framework for intelligent tool selection type: strategic-guideline --- # Intelligent Tools Selection Strategy -## ⚡ Quick Start +## ⚡ Core Decision Framework -### Essential Commands +**Gemini**: Analysis & understanding large codebases +**Codex**: Development & autonomous implementation -**Gemini** (Analysis & Pattern Recognition): -```bash -~/.claude/scripts/gemini-wrapper -p "analyze authentication patterns" -``` - -**Codex** (Development & Implementation): -```bash -codex --full-auto exec "implement user authentication system" -s danger-full-access -``` - -### ⚠️ CRITICAL Command Differences - -| Tool | Command | Has Wrapper | Key Feature | -|------|---------|-------------|-------------| -| **Gemini** | `~/.claude/scripts/gemini-wrapper` | ✅ YES | Large context window, pattern recognition | -| **Codex** | `codex --full-auto exec ... -s danger-full-access` | ❌ NO | Autonomous development, math reasoning | - -**❌ NEVER use**: `~/.claude/scripts/codex` - this wrapper does not exist! - -### 🔒 Codex Sandbox Modes - -Codex requires the `-s` (sandbox) parameter for write operations: - -- **`-s read-only`**: Safe analysis mode, no file modifications -- **`-s workspace-write`**: Standard development mode, can modify project files -- **`-s danger-full-access`**: Full system access (RECOMMENDED for development tasks) - -**Default Choice**: Use `-s danger-full-access` for all development and implementation tasks. +> **Implementation Details**: See @~/.claude/workflows/tools-implementation-guide.md ## 🎯 Tool Selection Matrix @@ -80,15 +54,9 @@ Codex requires the `-s` (sandbox) parameter for write operations: ## 🔄 Parallel Analysis Strategy For complex projects requiring both broad context and deep analysis: - -```bash -# Use Task agents to run both tools in parallel -Task(subagent_type="general-purpose", - prompt="Use Gemini (see @~/.claude/workflows/tools-implementation-guide.md) for architectural analysis") -+ -Task(subagent_type="general-purpose", - prompt="Use Codex (see @~/.claude/workflows/tools-implementation-guide.md) for algorithmic analysis") -``` +- **Gemini** for architectural understanding +- **Codex** for focused development tasks +- Run both via Task agents when comprehensive coverage needed ## 📈 Complexity-Based Selection @@ -104,56 +72,17 @@ Task(subagent_type="general-purpose", - **Gemini** for architectural understanding - **Codex** for focused development tasks -## 🎯 Quick Reference +## 🎯 Strategic Guidelines -### Gemini Quick Commands -```bash -# Pattern analysis -~/.claude/scripts/gemini-wrapper -p "analyze existing patterns in auth module" +1. **Task-driven selection**: Let project characteristics drive tool choice +2. **Start simple**: Begin with single tool, escalate to parallel if needed +3. **Context first**: Understand scope before selecting approach +4. **Trust autonomous capabilities**: Let tools handle their specialized domains -# Architecture review -cd src && ~/.claude/scripts/gemini-wrapper -p "review overall architecture" +## 🔗 Implementation Details -# Code conventions -~/.claude/scripts/gemini-wrapper -p "identify coding standards and conventions" -``` - -### Codex Quick Commands -```bash -# Feature development -codex --full-auto exec "implement JWT authentication with refresh tokens" -s danger-full-access - -# Performance optimization -codex --full-auto exec "optimize database queries in user service" -s danger-full-access - -# Security enhancement -codex --full-auto exec "add input validation and sanitization" -s danger-full-access -``` - -## 📋 Implementation Guidelines - -1. **Default Selection**: Let project characteristics drive tool choice -2. **Start Simple**: Begin with single tool, escalate to parallel if needed -3. **Context First**: Understand scope before selecting approach -4. **Trust the Tools**: Let autonomous capabilities handle complexity - -## 🔗 Detailed Implementation - -For comprehensive syntax, patterns, and advanced usage: -- **Implementation Guide**: @~/.claude/workflows/tools-implementation-guide.md - -## 📊 Tools Comparison Summary - -| Feature | Gemini | Codex | -|---------|--------|-------| -| **Command Syntax** | Has wrapper script | Direct command only | -| **File Loading** | `--all-files` available | `@` patterns required | -| **Default Mode** | Interactive analysis | `--full-auto exec ... -s danger-full-access` automation | -| **Primary Use** | Analysis & planning | Development & implementation | -| **Context Window** | Very large | Standard with smart discovery | -| **Automation Level** | Manual implementation | Autonomous execution | -| **Best For** | Understanding codebases | Building features | +**Complete syntax and usage patterns**: @~/.claude/workflows/tools-implementation-guide.md --- -**Remember**: Choose based on task nature, not personal preference. Gemini excels at understanding, Codex excels at building. \ No newline at end of file +**Decision Principle**: Choose based on task nature - Gemini excels at understanding, Codex excels at building. \ No newline at end of file diff --git a/.claude/workflows/tools-implementation-guide.md b/.claude/workflows/tools-implementation-guide.md index f52a85a2..3e102cdc 100644 --- a/.claude/workflows/tools-implementation-guide.md +++ b/.claude/workflows/tools-implementation-guide.md @@ -6,135 +6,174 @@ type: technical-guideline # Tools Implementation Guide -## 📚 Part A: Shared Resources +## 🚀 Quick Start -### 📁 Template System +### ⚡ Tool Selection at a Glance -**Structure**: `~/.claude/workflows/cli-templates/prompts/` +| Tool | Primary Use | Command Pattern | File Loading | Best For | +|------|-------------|-----------------|---------------|-----------| +| **Gemini** | Analysis & Understanding | `~/.claude/scripts/gemini-wrapper -p "prompt"` | `--all-files` or `@{patterns}` | Large context analysis, pattern detection | +| **Codex** | Development & Implementation | `codex --full-auto exec "task" -s danger-full-access` | `@{patterns}` or autonomous discovery | Feature development, automation | -**Categories**: -- `analysis/` - pattern.txt, architecture.txt, security.txt, performance.txt, quality.txt (Gemini primary, Codex compatible) -- `development/` - feature.txt, component.txt, refactor.txt, testing.txt, debugging.txt (Codex primary) -- `planning/` - task-breakdown.txt, migration.txt (Cross-tool) -- `automation/` - scaffold.txt, migration.txt, deployment.txt (Codex specialized) -- `review/` - code-review.txt (Cross-tool) -- `integration/` - api-design.txt, database.txt (Codex primary) - -**Usage**: `$(cat ~/.claude/workflows/cli-templates/prompts/[category]/[template].txt)` - -### 🎭 Planning Role Templates - -**Location**: `~/.claude/workflows/cli-templates/planning-roles/` - -**Specialized Planning Roles**: -- **business-analyst.md** - Business requirements and process analysis -- **data-architect.md** - Data modeling and architecture design -- **feature-planner.md** - Feature specification and planning -- **innovation-lead.md** - Innovation strategy and technology exploration -- **product-manager.md** - Product roadmap and user story management -- **security-expert.md** - Security architecture and threat modeling -- **system-architect.md** - System design and technical architecture -- **test-strategist.md** - Testing strategy and quality assurance -- **ui-designer.md** - User interface and experience design -- **user-researcher.md** - User research and requirements gathering - -**Usage**: `$(cat ~/.claude/workflows/cli-templates/planning-roles/[role].md)` - -### 🛠️ Tech Stack Templates - -**Location**: `~/.claude/workflows/cli-templates/tech-stacks/` - -**Technology-Specific Development Templates**: -- **go-dev.md** - Go development patterns and best practices -- **java-dev.md** - Java enterprise development standards -- **javascript-dev.md** - JavaScript development fundamentals -- **python-dev.md** - Python development conventions and patterns -- **react-dev.md** - React component development and architecture -- **typescript-dev.md** - TypeScript development guidelines and patterns - -**Usage**: `$(cat ~/.claude/workflows/cli-templates/tech-stacks/[stack]-dev.md)` - -### 📚 Template Quick Reference Map - -**Base Path**: `~/.claude/workflows/cli-templates/prompts/` - -**Templates by Category**: -- **analysis/** - pattern.txt, architecture.txt, security.txt, performance.txt, quality.txt -- **development/** - feature.txt, component.txt, refactor.txt, testing.txt, debugging.txt -- **planning/** - task-breakdown.txt, migration.txt -- **automation/** - scaffold.txt, deployment.txt -- **review/** - code-review.txt -- **integration/** - api-design.txt, database.txt - -### 📂 File Pattern Wildcards +### 🎯 Quick Commands +**Gemini (Analysis)**: ```bash -* # Any character (excluding path separators) -** # Any directory levels (recursive) -? # Any single character -[abc] # Any character within the brackets -{a,b,c} # Any of the options within the braces +# Pattern analysis +~/.claude/scripts/gemini-wrapper -p "analyze authentication patterns" + +# Architecture review +cd src && ~/.claude/scripts/gemini-wrapper -p "review overall architecture" ``` -### 🌐 Cross-Platform Rules +**Codex (Development)**: +```bash +# Autonomous feature development +codex --full-auto exec "implement JWT authentication system" -s danger-full-access -- Always use forward slashes (`/`) for paths -- Enclose paths with spaces in quotes: `@{"My Project/src/**/*"}` -- Escape special characters like brackets: `@{src/**/*\[bracket\]*}` +# Targeted development +codex --cd src/auth --full-auto exec "refactor authentication module" -s danger-full-access +``` -### ⏱️ Execution Settings +### ⚠️ Critical Differences -- **Default Timeout**: Bash command execution extended to **10 minutes** for complex analysis and development workflows -- **Error Handling**: Both tools provide comprehensive error logging and recovery mechanisms +| Aspect | Gemini | Codex | +|--------|--------|--------| +| **Wrapper Script** | ✅ Has wrapper: `~/.claude/scripts/gemini-wrapper` | ❌ No wrapper: direct `codex` command only | +| **File Discovery** | Auto `--all-files` for small projects | Autonomous discovery with `--full-auto` | +| **Sandbox Mode** | Not required | 🔒 Required: `-s danger-full-access` | +| **Default Mode** | Interactive analysis | Autonomous execution | --- -## 🔍 Part B: Gemini Implementation Guide +## 📚 Shared Resources -### 🚀 Command Overview +### 📁 Template System -- **Purpose**: Comprehensive codebase analysis, context gathering, and pattern detection across multiple files -- **Key Feature**: Large context window for simultaneous multi-file analysis -- **Primary Triggers**: "analyze", "get context", "understand the codebase", relationships between files +**Base Structure**: `~/.claude/workflows/cli-templates/` -### ⭐ Primary Method: gemini-wrapper +#### Prompt Templates (`prompts/`) +``` +analysis/ # Gemini primary, Codex compatible +├── pattern.txt - Code pattern analysis +├── architecture.txt - System architecture review +├── security.txt - Security assessment +├── performance.txt - Performance analysis +└── quality.txt - Code quality review + +development/ # Codex primary +├── feature.txt - Feature implementation +├── component.txt - Component development +├── refactor.txt - Refactoring tasks +├── testing.txt - Test generation +└── debugging.txt - Debug and fix issues + +planning/ # Cross-tool compatible +├── task-breakdown.txt - Task decomposition +└── migration.txt - Migration planning + +automation/ # Codex specialized +├── scaffold.txt - Project scaffolding +├── migration.txt - Data migration +└── deployment.txt - Deployment automation + +review/ # Cross-tool compatible +└── code-review.txt - Code review process + +integration/ # Codex primary +├── api-design.txt - API specification +└── database.txt - Database design +``` + +**Usage**: `$(cat ~/.claude/workflows/cli-templates/prompts/[category]/[template].txt)` + +#### Planning Role Templates (`planning-roles/`) +- **business-analyst.md** - Business requirements analysis +- **data-architect.md** - Data modeling and architecture +- **feature-planner.md** - Feature specification +- **innovation-lead.md** - Technology exploration +- **product-manager.md** - Product roadmap +- **security-expert.md** - Security architecture +- **system-architect.md** - System design +- **test-strategist.md** - Testing strategy +- **ui-designer.md** - UI/UX design +- **user-researcher.md** - User research + +**Usage**: `$(cat ~/.claude/workflows/cli-templates/planning-roles/[role].md)` + +#### Tech Stack Templates (`tech-stacks/`) +- **go-dev.md** - Go development patterns +- **java-dev.md** - Java enterprise standards +- **javascript-dev.md** - JavaScript fundamentals +- **python-dev.md** - Python conventions +- **react-dev.md** - React architecture +- **typescript-dev.md** - TypeScript guidelines + +**Usage**: `$(cat ~/.claude/workflows/cli-templates/tech-stacks/[stack]-dev.md)` + +### 📂 File Pattern Reference + +#### Universal Patterns +```bash +* # Any character (excluding path separators) +** # Any directory levels (recursive) +? # Any single character +[abc] # Any character within brackets +{a,b,c} # Any of the specified options +``` + +#### Common Pattern Examples +```bash +@{**/*} # All files recursively +@{src/**/*} # All source files +@{*.ts,*.js} # TypeScript and JavaScript files +@{CLAUDE.md,**/*CLAUDE.md} # Documentation hierarchy +@{package.json,*.config.*} # Configuration files +@{src/**/*.test.*} # Test files +``` + +#### Cross-Platform Rules +- Always use forward slashes (`/`) for paths +- Quote paths with spaces: `@{"My Project/src/**/*"}` +- Escape special characters: `@{src/**/*\[bracket\]*}` + +### ⏱️ Execution Environment +- **Default Timeout**: 20 minutes for complex analysis and development workflows +- **Error Logging**: Comprehensive logging and recovery mechanisms +- **Token Management**: Automatic optimization for large codebases + +--- + +## 🔍 Gemini Implementation Guide + +### 🎯 Purpose & Strengths +- **Large context window** for simultaneous multi-file analysis +- **Pattern detection** across multiple modules +- **Architectural understanding** of complex codebases +- **Cross-module relationship** analysis + +### ⭐ Primary Method: gemini-wrapper (RECOMMENDED) **Location**: `~/.claude/scripts/gemini-wrapper` (auto-installed) **Smart Features**: - **Token Threshold**: 2,000,000 tokens (configurable via `GEMINI_TOKEN_LIMIT`) -- **Auto `--all-files`**: Small projects get `--all-files`, large projects use patterns +- **Auto File Loading**: Small projects get `--all-files`, large projects use targeted patterns - **Smart Approval Modes**: Analysis tasks use `default`, execution tasks use `yolo` - **Error Logging**: Captures errors to `~/.claude/.logs/gemini-errors.log` **Task Detection**: -- **Analysis Keywords**: "analyze", "analysis", "review", "understand", "inspect", "examine" → `--approval-mode default` +- **Analysis Keywords**: "analyze", "review", "understand", "inspect" → `--approval-mode default` - **All Other Tasks**: → `--approval-mode yolo` -### 📝 Gemini Command Syntax +### 📝 Command Patterns -**Basic Structure**: +#### Automatic Management (90% of use cases) ```bash -gemini [flags] -p "@{patterns} {template} prompt" -``` - -**Key Arguments**: -- `--all-files`: Includes all files in current working directory -- `-p`: Prompt string with file patterns and analysis query -- `@{pattern}`: Special syntax for referencing files and directories -- `--approval-mode`: Tool approval mode (`default` | `yolo`) -- `--include-directories`: Additional workspace directories (max 5, comma-separated) - -### 📦 Gemini Usage Patterns - -#### 🎯 Using gemini-wrapper (RECOMMENDED - 90% of tasks) - -**Automatic Management**: -```bash -# Analysis task - auto detects and uses --approval-mode default +# Analysis task - auto detects and configures appropriately ~/.claude/scripts/gemini-wrapper -p "Analyze authentication module patterns" -# Development task - auto detects and uses --approval-mode yolo +# Development task - auto configures for execution ~/.claude/scripts/gemini-wrapper -p "Implement user login feature with JWT" # Directory-specific analysis @@ -144,139 +183,71 @@ cd src/auth && ~/.claude/scripts/gemini-wrapper -p "Review authentication patter GEMINI_TOKEN_LIMIT=500000 ~/.claude/scripts/gemini-wrapper -p "Custom analysis" ``` -**Module-Specific Analysis**: +#### Template-Enhanced Analysis ```bash -# Navigate to module directory -cd src/auth && ~/.claude/scripts/gemini-wrapper -p "Analyze authentication module patterns" - -# Template-enhanced analysis +# Single template cd frontend/components && ~/.claude/scripts/gemini-wrapper -p "$(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt)" -``` - -#### 📝 Direct Gemini Usage (Manual Control) - -**Manual Token Management**: -```bash -# Direct control when needed -gemini --all-files -p "Analyze authentication module patterns and implementation" - -# Pattern-based fallback -gemini -p "@{src/auth/**/*} @{CLAUDE.md} Analyze authentication patterns" -``` - -**Template-Enhanced Prompts**: -```bash -# Single template usage -gemini --all-files -p "@{src/**/*} @{CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt)" # Multi-template composition -gemini --all-files -p "@{src/**/*} @{CLAUDE.md} -$(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) +~/.claude/scripts/gemini-wrapper -p "$(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) Additional Security Focus: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/security.txt)" ``` -**Token Limit Fallback Strategy**: +#### Manual Control (when needed) ```bash -# If --all-files exceeds token limits, retry with targeted patterns: +# Direct control with all files +gemini --all-files -p "Analyze authentication module patterns" -# Original command that failed: -gemini --all-files -p "Analyze authentication patterns" - -# Fallback with specific patterns: -gemini -p "@{src/auth/**/*} @{src/middleware/**/*} @{CLAUDE.md} Analyze authentication patterns" - -# Focus on specific file types: -gemini -p "@{**/*.ts} @{**/*.js} @{CLAUDE.md} Analyze authentication patterns" +# Pattern-based targeting +gemini -p "@{src/auth/**/*} @{CLAUDE.md} Analyze authentication patterns" ``` -### 📋 Gemini File Pattern Rules - -**Syntax**: -- `@{pattern}`: Single file or directory pattern -- `@{pattern1,pattern2}`: Multiple patterns, comma-separated - -**CLAUDE.md Loading Rules**: -- **With `--all-files`**: CLAUDE.md files automatically included -- **Without `--all-files`**: Must use `@{CLAUDE.md}` or `@{**/CLAUDE.md}` - -**When to Use @ Patterns**: -1. User explicitly provides @ patterns - ALWAYS preserve exactly -2. Cross-directory analysis - relationships between modules -3. Configuration files - scattered config files -4. Selective inclusion - specific file types only - -### ⚠️ Gemini Best Practices - -- **Quote paths with spaces**: Use proper shell quoting -- **Test patterns first**: Validate @ patterns match existing files -- **Prefer directory navigation**: Reduces complexity, improves performance -- **Preserve user patterns**: When user provides @, always keep them -- **Handle token limits**: Immediate retry without `--all-files` using targeted patterns +### 🔄 Token Limit Fallback Strategy +```bash +# If automatic loading fails due to token limits, retry with patterns: +# Original: ~/.claude/scripts/gemini-wrapper -p "Analyze patterns" +# Fallback: +gemini -p "@{src/auth/**/*} @{src/middleware/**/*} @{CLAUDE.md} Analyze patterns" +``` --- -## 🛠️ Part C: Codex Implementation Guide +## 🛠️ Codex Implementation Guide -### 🚀 Command Overview +### 🎯 Purpose & Strengths +- **Autonomous development** workflows +- **Mathematical reasoning** and optimization +- **Security analysis** and implementation +- **Intelligent code generation** +- **Full project automation** -- **Purpose**: Automated codebase analysis, intelligent code generation, and autonomous development workflows -- **⚠️ CRITICAL**: **NO wrapper script exists** - always use direct `codex` command -- **Key Characteristic**: **No `--all-files` flag** - requires explicit `@` pattern references -- **Default Mode**: `-s workspace-write --full-auto exec` autonomous development mode (RECOMMENDED) -- **🔒 Sandbox Required**: Must specify `-s` (sandbox) parameter for write operations - -### 🔒 Codex Sandbox Modes - -Codex requires the `-s` (sandbox) parameter to control file modification permissions: - -- **`-s read-only`**: Safe analysis mode, no file modifications allowed -- **`-s workspace-write`**: Standard development mode, can modify project files -- **`-s danger-full-access`**: Full system access (**RECOMMENDED for development tasks**) -- **`-s danger-full-access`**: Full system access, use with extreme caution - -**Default Choice**: Always use `-s danger-full-access` for development and implementation tasks. - -### ⭐ CRITICAL: Default to `--full-auto` Mode - -**🎯 Golden Rule**: Always start with `codex --full-auto exec "task description" -s danger-full-access` for maximum autonomous capabilities. - -**Why `--full-auto` Should Be Your Default**: -- **🧠 Intelligent File Discovery**: Auto-identifies relevant files without manual `@` patterns -- **🎯 Context-Aware Execution**: Understands project structure and dependencies autonomously -- **⚡ Streamlined Workflow**: No need to specify file patterns - just describe what you want -- **🚀 Maximum Automation**: Leverages full autonomous development capabilities -- **📚 Smart Documentation**: Automatically includes relevant CLAUDE.md files - -**When to Use Explicit Patterns**: -- ✅ Precise control over which files are included -- ✅ Specific file patterns requiring manual specification -- ✅ Debugging issues with file discovery in `--full-auto` mode -- ❌ **NOT as default choice** - reserve for special circumstances - -### 📝 Codex Command Syntax - -**Basic Structure** (Priority Order): +### 🔒 Sandbox Modes (REQUIRED) ```bash -codex --full-auto exec "autonomous development task" -s danger-full-access # DEFAULT & RECOMMENDED -codex --full-auto exec "prompt with @{patterns}" -s danger-full-access # For specific control needs +-s read-only # Safe analysis mode, no modifications +-s workspace-write # Standard development mode +-s danger-full-access # Full system access (RECOMMENDED for development) ``` -**⚠️ NEVER use**: `~/.claude/scripts/codex` - this wrapper script does not exist! +**⚠️ CRITICAL**: No wrapper script exists - always use direct `codex` command -**Key Commands** (In Order of Preference): -- `codex --full-auto exec "..." -s danger-full-access` ⭐ **PRIMARY MODE** - Full autonomous development -- `codex --cd /path --full-auto exec "..." -s danger-full-access` - Directory-specific autonomous development -- `codex --cd /path --full-auto exec "@{patterns} ..." -s danger-full-access` - Directory-specific with patterns +### ⭐ Default Mode: Full Autonomous (RECOMMENDED) -### 📦 Codex Usage Patterns +**🎯 Golden Rule**: Always start with `codex --full-auto exec "task" -s danger-full-access` -#### 🎯 Autonomous Development (PRIMARY - 90% of tasks) +**Why Full-Auto is Primary Choice**: +- 🧠 **Intelligent File Discovery**: Auto-identifies relevant files +- 🎯 **Context-Aware Execution**: Understands project dependencies +- ⚡ **Streamlined Workflow**: Just describe what you want +- 🚀 **Maximum Automation**: Full autonomous capabilities +- 📚 **Smart Documentation**: Includes relevant CLAUDE.md files -**Basic Development**: +### 📝 Command Patterns (Priority Order) + +#### 1. Autonomous Development (PRIMARY - 90% of tasks) ```bash -# RECOMMENDED: Let Codex handle everything autonomously +# RECOMMENDED: Full autonomous mode codex --full-auto exec "Implement user authentication with JWT tokens" -s danger-full-access # Directory-specific autonomous development @@ -286,7 +257,7 @@ codex --cd src/auth --full-auto exec "Refactor authentication module using lates codex --full-auto exec "Create a complete todo application with React and TypeScript" -s danger-full-access ``` -**Template-Enhanced Development**: +#### 2. Template-Enhanced Development ```bash # Autonomous mode with template guidance codex --full-auto exec "$(cat ~/.claude/workflows/cli-templates/prompts/development/feature.txt) @@ -297,136 +268,135 @@ codex --full-auto exec "$(cat ~/.claude/workflows/cli-templates/prompts/developm - Password reset functionality" -s danger-full-access ``` -#### 🛠️ Controlled Development (When Explicit Control Needed) - -**Module-Specific with Patterns**: +#### 3. Controlled Development (When Explicit Control Needed) ```bash -# Explicit patterns when autonomous mode needs guidance -codex --full-auto exec "@{src/auth/**/*,CLAUDE.md} Refactor authentication module using latest patterns" -s danger-full-access +# Explicit patterns for specific control +codex --full-auto exec "@{src/auth/**/*,CLAUDE.md} Refactor authentication module" -s danger-full-access -# Alternative: Directory-specific execution with explicit patterns -codex --cd src/auth --full-auto exec "@{**/*,../../CLAUDE.md} Refactor authentication module" -s danger-full-access +# Directory-specific with patterns +codex --cd src/auth --full-auto exec "@{**/*,../../CLAUDE.md} Refactor module" -s danger-full-access ``` -**Debugging & Analysis**: -```bash -# Autonomous debugging mode -codex --full-auto exec "$(cat ~/.claude/workflows/cli-templates/prompts/development/debugging.txt) - -## Issue: Performance degradation in user dashboard -- Identify bottlenecks in the codebase -- Propose and implement optimizations -- Add performance monitoring" -s danger-full-access - -# Alternative: Explicit patterns for controlled analysis -codex --full-auto exec "@{src/**/*,package.json,CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/development/debugging.txt)" -s danger-full-access -``` - -### 📂 Codex File Pattern Rules - CRITICAL - -⚠️ **UNLIKE GEMINI**: Codex has **NO `--all-files` flag** - you MUST use `@` patterns to reference files. - -**Essential Patterns**: -```bash -@{**/*} # All files recursively (equivalent to --all-files) -@{src/**/*} # All source files -@{*.ts,*.js} # Specific file types -@{CLAUDE.md,**/*CLAUDE.md} # Documentation hierarchy -@{package.json,*.config.*} # Configuration files -``` - -**CLAUDE.md Loading Rules** (Critical Difference from Gemini): -- **Always explicit**: Must use `@{CLAUDE.md}` or `@{**/*CLAUDE.md}` -- **No automatic loading**: Codex will not include documentation without explicit reference -- **Hierarchical loading**: Use `@{CLAUDE.md,**/*CLAUDE.md}` for complete context - -### 🚀 Codex Advanced Patterns - -#### 🔄 Multi-Phase Development (Full Autonomous Workflow) +### 🚀 Advanced Workflow Patterns +#### Multi-Phase Development ```bash # Phase 1: Autonomous Analysis -codex --full-auto exec "Analyze current architecture for payment system integration" -s danger-full-access +codex --full-auto exec "Analyze current architecture for payment integration" -s danger-full-access -# Phase 2: Autonomous Implementation (RECOMMENDED APPROACH) -codex --full-auto exec "Implement Stripe payment integration based on the analyzed architecture" -s danger-full-access +# Phase 2: Autonomous Implementation +codex --full-auto exec "Implement Stripe payment integration" -s danger-full-access # Phase 3: Autonomous Testing -codex --full-auto exec "Generate comprehensive tests for the payment system implementation" -s danger-full-access - -# Alternative: Explicit control when needed -codex --full-auto exec "@{**/*,CLAUDE.md} Analyze current architecture for payment system integration" -s danger-full-access +codex --full-auto exec "Generate comprehensive tests for payment system" -s danger-full-access ``` -#### 🌐 Cross-Project Learning - +#### Cross-Project Learning ```bash -# RECOMMENDED: Autonomous cross-project pattern learning -codex --full-auto exec "Implement feature X by learning patterns from ../other-project/ and applying them to the current codebase" -s danger-full-access +# Learn from other projects +codex --full-auto exec "Implement feature X by learning patterns from ../other-project/" -s danger-full-access -# Alternative: Explicit pattern specification -codex --full-auto exec "@{../other-project/src/**/*,src/**/*,CLAUDE.md} Implement feature X using patterns from other-project" -s danger-full-access +# Explicit cross-project patterns +codex --full-auto exec "@{../other-project/src/**/*,src/**/*,CLAUDE.md} Implement feature X" -s danger-full-access ``` -#### 📊 Development Workflow Integration +### ⚠️ Critical Requirements +- **File References**: Unlike Gemini, Codex has NO `--all-files` flag +- **Sandbox Required**: Must specify `-s` parameter for write operations +- **Pattern Syntax**: Use `@{patterns}` when not using full-auto mode +- **Documentation Loading**: Must explicitly reference `@{CLAUDE.md}` when using patterns -**Pre-Development Analysis**: -```bash -# RECOMMENDED: Autonomous pattern analysis -codex --full-auto exec "$(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) +--- -Analyze the existing codebase patterns and conventions before implementing new features." -s danger-full-access -``` +## ✅ Best Practices & Guidelines -**Quality Assurance**: -```bash -# RECOMMENDED: Autonomous testing and validation -codex --full-auto exec "$(cat ~/.claude/workflows/cli-templates/prompts/development/testing.txt) +### 🎯 Tool Selection Strategy -Generate comprehensive tests and perform validation for the entire codebase." -s danger-full-access -``` +**Choose Gemini when**: +- Understanding large codebases (>50 files) +- Analyzing patterns across modules +- Cross-module dependency analysis +- Code convention detection +- Architectural review -### ⚠️ Codex Best Practices +**Choose Codex when**: +- Building new features +- Algorithm optimization +- Security implementation +- Autonomous development workflows +- Mathematical problem solving -**Always Use @ Patterns**: -- **MANDATORY**: Codex requires explicit file references via `@` patterns (when not using full-auto autonomous mode) -- **No automatic inclusion**: Unlike Gemini's `--all-files`, you must specify what to analyze -- **Be comprehensive**: Use `@{**/*}` for full codebase context when needed -- **Be selective**: Use specific patterns like `@{src/**/*.ts}` for targeted analysis +### 🛠️ Development Workflow -**Default Automation Mode** (CRITICAL GUIDANCE): -- **`codex --full-auto exec ... -s danger-full-access` is PRIMARY choice**: Use for 90% of all tasks - maximizes autonomous capabilities -- **Explicit patterns only when necessary**: Reserve for cases where you need explicit file pattern control -- **Trust the autonomous intelligence**: Codex excels at file discovery, context gathering, and architectural decisions -- **Start with full-auto always**: If it doesn't meet needs, then consider explicit patterns +#### Pre-Development Pattern +1. **Context Gathering** (Gemini): `~/.claude/scripts/gemini-wrapper -p "analyze project architecture"` +2. **Implementation** (Codex): `codex --full-auto exec "implement feature based on analysis" -s danger-full-access` +3. **Quality Assurance** (Codex): `codex --full-auto exec "generate tests and validate" -s danger-full-access` -**Error Prevention**: -- **Always include @ patterns**: Commands without file references will fail (except in full-auto mode) -- **Test patterns first**: Validate @ patterns match existing files -- **Use comprehensive patterns**: `@{**/*}` when unsure of file structure -- **Include documentation**: Always add `@{CLAUDE.md,**/*CLAUDE.md}` for context when using explicit patterns +#### Error Prevention +- **Test patterns first**: Validate `@{patterns}` match existing files - **Quote complex paths**: Use proper shell quoting for paths with spaces +- **Start simple**: Begin with basic patterns, add complexity as needed +- **Include documentation**: Always reference CLAUDE.md files for context + +#### Token and Context Management +- **Gemini**: Rely on wrapper for automatic token management +- **Codex**: Trust full-auto mode for intelligent file discovery +- **Manual patterns**: Use only when autonomous modes need guidance +- **Fallback strategies**: Have targeted patterns ready for large projects + +### 📊 Template Integration Strategy + +#### Template Composition +```bash +# Combine multiple templates +codex --full-auto exec "$(cat ~/.claude/workflows/cli-templates/prompts/development/feature.txt) + +$(cat ~/.claude/workflows/cli-templates/planning-roles/system-architect.md) + +Task: Implement authentication system" -s danger-full-access +``` + +#### Cross-Tool Template Reuse +- Templates work identically with both tools +- Use `cat` command for seamless integration +- Combine analysis and development templates +- Build complex prompts from multiple sources + +### 🚨 Troubleshooting + +#### Common Issues +1. **Token limit exceeded** (Gemini): Wrapper automatically retries with targeted patterns +2. **File not found** (Both): Validate patterns with `ls` before using +3. **Sandbox errors** (Codex): Ensure `-s` parameter is specified +4. **Pattern matching** (Both): Test with simple patterns first + +#### Recovery Strategies +- **Gemini**: Fallback from `--all-files` to specific patterns +- **Codex**: Fallback from full-auto to explicit patterns +- **Both**: Use directory navigation to reduce complexity +- **Documentation**: Always include CLAUDE.md for context --- -## 🎯 Strategic Integration +## 🎯 Strategic Integration Summary -### Template Reuse Across Tools +### Template Ecosystem +- **Cross-tool compatibility**: Templates work with both Gemini and Codex +- **Layered approach**: Combine prompt templates with planning roles and tech stacks +- **Reusable patterns**: Build library of common development patterns -**Gemini and Codex Template Compatibility**: -- **`cat` command works identically**: Reuse templates seamlessly between tools -- **Cross-reference patterns**: Combine analysis and development templates -- **Template composition**: Build complex prompts from multiple template sources +### Autonomous Development Pipeline +1. **Analysis Phase** (Gemini): Large context understanding +2. **Development Phase** (Codex): Autonomous implementation +3. **Quality Phase** (Codex): Testing and validation -### Autonomous Development Pattern (Codex-Specific) - -1. **Context Gathering**: `@{**/*,CLAUDE.md}` for full project understanding (or let full-auto handle) -2. **Pattern Analysis**: Understand existing code conventions -3. **Automated Implementation**: Let codex handle the development workflow -4. **Quality Assurance**: Built-in testing and validation +### Key Reminders +- **Gemini excels at understanding** - use for analysis and pattern recognition +- **Codex excels at building** - use for development and implementation +- **Start with autonomous modes** - leverage full capabilities before manual control +- **Trust the intelligence** - both tools excel at their specialized functions --- -**Remember**: -- **Gemini excels at understanding** - use `~/.claude/scripts/gemini-wrapper` for analysis and pattern recognition -- **Codex excels at building** - use `codex --full-auto exec ... -s danger-full-access` for autonomous development and implementation \ No newline at end of file +**Quick Reference**: For strategic guidance on tool selection, see `@~/.claude/workflows/intelligent-tools-strategy.md` \ No newline at end of file diff --git a/.claude/workflows/workflow-architecture.md b/.claude/workflows/workflow-architecture.md index d7cfefbf..4ad92623 100644 --- a/.claude/workflows/workflow-architecture.md +++ b/.claude/workflows/workflow-architecture.md @@ -4,6 +4,16 @@ This document defines the complete workflow system architecture using a **JSON-only data model**, **marker-based session management**, and **unified file structure** with dynamic task decomposition. +## Core Architecture + +### JSON-Only Data Model +**JSON files (.task/IMPL-*.json) are the only authoritative source of task state. All markdown documents are read-only generated views.** + +- **Task State**: Stored exclusively in JSON files +- **Documents**: Generated on-demand from JSON data +- **No Synchronization**: Eliminates bidirectional sync complexity +- **Performance**: Direct JSON access without parsing overhead + ### Key Design Decisions - **JSON files are the single source of truth** - All markdown documents are read-only generated views - **Marker files for session tracking** - Ultra-simple active session management @@ -27,7 +37,7 @@ This document defines the complete workflow system architecture using a **JSON-o **Marker File Benefits**: - **Zero Parsing**: File existence check is atomic and instant -- **Atomic Operations**: File creation/deletion is naturally atomic +- **Atomic Operations**: File creation/deletion is naturally atomic - **Visual Discovery**: `ls .workflow/.active-*` shows active session immediately - **Simple Switching**: Delete old marker + create new marker = session switch @@ -47,14 +57,14 @@ fi find .workflow -name ".active-*" -delete && touch .workflow/.active-WFS-new-feature ``` -### Individual Session Tracking +### Session State Tracking Each session directory contains `workflow-session.json`: ```json { "session_id": "WFS-[topic-slug]", "project": "feature description", - "type": "simple|medium|complex", + "type": "simple|medium|complex", "current_phase": "PLAN|IMPLEMENT|REVIEW", "status": "active|paused|completed", "progress": { @@ -64,17 +74,9 @@ Each session directory contains `workflow-session.json`: } ``` -## Data Model +## Task System -### JSON-Only Architecture -**JSON files (.task/IMPL-*.json) are the only authoritative source of task state. All markdown documents are read-only generated views.** - -- **Task State**: Stored exclusively in JSON files -- **Documents**: Generated on-demand from JSON data -- **No Synchronization**: Eliminates bidirectional sync complexity -- **Performance**: Direct JSON access without parsing overhead - -### Hierarchical Task System +### Hierarchical Task Structure **Maximum Depth**: 2 levels (IMPL-N.M format) ``` @@ -91,7 +93,7 @@ IMPL-2.1 # Subtask of IMPL-2 (dynamically created) - **Status inheritance**: Parent status derived from subtask completion ### Task JSON Schema -All task files use this simplified 5-field schema: +All task files use this unified 5-field schema: ```json { @@ -122,24 +124,21 @@ All task files use this simplified 5-field schema: "flow_control": { "pre_analysis": [ { - "step": "...", - "action": "...", - "command": "..." + "step": "check_patterns", + "action": "Analyze existing patterns", + "command": "bash(rg 'auth' src/ | head -10)", + "output_to": "auth_patterns" } ], "implementation_approach": { - "task_description": "Implement comprehensive JWT authentication system with secure token management and validation middleware. Reference [inherited.context] from parent task [parent] for architectural consistency. Apply [shared_context.auth_strategy] across authentication modules. Focus implementation on [focus_paths] directories following established patterns.", + "task_description": "Implement JWT authentication following existing patterns", "modification_points": [ - "Add JWT token generation in login handler (src/auth/login.ts:handleLogin:75-120) following [shared_context.auth_strategy]", - "Implement token validation middleware (src/middleware/auth.ts:validateToken) referencing [inherited.context] design patterns", - "Add refresh token mechanism for session management using [shared_context] token strategy", - "Update user authentication flow to support JWT tokens in [focus_paths] modules" + "Add JWT generation in login handler", + "Implement token validation middleware" ], "logic_flow": [ - "User login request → validate credentials → generate JWT token using [shared_context.auth_strategy] → store refresh token", - "Protected route access → extract JWT from headers → validate token against [inherited.context] schema → allow/deny access", - "Token expiry handling → use refresh token following [shared_context] strategy → generate new JWT → continue session", - "Logout process → invalidate refresh token → clear client-side tokens in [focus_paths] components" + "User login → validate → generate JWT → return token", + "Protected route → extract JWT → validate → allow/deny" ] }, "target_files": [ @@ -150,185 +149,41 @@ All task files use this simplified 5-field schema: } ``` -### Focus Paths Field Details - -The **focus_paths** field within **context** specifies concrete project paths relevant to the task implementation: +### Focus Paths & Context Management #### Focus Paths Format +The **focus_paths** field specifies concrete project paths for task implementation: - **Array of strings**: `["folder1", "folder2", "specific_file.ts"]` - **Concrete paths**: Use actual directory/file names without wildcards - **Mixed types**: Can include both directories and specific files - **Relative paths**: From project root (e.g., `src/auth`, not `./src/auth`) -#### Path Selection Strategy -- **Directories**: Include relevant module directories (e.g., `src/auth`, `tests/auth`) -- **Specific files**: Include files explicitly mentioned in requirements (e.g., `config/auth.json`) -- **Avoid wildcards**: Use concrete paths discovered via `get_modules_by_depth.sh` -- **Focus scope**: Only include paths directly related to task implementation +#### Flow Control Configuration +The **flow_control** field manages task execution with two main components: -#### Examples -```json -// Authentication system task -"focus_paths": ["src/auth", "tests/auth", "config/auth.json", "src/middleware/auth.ts"] +**pre_analysis** - Context gathering phase: +- **Flexible commands**: Supports bash pipelines, CLI tools, and agent calls +- **Step structure**: Each step has `step`, `action`, `command` fields +- **Variable accumulation**: Steps can reference previous outputs via `[variable_name]` +- **Error handling**: `skip_optional`, `fail`, `retry_once`, `manual_intervention` -// UI component task -"focus_paths": ["src/components/Button", "src/styles", "tests/components"] +**implementation_approach** - Implementation definition: +- **task_description**: Comprehensive implementation description +- **modification_points**: Specific code modification targets +- **logic_flow**: Business logic execution sequence +- **target_files**: Target file list in `file:function:lines` format -// Database migration task -"focus_paths": ["migrations", "src/models", "config/database.json"] -``` +### Task Validation Rules +1. **ID Uniqueness**: All task IDs must be unique +2. **Hierarchical Format**: Must follow IMPL-N[.M] pattern (maximum 2 levels) +3. **Parent References**: All parent IDs must exist as JSON files +4. **Status Consistency**: Status values from defined enumeration +5. **Required Fields**: All 5 core fields must be present +6. **Focus Paths Structure**: context.focus_paths must contain valid project paths +7. **Flow Control Format**: pre_analysis must be array with required fields +8. **Dependency Integrity**: All depends_on task IDs must exist as JSON files -### Flow Control Field Details - -The **flow_control** field serves as a universal process manager for task execution with comprehensive flow orchestration: - -#### pre_analysis - Flexible Context Gathering - -**核心定位**: 纯上下文获取阶段,为实现准备充分信息 - -**四种灵活获取方式**: -- **文档引用**: `bash(cat 相关文档路径)` - 直接读取项目文档 -- **搜索命令**: `bash(grep/rg/find等)` - 灵活搜索代码模式 -- **CLI分析**: `bash(gemini/codex分析命令)` - 深度分析理解 -- **自由探索**: Agent自主使用Read、Grep、Search等工具 - -**设计原则**: -- **步骤数量自由**: 1-N步,按需求复杂度决定 -- **命令组合灵活**: 支持任意bash管道组合 -- **够用即可**: 不要过度设计,获取足够上下文即可 - -**基本步骤结构**: -- **step**: 步骤标识 -- **action**: 步骤描述 -- **command**: 执行命令(支持变量引用) -- **output_to**: 存储结果的变量名(可选) -- **on_error**: 错误处理策略 - -#### Context Flow Management -- **Variable Accumulation**: Each step can reference outputs from previous steps via `[variable_name]` -- **Context Inheritance**: Steps can use dependency summaries and parent task context -- **Pipeline Processing**: Results flow sequentially through the analysis chain - -#### Variable Reference Format -- **Context Variables**: Use `[variable_name]` to reference step outputs -- **Task Properties**: Use `[depends_on]`, `[focus_paths]` to reference task JSON properties -- **Bash Compatibility**: Avoids conflicts with bash `${}` variable expansion - -#### Path Reference Format -- **Session-Specific**: Use `.workflow/WFS-[session-id]/` for commands within active session context -- **Cross-Session**: Use `.workflow/*/` only when accessing multiple sessions (rare cases) -- **Relative Paths**: Use `.summaries/` when executing from within session directory - -#### Supported Context Acquisition Methods -- **Document Retrieval**: `bash(cat)` - Read CLAUDE.md, README and other documentation -- **Pattern Search**: `bash(rg)`, `bash(grep)`, `bash(find)` - Search for code patterns -- **Deep Analysis**: `bash(gemini-wrapper)` - Understand existing architecture and patterns -- **Autonomous Exploration**: Flexible combination of Read, Grep, Search and other tools -- **Pipeline Combinations**: Any bash command pipelines, supporting complex information processing - -#### Flexible Command Combination Examples - -**Basic Search**: -```bash -rg "auth|login" --type ts # Search authentication-related code -find . -name "*test*" | head # Find test files -cat CLAUDE.md # Read project specifications -``` - -**Dependency Task Summary References**: -```bash -# Reference completed task summary documents -cat .workflow/WFS-[session-id]/.summaries/IMPL-1.1-summary.md - -# Batch read dependency task summaries -for dep in IMPL-1.1 IMPL-1.2; do - cat .workflow/WFS-[session-id]/.summaries/${dep}-summary.md 2>/dev/null -done -``` - -**Combined Analysis**: -```bash -rg "interface.*Auth" | head -20 # Find interface definitions -find src -name "*.ts" | xargs rg -l "login" # Find related files -gemini-wrapper -p "analyze existing auth patterns" # Deep analysis -``` - -**Flexibility Principles**: -- Combine commands based on task requirements, don't mechanically copy examples -- Simple tasks may only need 1-2 search commands -- Complex tasks can design multi-step context accumulation -- Fully utilize the powerful combination capabilities of pipeline commands -- Reasonably reference prerequisite task summary documents as context - -#### Error Handling Strategies -- **skip_optional**: Continue execution, step result is empty -- **fail**: Stop execution, mark task as failed -- **retry_once**: Retry step once, then fail if still unsuccessful -- **manual_intervention**: Pause execution for manual review - -#### Flexible Design Examples - -**Simple Tasks** (1-2 step context gathering): -```json -"pre_analysis": [ - { - "step": "check_patterns", - "action": "Search existing patterns", - "command": "bash(rg 'login|auth' src/ | head -10)" - } -] -``` - -**Medium Tasks** (Multi-step context accumulation): -```json -"pre_analysis": [ - { - "step": "load_dependencies", - "action": "Read dependency task summaries", - "command": "bash(cat .workflow/WFS-[session-id]/.summaries/IMPL-1.1-summary.md)", - "output_to": "dependency_context" - }, - { - "step": "read_docs", - "action": "Read project specifications", - "command": "bash(cat CLAUDE.md)", - "output_to": "project_rules" - }, - { - "step": "find_similar", - "action": "Find similar implementations", - "command": "bash(rg 'class.*Service' src/)", - "output_to": "existing_services" - } -] -``` - -**Important**: These are references only, please design flexibly based on actual task requirements, don't mechanically copy. - -#### implementation_approach - Implementation Method Definition - -**Core Purpose**: Based on context gathered from pre_analysis, describe specific implementation strategies and methods - -**Four Design Principles**: -1. **Context Driven**: Fully utilize all context information collected during pre_analysis phase -2. **Pattern Following**: Implement based on discovered existing code patterns and project conventions -3. **Precise Targeting**: Clearly specify files, functions and code locations that need modification -4. **Clear Logic**: Describe clear implementation flow and business logic - -**Field Descriptions**: -- **task_description**: Comprehensive description, referencing context variables and inherited information -- **modification_points**: Specific code modification points, precise to files and functions -- **logic_flow**: Business logic flow, describing implementation execution sequence -- **target_files**: Target file list, format as `file:function:lines` - -#### Benefits of Flow Control -- **Universal Process Manager**: Handles any type of analysis or implementation flow -- **Context Accumulation**: Builds comprehensive context through step chain -- **Error Recovery**: Granular error handling at step level -- **Command Flexibility**: Supports any executable command or agent -- **Dependency Integration**: Automatic loading of prerequisite task results - -## File Structure +## Workflow Structure ### Unified File Structure All workflows use the same file structure definition regardless of complexity. **Directories and files are created on-demand as needed**, not all at once during initialization. @@ -353,10 +208,7 @@ All workflows use the same file structure definition regardless of complexity. * #### Creation Strategy - **Initial Setup**: Create only `workflow-session.json`, `IMPL_PLAN.md`, `TODO_LIST.md`, and `.task/` directory -- **On-Demand Creation**: Other directories created when first needed: - - `.brainstorming/` → When brainstorming phase is initiated - - `.chat/` → When CLI analysis commands are executed - - `.summaries/` → When first task is completed +- **On-Demand Creation**: Other directories created when first needed - **Dynamic Files**: Subtask JSON files created during task decomposition ### File Naming Conventions @@ -381,21 +233,8 @@ All workflows use the same file structure definition regardless of complexity. * - Chat sessions: `chat-analysis-*.md` - Task summaries: `IMPL-[task-id]-summary.md` - ### Document Templates -#### IMPL_PLAN.md Template -Generated based on task complexity and requirements. Contains overview, requirements, and task structure. - -**Notes for Future Tasks**: [Any important considerations, limitations, or follow-up items] - -**Summary Document Purpose**: -- **Context Inheritance**: Provides structured context for dependent tasks -- **Integration Guidance**: Offers clear integration points and usage instructions -- **Quality Assurance**: Documents testing and validation performed -- **Decision History**: Preserves rationale for implementation choices -- **Dependency Chain**: Enables automatic context accumulation through task dependencies - #### TODO_LIST.md Template ```markdown # Tasks: [Session Topic] @@ -404,23 +243,99 @@ Generated based on task complexity and requirements. Contains overview, requirem ▸ **IMPL-001**: [Main Task Group] → [📋](./.task/IMPL-001.json) - [ ] **IMPL-001.1**: [Subtask] → [📋](./.task/IMPL-001.1.json) - [x] **IMPL-001.2**: [Subtask] → [📋](./.task/IMPL-001.2.json) | [✅](./.summaries/IMPL-001.2.md) - -- [x] **IMPL-002**: [Simple Task] → [📋](./.task/IMPL-002.json) | [✅](./.summaries/IMPL-002.md) -▸ **IMPL-003**: [Main Task Group] → [📋](./.task/IMPL-003.json) - - [ ] **IMPL-003.1**: [Subtask] → [📋](./.task/IMPL-003.1.json) - - [ ] **IMPL-003.2**: [Subtask] → [📋](./.task/IMPL-003.2.json) +- [x] **IMPL-002**: [Simple Task] → [📋](./.task/IMPL-002.json) | [✅](./.summaries/IMPL-002.md) ## Status Legend - `▸` = Container task (has subtasks) -- `- [ ]` = Pending leaf task +- `- [ ]` = Pending leaf task - `- [x]` = Completed leaf task - Maximum 2 levels: Main tasks and subtasks only - -## Notes -[Optional notes] ``` +## Operations Guide + +### Session Management +```bash +# Create minimal required structure +mkdir -p .workflow/WFS-topic-slug/.task +echo '{"session_id":"WFS-topic-slug",...}' > .workflow/WFS-topic-slug/workflow-session.json +echo '# Implementation Plan' > .workflow/WFS-topic-slug/IMPL_PLAN.md +echo '# Tasks' > .workflow/WFS-topic-slug/TODO_LIST.md +``` + +### Task Operations +```bash +# Create task +echo '{"id":"IMPL-1","title":"New task",...}' > .task/IMPL-1.json + +# Update task status +jq '.status = "active"' .task/IMPL-1.json > temp && mv temp .task/IMPL-1.json + +# Generate TODO list from JSON state +generate_todo_list_from_json .task/ +``` + +### Directory Creation (On-Demand) +```bash +mkdir -p .brainstorming # When brainstorming is initiated +mkdir -p .chat # When analysis commands are run +mkdir -p .summaries # When first task completes +``` + +### Session Consistency Checks & Recovery +```bash +# Validate active session integrity +active_marker=$(find .workflow -name ".active-*" | head -1) +if [ -n "$active_marker" ]; then + session_name=$(basename "$active_marker" | sed 's/^\.active-//') + session_dir=".workflow/$session_name" + if [ ! -d "$session_dir" ]; then + echo "⚠️ Orphaned active marker, removing..." + rm "$active_marker" + fi +fi +``` + +**Recovery Strategies**: +- **Missing Session Directory**: Remove orphaned active marker +- **Multiple Active Markers**: Keep newest, remove others +- **Corrupted Session File**: Recreate from template +- **Broken Task Hierarchy**: Reconstruct parent-child relationships + +## Complexity Classification + +### Task Complexity Rules +**Complexity is determined by task count and decomposition needs:** + +| Complexity | Task Count | Hierarchy Depth | Decomposition Behavior | +|------------|------------|----------------|----------------------| +| **Simple** | <5 tasks | 1 level (IMPL-N) | Direct execution, minimal decomposition | +| **Medium** | 5-15 tasks | 2 levels (IMPL-N.M) | Moderate decomposition, context coordination | +| **Complex** | >15 tasks | 2 levels (IMPL-N.M) | Frequent decomposition, multi-agent orchestration | + +### Workflow Characteristics + +#### Simple Workflows +- **Examples**: Bug fixes, small feature additions, configuration changes +- **Task Decomposition**: Usually single-level tasks, minimal breakdown needed +- **Agent Coordination**: Direct execution without complex orchestration + +#### Medium Workflows +- **Examples**: New features, API endpoints with integration, database schema changes +- **Task Decomposition**: Two-level hierarchy when decomposition is needed +- **Agent Coordination**: Context coordination between related tasks + +#### Complex Workflows +- **Examples**: Major features, architecture refactoring, security implementations, multi-service deployments +- **Task Decomposition**: Frequent use of two-level hierarchy with dynamic subtask creation +- **Agent Coordination**: Multi-agent orchestration with deep context analysis + +### Assessment & Upgrades +- **During Creation**: System evaluates requirements and assigns complexity +- **During Execution**: Can upgrade (Simple→Medium→Complex) but never downgrade +- **Override Allowed**: Users can specify higher complexity manually + ## Agent Integration ### Agent Assignment @@ -442,106 +357,3 @@ Agents receive complete task JSON plus workflow context: } ``` -## Data Operations - -### Session Initialization -```bash -# Create minimal required structure -mkdir -p .workflow/WFS-topic-slug/.task -echo '{"session_id":"WFS-topic-slug",...}' > .workflow/WFS-topic-slug/workflow-session.json -echo '# Implementation Plan' > .workflow/WFS-topic-slug/IMPL_PLAN.md -echo '# Tasks' > .workflow/WFS-topic-slug/TODO_LIST.md -``` - -### Task Creation -```bash -echo '{"id":"IMPL-1","title":"New task",...}' > .task/IMPL-1.json -``` - -### Directory Creation (On-Demand) -```bash -# Create directories only when needed -mkdir -p .brainstorming # When brainstorming is initiated -mkdir -p .chat # When analysis commands are run -mkdir -p .summaries # When first task completes -``` - -### Task Updates -```bash -jq '.status = "active"' .task/IMPL-1.json > temp && mv temp .task/IMPL-1.json -``` - -### Document Generation -```bash -# Generate TODO_LIST.md from current JSON state -generate_todo_list_from_json .task/ -``` - -## Complexity Classification - -### Task Complexity Rules -**Complexity is determined by task count and decomposition needs:** - -| Complexity | Task Count | Hierarchy Depth | Decomposition Behavior | -|------------|------------|----------------|----------------------| -| **Simple** | <5 tasks | 1 level (IMPL-N) | Direct execution, minimal decomposition | -| **Medium** | 5-15 tasks | 2 levels (IMPL-N.M) | Moderate decomposition, context coordination | -| **Complex** | >15 tasks | 2 levels (IMPL-N.M) | Frequent decomposition, multi-agent orchestration | - -### Simple Workflows -**Characteristics**: Direct implementation tasks with clear, limited scope -- **Examples**: Bug fixes, small feature additions, configuration changes -- **Task Decomposition**: Usually single-level tasks, minimal breakdown needed -- **Agent Coordination**: Direct execution without complex orchestration - -### Medium Workflows -**Characteristics**: Feature implementation requiring moderate task breakdown -- **Examples**: New features, API endpoints with integration, database schema changes -- **Task Decomposition**: Two-level hierarchy when decomposition is needed -- **Agent Coordination**: Context coordination between related tasks - -### Complex Workflows -**Characteristics**: System-wide changes requiring detailed decomposition -- **Examples**: Major features, architecture refactoring, security implementations, multi-service deployments -- **Task Decomposition**: Frequent use of two-level hierarchy with dynamic subtask creation -- **Agent Coordination**: Multi-agent orchestration with deep context analysis - -### Automatic Assessment & Upgrades -- **During Creation**: System evaluates requirements and assigns complexity -- **During Execution**: Can upgrade (Simple→Medium→Complex) but never downgrade -- **Override Allowed**: Users can specify higher complexity manually - -## Validation and Error Handling - -### Task Integrity Rules -1. **ID Uniqueness**: All task IDs must be unique -2. **Hierarchical Format**: Must follow IMPL-N[.M] pattern (maximum 2 levels) -3. **Parent References**: All parent IDs must exist as JSON files -4. **Depth Limits**: Maximum 2 levels deep -5. **Status Consistency**: Status values from defined enumeration -6. **Required Fields**: All 5 core fields must be present (id, title, status, meta, context, flow_control) -7. **Focus Paths Structure**: context.focus_paths array must contain valid project paths -8. **Flow Control Format**: flow_control.pre_analysis must be array with step, action, command fields -9. **Dependency Integrity**: All context.depends_on task IDs must exist as JSON files - -### Session Consistency Checks -```bash -# Validate active session integrity -active_marker=$(find .workflow -name ".active-*" | head -1) -if [ -n "$active_marker" ]; then - session_name=$(basename "$active_marker" | sed 's/^\.active-//') - session_dir=".workflow/$session_name" - - if [ ! -d "$session_dir" ]; then - echo "⚠️ Orphaned active marker, removing..." - rm "$active_marker" - fi -fi -``` - -### Recovery Strategies -- **Missing Session Directory**: Remove orphaned active marker -- **Multiple Active Markers**: Keep newest, remove others -- **Corrupted Session File**: Recreate from template -- **Broken Task Hierarchy**: Reconstruct parent-child relationships -