#!/bin/bash

# Claude Run - Enhanced Development System
# Combines SPARC methodology with iterative planning and Claude CLI SDK integration
# Supports both automated development workflows and agent system integration

set -e  # Exit on any error

# Default configuration
PROJECT_NAME="claude-project"
README_PATH="README.md"
MCP_CONFIG="./mcp.json"
VERBOSE=false
DRY_RUN=false
SKIP_RESEARCH=false
SKIP_TESTS=false
TEST_COVERAGE_TARGET=100
PARALLEL_EXECUTION=true
COMMIT_FREQUENCY="phase"  # phase, feature, or manual
OUTPUT_FORMAT="text"
DEVELOPMENT_MODE="full"   # full, backend-only, frontend-only, api-only, agent-integration
WORKFLOW_MODE="iterative"     # sparc, iterative, hybrid
AGENT_SDK_PATH="claude-agent-system"
GITHUB_REPO=""
ITERATION_COUNT=3
METRICS_ENABLED=true
ARCHITECTURE_DIAGRAMS=true
ENABLE_MCP=true
ENV_FILE=".env"
MAX_PARALLELISM=10  # Global max parallel tasks
FORCE_PARALLEL=true  # Always seek parallelism opportunities
CHECKPOINT_ENABLED=true  # Enable implementation phase checkpoints
CHECKPOINT_TRIGGER="1-2"  # Trigger after 1-2 steps with few remaining

# Help function
show_help() {
    cat << EOF
Claude Run - Enhanced Development System
=======================================

A comprehensive development system combining SPARC methodology with iterative planning,
Claude CLI SDK integration, and advanced workflow management.

USAGE:
    ./claude-run.sh [OPTIONS] [PROJECT_NAME] [README_PATH]

ARGUMENTS:
    PROJECT_NAME    Name of the project to develop (default: claude-project)
    README_PATH     Path to requirements file (default: README.md, auto-searches for common names)

OPTIONS:
    -h, --help                  Show this help message
    -v, --verbose              Enable verbose output
    -d, --dry-run              Show what would be done without executing
    -c, --config FILE          MCP configuration file (default: ./mcp.json)
    
    # Workflow Options
    --workflow MODE            Workflow mode: sparc, iterative, hybrid (default: iterative)
    --iterations COUNT         Number of planning iterations (default: 3)
    --metrics                  Enable SPCT metrics evaluation (default: true)
    --no-metrics               Disable metrics evaluation
    
    # Research Options
    --skip-research            Skip the web research phase
    --research-depth LEVEL     Research depth: basic, standard, comprehensive (default: standard)
    
    # Development Options
    --mode MODE                Development mode: full, backend-only, frontend-only, api-only, agent-integration (default: full)
    --skip-tests               Skip test development (not recommended)
    --coverage TARGET          Test coverage target percentage (default: 100)
    --no-parallel              Disable parallel execution
    --max-parallel COUNT       Maximum parallel tasks globally (default: 10)
    --force-parallel           Always seek parallelism opportunities (default: true)
    
    # Agent Integration Options
    --agent-sdk PATH           Path to Claude agent SDK system (default: claude-agent-system)
    --enable-mcp               Enable MCP support in agent integration (default: true)
    --disable-mcp              Disable MCP support
    --env-file FILE            Environment file to source (default: .env)
    --input-mapping            Enable input file/folder mapping for agent system
    
    # Architecture Options
    --arch-diagrams            Generate architecture diagrams (default: true)
    --key-modules              Generate KEY_MODULES.md analysis
    --risk-analysis            Generate RISK_FACTORS.md analysis
    
    # Documentation Update Options
    --doc-update               Enable hierarchical CLAUDE.md updates (default: true)
    --no-doc-update            Disable hierarchical CLAUDE.md updates
    --doc-threshold LINES      Lines of code change threshold for doc updates (default: 100)
    --doc-parallelism COUNT    Max parallel agents for doc updates (default: 10)
    
    # Commit Options
    --commit-freq FREQ         Commit frequency: phase, feature, manual (default: phase)
    --no-commits               Disable automatic commits
    --github-repo REPO         GitHub repository for commits (format: owner/repo)
    
    # Output Options
    --output FORMAT            Output format: text, json, markdown (default: text)
    --quiet                    Suppress non-essential output
    
    # Checkpoint Options
    --enable-checkpoints       Enable implementation phase validation checkpoints (default: true)
    --disable-checkpoints      Disable implementation phase checkpoints
    --checkpoint-trigger STEPS Trigger checkpoints after N steps with few remaining (default: 1-2)
    
    # BatchTool Parallelization Options
    --batch-optimization       Enable maximum BatchTool usage validation (default: true)
    --min-parallel-tasks COUNT Minimum parallel tasks to launch when possible (default: 5)
    --parallel-efficiency PCT  Target parallel execution efficiency percentage (default: 80)

WORKFLOW MODES:
    sparc                Classic SPARC methodology (Specification, Pseudocode, Architecture, Refinement, Completion)
    iterative            Iterative planning with metrics evaluation and refinement (default)
    hybrid               Combines SPARC with iterative planning and comprehensive analysis

DEVELOPMENT MODES:
    full                 Complete full-stack development (default)
    backend-only         Backend services and APIs only
    frontend-only        Frontend application only
    api-only             REST/GraphQL API development only
    agent-integration    Claude CLI SDK agent system integration

EXAMPLES:
    # Basic SPARC development
    ./claude-run.sh my-app requirements.md
    
    # Using a custom requirements file
    ./claude-run.sh implement-this.md
    
    # Agent integration with iterative planning
    ./claude-run.sh --workflow iterative --mode agent-integration --enable-mcp agent-app readme2.md
    
    # Hybrid workflow with architecture analysis
    ./claude-run.sh --workflow hybrid --arch-diagrams --key-modules --risk-analysis my-project spec.md
    
    # Full development with GitHub integration
    ./claude-run.sh --github-repo myuser/myproject --iterations 5 full-app requirements.md
    
    # Development with custom documentation update settings
    ./claude-run.sh --doc-threshold 50 --doc-parallelism 15 my-project spec.md
    
    # Implementation with checkpoint validation enabled
    ./claude-run.sh --enable-checkpoints --checkpoint-trigger 2-3 my-project requirements.md
    
    # Fast development without checkpoints
    ./claude-run.sh --disable-checkpoints --workflow iterative my-project spec.md
    
    # Maximum parallelization with BatchTool optimization
    ./claude-run.sh --batch-optimization --min-parallel-tasks 7 --parallel-efficiency 90 my-project spec.md
    
    # High-performance development with comprehensive parallelization
    ./claude-run.sh --force-parallel --max-parallel 15 --batch-optimization my-project requirements.md

PHASES:
    1. Research & Discovery     - Comprehensive domain and technology research (BatchTool parallel research)
    2. Specification           - Requirements analysis and system specification (parallel spec development)
    3. Architecture            - System design with diagrams and analysis (concurrent architecture tasks)
    4. Iterative Planning      - Multi-round planning with metrics evaluation (parallel planning agents)
    5. Implementation          - TDD-based incremental development (maximum BatchTool parallelization)
    6. Integration & Testing   - Comprehensive testing and quality assurance (parallel test execution)
    7. Deployment             - Production readiness and deployment (parallel deployment tasks)

BATCHTOOL PARALLELIZATION FOCUS:
    • Core Principle: Always use BatchTool for multiple tool invocations in single requests
    • Minimum 5 parallel tasks launched when possible
    • >80% parallel execution efficiency target
    • Comprehensive checkpoint validation for parallelization compliance
    • Examples: 5 haikus = 1 BatchTool request (not 12 separate requests)

For more information, see claude-run-guide.md
EOF
}

# Parse command line arguments
parse_args() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            -v|--verbose)
                VERBOSE=true
                shift
                ;;
            -d|--dry-run)
                DRY_RUN=true
                shift
                ;;
            -c|--config)
                MCP_CONFIG="$2"
                shift 2
                ;;
            --workflow)
                WORKFLOW_MODE="$2"
                shift 2
                ;;
            --iterations)
                ITERATION_COUNT="$2"
                shift 2
                ;;
            --metrics)
                METRICS_ENABLED=true
                shift
                ;;
            --no-metrics)
                METRICS_ENABLED=false
                shift
                ;;
            --skip-research)
                SKIP_RESEARCH=true
                shift
                ;;
            --research-depth)
                RESEARCH_DEPTH="$2"
                shift 2
                ;;
            --mode)
                DEVELOPMENT_MODE="$2"
                shift 2
                ;;
            --skip-tests)
                SKIP_TESTS=true
                shift
                ;;
            --coverage)
                TEST_COVERAGE_TARGET="$2"
                shift 2
                ;;
            --no-parallel)
                PARALLEL_EXECUTION=false
                FORCE_PARALLEL=false
                shift
                ;;
            --max-parallel)
                MAX_PARALLELISM="$2"
                shift 2
                ;;
            --force-parallel)
                FORCE_PARALLEL=true
                shift
                ;;
            --agent-sdk)
                AGENT_SDK_PATH="$2"
                shift 2
                ;;
            --enable-mcp)
                ENABLE_MCP=true
                shift
                ;;
            --disable-mcp)
                ENABLE_MCP=false
                shift
                ;;
            --env-file)
                ENV_FILE="$2"
                shift 2
                ;;
            --input-mapping)
                INPUT_MAPPING=true
                shift
                ;;
            --arch-diagrams)
                ARCHITECTURE_DIAGRAMS=true
                shift
                ;;
            --key-modules)
                KEY_MODULES_ANALYSIS=true
                shift
                ;;
            --risk-analysis)
                RISK_ANALYSIS=true
                shift
                ;;
            --doc-update)
                DOCUMENTATION_UPDATE_ENABLED=true
                shift
                ;;
            --no-doc-update)
                DOCUMENTATION_UPDATE_ENABLED=false
                shift
                ;;
            --doc-threshold)
                DOCUMENTATION_UPDATE_THRESHOLD="$2"
                shift 2
                ;;
            --doc-parallelism)
                DOCUMENTATION_MAX_PARALLELISM="$2"
                shift 2
                ;;
            --commit-freq)
                COMMIT_FREQUENCY="$2"
                shift 2
                ;;
            --no-commits)
                COMMIT_FREQUENCY="manual"
                shift
                ;;
            --github-repo)
                GITHUB_REPO="$2"
                shift 2
                ;;
            --output)
                OUTPUT_FORMAT="$2"
                shift 2
                ;;
            --quiet)
                VERBOSE=false
                shift
                ;;
            --enable-checkpoints)
                CHECKPOINT_ENABLED=true
                shift
                ;;
            --disable-checkpoints)
                CHECKPOINT_ENABLED=false
                shift
                ;;
            --checkpoint-trigger)
                CHECKPOINT_TRIGGER="$2"
                shift 2
                ;;
            -*)
                echo "Unknown option: $1" >&2
                echo "Use --help for usage information" >&2
                exit 1
                ;;
            *)
                # If the argument looks like a file (has an extension), treat it as README_PATH
                if [[ "$1" == *.* ]] && [[ -f "$1" || ! -e "$1" ]]; then
                    # It's likely a file, use it as README_PATH
                    if [[ "$README_PATH" == "README.md" ]]; then
                        README_PATH="$1"
                        # If project name is still default, derive it from the file
                        if [[ "$PROJECT_NAME" == "claude-project" ]]; then
                            PROJECT_NAME="${1%.*}"  # Remove extension
                            PROJECT_NAME="${PROJECT_NAME##*/}"  # Remove path
                        fi
                    else
                        echo "Too many arguments: $1" >&2
                        echo "Use --help for usage information" >&2
                        exit 1
                    fi
                else
                    # No extension or is a directory, treat as project name
                    if [[ "$PROJECT_NAME" == "claude-project" ]]; then
                        PROJECT_NAME="$1"
                    elif [[ "$README_PATH" == "README.md" ]]; then
                        README_PATH="$1"
                    else
                        echo "Too many arguments: $1" >&2
                        echo "Use --help for usage information" >&2
                        exit 1
                    fi
                fi
                shift
                ;;
        esac
    done
}

# Validate configuration
validate_config() {
    # Check for ANTHROPIC_API_KEY and unset with warning
    if [[ -n "$ANTHROPIC_API_KEY" ]]; then
        echo "Warning: ANTHROPIC_API_KEY environment variable detected." >&2
        echo "Unsetting ANTHROPIC_API_KEY to use claude-cli authentication instead." >&2
        echo "The CLI uses its own authentication mechanism." >&2
        unset ANTHROPIC_API_KEY
    fi
    
    # Check for environment file (required whether default .env or custom specified)
    if [[ ! -f "$ENV_FILE" ]]; then
        echo "Error: Environment file not found: $ENV_FILE" >&2
        echo "Please create an environment file (can be empty):" >&2
        echo "  touch $ENV_FILE" >&2
        echo "Or specify a different file with: --env-file /path/to/.env" >&2
        exit 1
    fi
    
    # Source environment file
    if [[ "$VERBOSE" == true ]]; then
        echo "Sourcing environment file: $ENV_FILE" >&2
    fi
    # Export all variables from the env file
    set -a
    source "$ENV_FILE"
    set +a
    
    # Check if MCP config exists when MCP is enabled
    if [[ "$ENABLE_MCP" == true ]]; then
        # Check for npm and npx
        if ! command -v npm &> /dev/null; then
            echo "Error: npm is required for MCP but not found in PATH" >&2
            echo "Please install Node.js and npm: https://nodejs.org/" >&2
            exit 1
        fi
        
        if ! command -v npx &> /dev/null; then
            echo "Error: npx is required for MCP but not found in PATH" >&2
            echo "Please ensure npm is properly installed with npx" >&2
            exit 1
        fi
        
        if [[ ! -f "$MCP_CONFIG" ]]; then
            echo "Error: MCP is enabled but config file not found: $MCP_CONFIG" >&2
            echo "Please either:" >&2
            echo "  1. Create the MCP config file at: $MCP_CONFIG" >&2
            echo "  2. Specify a different config with: --config /path/to/mcp.json" >&2
            echo "  3. Disable MCP with: --disable-mcp" >&2
            echo "" >&2
            echo "Example MCP config structure:" >&2
            echo '{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/directory"]
    }
  }
}' >&2
            exit 1
        fi
    fi
    
    # Check if requirements file exists
    if [[ ! -f "$README_PATH" ]]; then
        # Only search for README alternatives if the user didn't specify a custom file
        if [[ "$README_PATH" == "README.md" ]]; then
            # User didn't specify a file, so try common README file variations
            local readme_alternatives=("README.md" "readme.md" "Readme.md" "README.txt" "readme.txt" "readme2.md")
            local found_readme=""
            
            for alt in "${readme_alternatives[@]}"; do
                if [[ -f "$alt" ]]; then
                    found_readme="$alt"
                    break
                fi
            done
            
            if [[ -n "$found_readme" ]]; then
                echo "README file '$README_PATH' not found, using '$found_readme' instead" >&2
                README_PATH="$found_readme"
            else
                # No README found - show interactive prompt instead of error
                echo "" >&2
                echo "Claude Run - Enhanced Development System" >&2
                echo "=======================================" >&2
                echo "" >&2
                echo "This system helps you build high-quality software using:" >&2
                echo "" >&2
                echo "Available Workflows:" >&2
                echo "  • SPARC: Specification → Pseudocode → Architecture → Refinement → Completion" >&2
                echo "  • Iterative: Multiple planning rounds with metrics-based refinement" >&2
                echo "  • Hybrid: Combines both approaches for maximum thoroughness" >&2
                echo "" >&2
                echo "Features:" >&2
                echo "  • Parallel execution optimization (up to ${MAX_PARALLELISM} concurrent tasks)" >&2
                echo "  • Test-driven development with ${TEST_COVERAGE_TARGET}% coverage target" >&2
                echo "  • Hierarchical documentation updates" >&2
                echo "  • MCP integration for enhanced capabilities" >&2
                echo "" >&2
                echo "To get started, please provide your requirements in one of these ways:" >&2
                echo "" >&2
                echo "1. Create a requirements file:" >&2
                echo "   echo '# My Project Requirements' > requirements.md" >&2
                echo "   ./claude-run.sh requirements.md" >&2
                echo "" >&2
                echo "2. Use any markdown file:" >&2
                echo "   ./claude-run.sh myproject.md" >&2
                echo "" >&2
                echo "3. Run with --help for all options:" >&2
                echo "   ./claude-run.sh --help" >&2
                echo "" >&2
                echo "What would you like to build today?" >&2
                exit 0
            fi
        else
            # User specified a custom file that doesn't exist
            echo "Error: Specified requirements file not found: $README_PATH" >&2
            echo "Please check the file path and try again." >&2
            exit 1
        fi
    fi
    
    # Validate workflow mode
    case $WORKFLOW_MODE in
        sparc|iterative|hybrid) ;;
        *) echo "Error: Invalid workflow mode: $WORKFLOW_MODE" >&2; exit 1 ;;
    esac
    
    # Validate development mode
    case $DEVELOPMENT_MODE in
        full|backend-only|frontend-only|api-only|agent-integration) ;;
        *) echo "Error: Invalid development mode: $DEVELOPMENT_MODE" >&2; exit 1 ;;
    esac
    
    # Validate commit frequency
    case $COMMIT_FREQUENCY in
        phase|feature|manual) ;;
        *) echo "Error: Invalid commit frequency: $COMMIT_FREQUENCY" >&2; exit 1 ;;
    esac
    
    # Validate output format
    case $OUTPUT_FORMAT in
        text|json|markdown) ;;
        *) echo "Error: Invalid output format: $OUTPUT_FORMAT" >&2; exit 1 ;;
    esac
    
    # Validate coverage target
    if [[ ! "$TEST_COVERAGE_TARGET" =~ ^[0-9]+$ ]] || [[ "$TEST_COVERAGE_TARGET" -lt 0 ]] || [[ "$TEST_COVERAGE_TARGET" -gt 100 ]]; then
        echo "Error: Invalid coverage target: $TEST_COVERAGE_TARGET (must be 0-100)" >&2
        exit 1
    fi
    
    # Validate iteration count
    if [[ ! "$ITERATION_COUNT" =~ ^[0-9]+$ ]] || [[ "$ITERATION_COUNT" -lt 1 ]] || [[ "$ITERATION_COUNT" -gt 10 ]]; then
        echo "Error: Invalid iteration count: $ITERATION_COUNT (must be 1-10)" >&2
        exit 1
    fi
    
    # Validate documentation update threshold
    if [[ ! "$DOCUMENTATION_UPDATE_THRESHOLD" =~ ^[0-9]+$ ]] || [[ "$DOCUMENTATION_UPDATE_THRESHOLD" -lt 1 ]]; then
        echo "Error: Invalid documentation update threshold: $DOCUMENTATION_UPDATE_THRESHOLD (must be positive integer)" >&2
        exit 1
    fi
    
    # Validate documentation update parallelism
    if [[ ! "$DOCUMENTATION_MAX_PARALLELISM" =~ ^[0-9]+$ ]] || [[ "$DOCUMENTATION_MAX_PARALLELISM" -lt 1 ]] || [[ "$DOCUMENTATION_MAX_PARALLELISM" -gt 20 ]]; then
        echo "Error: Invalid documentation update parallelism: $DOCUMENTATION_MAX_PARALLELISM (must be 1-20)" >&2
        exit 1
    fi
    
    # Validate checkpoint trigger format
    if [[ ! "$CHECKPOINT_TRIGGER" =~ ^[0-9]+-[0-9]+$ ]]; then
        echo "Error: Invalid checkpoint trigger format: $CHECKPOINT_TRIGGER (must be N-M format, e.g., 1-2)" >&2
        exit 1
    fi
    
    # Check agent SDK path if agent-integration mode
    if [[ "$DEVELOPMENT_MODE" == "agent-integration" ]] && [[ ! -d "$AGENT_SDK_PATH" ]]; then
        echo "Warning: Agent SDK path not found: $AGENT_SDK_PATH" >&2
        echo "Agent integration features may be limited" >&2
    fi
}

# Show configuration
show_config() {
    if [[ "$VERBOSE" == true ]]; then
        cat << EOF
Claude Run Configuration:
========================
Project Name: $PROJECT_NAME
README Path: $README_PATH
MCP Config: $MCP_CONFIG
Workflow Mode: $WORKFLOW_MODE
Development Mode: $DEVELOPMENT_MODE
Iterations: $ITERATION_COUNT
Research Depth: ${RESEARCH_DEPTH:-standard}
Test Coverage Target: $TEST_COVERAGE_TARGET%
Parallel Execution: $PARALLEL_EXECUTION
Force Parallel: $FORCE_PARALLEL
Max Parallelism: $MAX_PARALLELISM agents
Commit Frequency: $COMMIT_FREQUENCY
GitHub Repo: ${GITHUB_REPO:-none}
Output Format: $OUTPUT_FORMAT
Metrics Enabled: $METRICS_ENABLED
Architecture Diagrams: $ARCHITECTURE_DIAGRAMS
Documentation Updates: $DOCUMENTATION_UPDATE_ENABLED
Doc Update Threshold: $DOCUMENTATION_UPDATE_THRESHOLD lines
Doc Update Parallelism: $DOCUMENTATION_MAX_PARALLELISM agents
MCP Enabled: $ENABLE_MCP
Skip Research: $SKIP_RESEARCH
Skip Tests: $SKIP_TESTS
Checkpoints Enabled: $CHECKPOINT_ENABLED
Checkpoint Trigger: $CHECKPOINT_TRIGGER steps
Dry Run: $DRY_RUN
========================
EOF
    fi
}

# Build allowed tools based on configuration
build_allowed_tools() {
    local tools="View,Edit,Replace,GlobTool,GrepTool,LS,Bash"
    
    if [[ "$SKIP_RESEARCH" != true ]]; then
        tools="$tools,WebFetchTool"
    fi
    
    if [[ "$PARALLEL_EXECUTION" == true ]]; then
        tools="$tools,BatchTool,dispatch_agent"
    fi
    
    if [[ -n "$GITHUB_REPO" ]]; then
        tools="$tools,mcp__github__create_repository,mcp__github__create_or_update_file,mcp__github__push_files"
    fi
    
    if [[ "$DEVELOPMENT_MODE" == "agent-integration" ]] && [[ "$ENABLE_MCP" == true ]]; then
        tools="$tools,mcp__puppeteer__puppeteer_navigate,mcp__puppeteer__puppeteer_screenshot"
    fi
    
    echo "$tools"
}

# Build Claude command flags
build_claude_flags() {
    local flags="--mcp-config $MCP_CONFIG --dangerously-skip-permissions"
    
    if [[ "$VERBOSE" == true ]]; then
        flags="$flags --verbose"
    fi
    
    if [[ "$OUTPUT_FORMAT" != "text" ]]; then
        flags="$flags --output-format $OUTPUT_FORMAT"
    fi
    
    echo "$flags"
}

# Generate workflow prompt based on mode
generate_workflow_prompt() {
    local prompt=""
    
    # Header with explicit parallel execution mandate
    prompt+="# Claude Run - Enhanced Development System\n"
    prompt+="# Project: ${PROJECT_NAME}\n"
    prompt+="# Requirements: ${README_PATH}\n"
    prompt+="# Workflow: ${WORKFLOW_MODE}\n"
    prompt+="# Mode: ${DEVELOPMENT_MODE}\n"
    prompt+="\n"
    prompt+="## ⚠️  CRITICAL PARALLEL EXECUTION MANDATE ⚠️\n"
    prompt+="### YOU MUST LAUNCH PARALLEL TASKS - NOT SEQUENTIAL EXECUTION\n"
    prompt+="\n"
    prompt+="**MANDATORY BEHAVIOR**: This system requires PARALLEL task execution.\n"
    prompt+="- ALWAYS decompose complex tasks into ${MAX_PARALLELISM} concurrent tasks\n"
    prompt+="- LAUNCH multiple Task() commands simultaneously\n"
    prompt+="- NEVER execute tasks one-by-one when they can run in parallel\n"
    prompt+="- USE Task(specific_action) syntax for parallel execution\n"
    prompt+="- EXAMPLE: Instead of sequential file reading, launch:\n"
    prompt+="  Task(read file1.py), Task(read file2.py), Task(read file3.py) concurrently\n"
    prompt+="\n"
    prompt+="**FAILURE TO EXECUTE IN PARALLEL VIOLATES SYSTEM REQUIREMENTS**\n"
    prompt+="\n"
    
    # Include research phase unless skipped
    if [[ "$SKIP_RESEARCH" != true ]]; then
        prompt+="\n$(generate_research_phase)"
    fi
    
    # Include workflow-specific phases
    case $WORKFLOW_MODE in
        sparc)
            prompt+="\n$(generate_sparc_phases)"
            ;;
        iterative)
            prompt+="\n$(generate_iterative_phases)"
            ;;
        hybrid)
            prompt+="\n$(generate_hybrid_phases)"
            ;;
    esac
    
    # Include implementation phase (with checkpoints if enabled)
    if [[ "$CHECKPOINT_ENABLED" == true ]]; then
        prompt+="\n$(generate_implementation_phase)"
    else
        prompt+="\n$(generate_implementation_phase_no_checkpoints)"
    fi
    
    # Include quality standards
    prompt+="\n$(generate_quality_standards)"
    
    # Include parallel execution principles if force parallel is enabled
    if [[ "$FORCE_PARALLEL" == true ]]; then
        prompt+="\n$(generate_parallel_principles)"
    fi
    
    # Include documentation update phase if enabled
    if [[ "$DOCUMENTATION_UPDATE_ENABLED" == true ]]; then
        prompt+="\n$(generate_documentation_update_phase)"
    fi
    
    echo -e "$prompt"
}

# Generate research phase
generate_research_phase() {
    cat << 'RESEARCH_PHASE'
## PHASE 0: COMPREHENSIVE PARALLEL RESEARCH & DISCOVERY
### MANDATORY PARALLEL EXECUTION: ${MAX_PARALLELISM} concurrent tasks MUST be launched
### Research Depth: ${RESEARCH_DEPTH:-standard}

### EXPLICIT PARALLEL RESEARCH EXECUTION:

**Stage 1: LAUNCH ${MAX_PARALLELISM} CONCURRENT RESEARCH TASKS IMMEDIATELY**
You MUST launch these parallel Task() commands simultaneously:
```
Task(Domain analysis from ${README_PATH})
Task(Technology landscape research)
Task(Competitive analysis)
Task(Best practices investigation)
Task(Security & compliance research)
Task(Testing framework analysis)
Task(Deployment pattern research)
Task(Performance optimization strategies)
Task(Monitoring solutions research)
Task(Architecture pattern discovery)
```
DO NOT execute these sequentially - ALL must run in parallel.

**Stage 2: Deep-Dive Parallel Research** (Based on Stage 1 results)
Analyze Stage 1 results, then launch parallel deep-dives:
- For each identified technology: research implementation details
- For each architectural pattern: find concrete examples
- For each security concern: investigate mitigation strategies
- For each performance consideration: research optimization techniques

$(if [[ "$DEVELOPMENT_MODE" == "agent-integration" ]]; then cat << 'AGENT_RESEARCH'
**Stage 3: Agent-Specific Parallel Research**
- Claude CLI SDK capabilities analysis
- MCP integration pattern research
- Multi-agent orchestration strategies
- Parallel workflow management techniques
AGENT_RESEARCH
fi)

### Parallel Results Synthesis:
1. Gather all parallel research results
2. Identify common patterns and conflicts
3. Create unified technology recommendations
4. Generate prioritized implementation approach

**Commit**: 'feat: complete parallel research - ${MAX_PARALLELISM} concurrent investigations synthesized'
RESEARCH_PHASE
}

# Generate SPARC phases
generate_sparc_phases() {
    cat << 'SPARC_PHASES'
## SPECIFICATION PHASE - PARALLEL DECOMPOSITION
### Parallel Specification Strategy:

**Stage 1: High-Level Specification Outline** (Single task)
- Analyze ${README_PATH} to create system overview
- Identify major components and subsystems
- Define component boundaries for parallel analysis

**Stage 2: LAUNCH ${MAX_PARALLELISM} CONCURRENT SPECIFICATION TASKS**
You MUST launch these parallel Task() commands simultaneously:
```
Task(API specification - endpoints, models, auth)
Task(Frontend specification - UI/UX, workflows)
Task(Data layer specification - schemas, relationships)
Task(Integration specification - external services)
Task(Security specification - auth, encryption)
Task(Performance specification - metrics, SLAs)
Task(Infrastructure specification - deployment)
Task(Testing specification - strategies, coverage)
Task(Monitoring specification - observability)
Task(Documentation specification - user/dev docs)
```
CRITICAL: These MUST run concurrently, not one after another.

**Stage 3: Parallel Deep-Dive Specifications**
For each component from Stage 2, parallelize sub-specifications:
- API: Parallelize endpoint groups (user, admin, public, etc.)
- Frontend: Parallelize page/feature specifications
- Data: Parallelize domain model specifications
- Security: Parallelize threat model components

**Stage 4: Specification Integration**
- Gather all parallel specifications
- Resolve cross-component dependencies
- Create unified specification document
- Validate completeness and consistency

**Commit**: 'docs: complete parallel specification - ${MAX_PARALLELISM} concurrent component specs integrated'

## PSEUDOCODE PHASE - PARALLEL ALGORITHM DESIGN
### Parallel Algorithm Development:

**Stage 1: Component Interface Design** (${MAX_PARALLELISM} agents)
Parallel Task agents design interfaces for each component:
- API contracts and protocols
- Frontend component interfaces
- Data access layer interfaces
- Service communication protocols
- Event/message schemas

**Stage 2: Parallel Algorithm Implementation** (per component)
For each component, parallelize algorithm design:
- Business logic algorithms (parallel by domain)
- Data transformation pipelines (parallel by data type)
- Validation and security checks (parallel by component)
- Performance optimization strategies (parallel by bottleneck)

**Stage 3: Test Strategy Parallelization**
- Unit test design per component (parallel)
- Integration test scenarios (parallel by interaction)
- E2E test workflows (parallel by user journey)
- Performance test suites (parallel by load type)

**Commit**: 'design: complete parallel pseudocode - ${MAX_PARALLELISM} concurrent algorithm designs'

## ARCHITECTURE PHASE - PARALLEL DEEP DESIGN
### Parallel Architecture Generation:

**Stage 1: Architecture Decomposition**
- Create high-level architecture outline
- Identify architectural components for parallel design
- Define integration boundaries

**Stage 2: Parallel Architecture Design** (${MAX_PARALLELISM} agents)
$(if [[ "$ARCHITECTURE_DIAGRAMS" == true ]]; then cat << 'ARCH_PARALLEL'
Launch parallel agents for architectural diagrams:
- System architecture diagram
- Component interaction diagrams
- Data flow diagrams
- Deployment architecture
- Security architecture
- Network topology
- CI/CD pipeline architecture
- Monitoring architecture
ARCH_PARALLEL
fi)

$(if [[ "$KEY_MODULES_ANALYSIS" == true ]]; then cat << 'KEY_MODULES_PARALLEL'
**Stage 3: Parallel Key Modules Analysis**
- Identify top-level critical modules
- Launch parallel analysis for each module:
  * Module specifications
  * Success factors
  * Dependencies
  * Risk factors
  * Performance characteristics
KEY_MODULES_PARALLEL
fi)

$(if [[ "$RISK_ANALYSIS" == true ]]; then cat << 'RISK_PARALLEL'
**Stage 4: Parallel Risk Analysis**
- Identify risk categories
- Parallel risk assessment per category:
  * Technical risks
  * Security risks
  * Performance risks
  * Scalability risks
  * Integration risks
  * Operational risks
RISK_PARALLEL
fi)

**Stage 5: Architecture Integration**
- Synthesize all parallel architectural designs
- Resolve conflicts and dependencies
- Create unified ARCHITECTURE.md
- Validate architectural consistency

**Commit**: 'arch: complete parallel architecture - ${MAX_PARALLELISM} concurrent designs integrated'

## REFINEMENT PHASE - PARALLEL TDD IMPLEMENTATION
### Parallel Development Strategy:
Create folder structure for parallel execution:
- 1_parallel/: Independent modules (auth, user, admin, api)
- 2_parallel/: Service layers (business, data, integration)
- 3_parallel/: Frontend components (pages, widgets, utils)
- 4_integration/: Sequential integration phase

Each parallel folder contains tasks that can execute concurrently.
SPARC_PHASES
}

# Generate iterative phases
generate_iterative_phases() {
    cat << 'ITERATIVE_PHASES'
## ITERATIVE PLANNING PHASE - MAXIMIZING PARALLELISM
### Parallel Planning Strategy:

**Initial Planning - Parallel Decomposition**:
1. **System Analysis** (Single task):
   - Extract high-level requirements from ${README_PATH}
   - Identify independent subsystems for parallel planning
   - Define integration points between subsystems

2. **Parallel Subsystem Planning** (${MAX_PARALLELISM} agents):
   Launch parallel Task agents to plan each subsystem:
   - Frontend planning (components, routes, state)
   - Backend API planning (endpoints, middleware, auth)
   - Data layer planning (models, migrations, queries)
   - Infrastructure planning (deployment, scaling, monitoring)
   - Testing planning (unit, integration, e2e strategies)
   - Security planning (auth, encryption, validation)
   - Performance planning (caching, optimization, CDN)
   - Documentation planning (user guides, API docs)

3. **Parallel Step Organization**:
   Create folder structure emphasizing parallelism:
   ```
   plan_r${iteration}/
   ├── 1_parallel/     # Independent foundation tasks
   │   ├── setup_dev_env.md
   │   ├── create_project_structure.md
   │   ├── configure_tools.md
   │   └── initialize_repos.md
   ├── 2_parallel/     # Core module development
   │   ├── auth_module.md
   │   ├── user_module.md
   │   ├── data_models.md
   │   └── api_framework.md
   ├── 3_parallel/     # Feature development
   │   ├── frontend_components.md
   │   ├── backend_services.md
   │   ├── database_layer.md
   │   └── external_integrations.md
   └── 4_sequential/   # Integration only
       └── system_integration.md
   ```

### Iterative Refinement (${ITERATION_COUNT} iterations):
For iteration in 1..${ITERATION_COUNT}:
   1. **Parallel Evaluation** (${MAX_PARALLELISM} agents):
      - Each agent evaluates different aspects:
        * SPCT metrics evaluation
        * Dependency analysis
        * Risk assessment
        * Resource optimization
        * Parallelism opportunities
   
   2. **Parallel Deep Research**:
      Based on gaps found, launch parallel research:
      - Technology-specific best practices
      - Performance optimization techniques
      - Security hardening approaches
      - Testing methodology improvements
   
   3. **Parallel Plan Refinement**:
      - Each subsystem refined by dedicated agent
      - Maximize parallel execution opportunities
      - Minimize sequential bottlenecks
      - Optimize resource utilization
   
   4. **Integration Validation**:
      - Verify parallel steps don't conflict
      - Ensure clean integration points
      - Validate end-to-end workflows
      - Confirm parallel execution feasibility

### Final Parallel Plan:
- Structure: plan_final/ with maximized parallelism
- Each step annotated with:
  * Dependencies (what must complete first)
  * Outputs (what this step produces)
  * Integration points (how results combine)
  * Estimated parallel execution time
- Clear integration checkpoints between parallel phases

**Commit**: 'plan: iterative planning optimized for ${MAX_PARALLELISM}-way parallelism'
ITERATIVE_PHASES
}

# Generate hybrid phases
generate_hybrid_phases() {
    cat << 'HYBRID_PHASES'
## HYBRID WORKFLOW: SPARC + ITERATIVE PLANNING

### Phase 1: SPARC Foundation
$(generate_sparc_phases)

### Phase 2: Iterative Enhancement
$(generate_iterative_phases)

### Phase 3: Integration & Synthesis
1. **Architecture Refinement**:
   - Merge SPARC architecture with iterative insights
   - Update ARCHITECTURE.md with comprehensive diagrams
   - Refine component interactions based on planning
   - Optimize for identified critical success factors

2. **Risk Mitigation**:
   - Address all identified risks from both methodologies
   - Create contingency plans for high-risk areas
   - Design fallback strategies for critical components
   - Update RISK_FACTORS.md with mitigation strategies

3. **Module Optimization**:
   - Focus development on key modules from KEY_MODULES.md
   - Prioritize critical success factors
   - Design for maximum impact on project outcomes
   - Create detailed implementation guides

**Commit**: 'arch: complete hybrid workflow synthesis - integrated SPARC and iterative methodologies'
HYBRID_PHASES
}

# Generate implementation phase
generate_implementation_phase() {
    cat << 'IMPLEMENTATION_PHASE'
## IMPLEMENTATION PHASE - MASSIVE PARALLELIZATION WITH CHECKPOINT VALIDATION
### Parallel-First Development Strategy with Quality Gates:

**Phase 1: LAUNCH ${MAX_PARALLELISM} CONCURRENT FOUNDATION TASKS**
You MUST execute these parallel Task() commands simultaneously:
```
Task(Development environment setup)
Task(Project scaffolding - frontend, backend, infra)
Task(Tool configuration - linters, formatters, CI)
Task(Repository initialization)
Task(Dependency installation)
Task(Database setup)
Task(Container configuration)
Task(Testing framework setup)
```
MANDATORY: All foundation tasks MUST run in parallel, not sequentially.

**Phase 2: Parallel Module Development** (2_parallel/)
For each independent module, launch parallel agents:

*Backend Modules* (parallel execution):
- Auth service (JWT, OAuth, sessions)
- User management service
- Core business logic services
- Data access layer
- API gateway setup
- Middleware components
- Background job processors
- Cache layer implementation

*Frontend Modules* (parallel execution):
- Component library setup
- Page components
- State management
- Routing configuration
- API client services
- Utility functions
- Style system
- Asset management

*Infrastructure Modules* (parallel execution):
- Docker configurations
- Kubernetes manifests
- CI/CD pipelines
- Monitoring setup
- Logging configuration
- Security policies
- Backup strategies
- Load balancer config

**Phase 3: Parallel Testing** (3_parallel/)
Launch ${MAX_PARALLELISM} test agents:
- Unit tests per module (parallel)
- Integration tests per service (parallel)
- API endpoint tests (parallel by route)
- Frontend component tests (parallel)
- Performance tests (parallel scenarios)
- Security tests (parallel vulnerabilities)
- Load tests (parallel user patterns)

**Phase 4: Parallel Integration & Optimization**
While maintaining module independence:
- Parallel API integration tests
- Parallel frontend-backend integration
- Parallel performance optimization
- Parallel security hardening
- Parallel documentation generation

**Phase 5: Final Sequential Integration** (4_sequential/)
Only truly sequential tasks:
- System-wide integration test
- End-to-end user flow validation
- Production deployment preparation
- Final documentation review

## 🔍 CRITICAL IMPLEMENTATION CHECKPOINT SYSTEM
### MANDATORY VALIDATION AFTER 1-2 STEPS WITH FEW REMAINING

**CHECKPOINT TRIGGER CONDITIONS:**
- After completing 1-2 implementation steps
- When few steps remain (typically 2-3 steps left)
- Before final integration phase
- When significant architectural decisions are made

**CHECKPOINT VALIDATION REQUIREMENTS:**

### 1. BatchTool Parallelization Compliance Validation
**🚀 CRITICAL PARALLEL EXECUTION MANDATE**: Verify maximum parallelism implementation:

**Core Principle Enforcement:**
- ✅ **MANDATORY**: Always use BatchTool to run multiple tool invocations in a single request
- ✅ **RULE**: If k tool invocations can be made in one request, make ONE request with k invocations using BatchTool, NOT k different requests
- ✅ **VERIFICATION**: Check implementation uses BatchTool/parallel approaches instead of sequential tool usage
- ✅ **VALIDATION**: Confirm minimum 5 parallel tasks launched when applicable
- ✅ **ANALYSIS**: Identify and flag any missed parallelization opportunities

**BatchTool Implementation Pattern Validation:**

**✅ File Creation Pattern Compliance:**
- **INCORRECT PATTERN**: Write 5 haikus → 12 tool uses in separate requests ❌
- **CORRECT PATTERN**: Use BatchTool with 5 Write tool calls in single batch request ✅
- **VALIDATION**: Verify file creation operations use BatchTool for multiple files
- **CHECK**: Confirm no sequential file creation when batch creation is possible

**✅ Multi-Language Development Pattern:**
- **CORRECT PATTERN**: 2 Python + 2 Rust + 1 TypeScript scripts → 5 parallel Task tools with comprehensive todo tracking ✅
- **VALIDATION**: Verify different language files created in parallel batches
- **CHECK**: Confirm Update Todos tracks all parallel work appropriately

**✅ Research and Implementation Pattern:**
- **CORRECT PATTERN**: Deep research → Multiple parallel Task tools for different research aspects ✅
- **CORRECT PATTERN**: Implementation → Parallel Task tools for backend/frontend modules ✅
- **VALIDATION**: Verify research tasks launched in parallel, not sequentially
- **CHECK**: Confirm implementation modules developed concurrently

**✅ Complex Application Development Pattern:**
- **CORRECT PATTERN**: Trivia quiz app → 7 parallel research tasks, then 6 parallel backend tasks, then 6 parallel frontend tasks ✅
- **VALIDATION**: Verify complex applications broken into parallel development phases
- **CHECK**: Confirm each phase maximizes parallel task execution

**Key Parallelization Patterns to Enforce:**
- ✅ Use Update Todos to track parallel work progress
- ✅ Launch minimum 5 parallel tasks when possible (verify this threshold)
- ✅ Think harder to find parallelization opportunities (document analysis)
- ✅ Use Task tools for complex parallel work coordination
- ✅ Use Write tools in batches for simple file operations
- ✅ Maximize speed through high parallelism (measure and validate)

**Parallelization Opportunity Detection:**
- 🔍 **SCAN**: Review all tool invocations for sequential patterns
- 🔍 **IDENTIFY**: Find operations that could be batched together
- 🔍 **ANALYZE**: Determine if parallel execution was maximized
- 🔍 **VALIDATE**: Confirm no artificial sequencing where parallel is possible
- 🔍 **OPTIMIZE**: Suggest improvements for better parallelization

### 2. Architecture Consistency Validation
**MANDATORY CHECK**: Compare current implementation against plan_wholistic reference:
- ✅ Verify alignment with ARCHITECTURE_FLOW.md session management principles
- ✅ Validate against 1_SPECIFICATIONS.md core requirements
- ✅ Confirm implementation of 2_KEY_MODULES.md critical components
- ✅ Address all 3_RISK_FACTORS.md identified risks and mitigations
- ✅ Ensure orchestrator session continuity (always use -r when session exists)
- ✅ Verify workers start fresh from orchestrator (no -r inheritance)
- ✅ Confirm worker error recovery uses worker's own sessions only
- ✅ Validate phase transitions use orchestrator sessions exclusively

### 3. Implementation Drift Detection
**CRITICAL ANALYSIS**: Identify and correct any deviations:
- 🚨 Check for goal drift from original architecture specifications
- 🚨 Detect hallucination or false assumptions not in plan_wholistic
- 🚨 Verify no task reuse violations (each execution must create new task)
- 🚨 Confirm timeout handling follows specified recovery patterns
- 🚨 Validate session tracking separates orchestrator vs worker contexts
- 🚨 Ensure no mixing of orchestrator and worker session management
- 🚨 **NEW**: Detect sequential tool usage where BatchTool parallelization was possible
- 🚨 **NEW**: Flag missed opportunities for parallel task execution

### 4. Real API vs Mock Validation
**VERIFICATION REQUIRED**:
- ✅ Confirm using real Claude API, not mock implementations
- ✅ Verify actual session management with real API responses
- ✅ Test timeout scenarios with real API timeouts (not simulated)
- ✅ Validate error recovery with actual API error responses
- ✅ Ensure integration tests use real API endpoints

### 5. Human-Proof Implementation Analysis
**ROBUSTNESS TESTING**: Think like end users and identify failure points:
- 🔧 How will users misuse the session management system?
- 🔧 What happens when users interrupt multi-phase execution?
- 🔧 How does the system handle unexpected API timeouts?
- 🔧 What if users manually modify session files?
- 🔧 How does error recovery work with corrupted session data?
- 🔧 What happens with concurrent phase executions?
- 🔧 How does the system handle network interruptions?

### 6. Comprehensive Failure Mode Analysis
**EDGE CASE VALIDATION**: Consider all potential failure scenarios:
- ⚠️ Orchestrator timeout during worker execution
- ⚠️ Worker timeout on first execution (no session)
- ⚠️ Worker timeout after successful execution (has session)
- ⚠️ Mixed worker results (some succeed, some fail)
- ⚠️ Phase transition with incomplete orchestrator sessions
- ⚠️ Concurrent session updates from multiple workers
- ⚠️ API rate limiting during parallel execution
- ⚠️ Disk space exhaustion during session storage
- ⚠️ Memory issues with large session histories
- ⚠️ Network partitions during distributed execution

### 7. MANDATORY INTERIM REPORTING
**REQUIRED DELIVERABLES**: Generate these specific reports:

**Brief Report** (steps[X-Y]-interim-report-brief.md):
- Executive summary of implementation progress
- Key architectural decisions made
- Critical success factors achieved
- Major risks mitigated
- **BatchTool Parallelization Summary**: Overall parallel execution efficiency
- **Parallel Task Metrics**: Number of concurrent tasks launched
- **Symmetries Testing Summary**: Overview of symmetric testing strategies implemented
- **Testing Efficiency Gains**: Quantified improvements from symmetry exploitation
- Next steps prioritization

**Detailed Report** (steps[X-Y]-interim-report-detailed.md):
- Complete implementation status against plan_wholistic
- Detailed session management implementation analysis
- Worker vs orchestrator separation validation
- Timeout handling mechanism verification
- Error recovery path testing results
- Integration point validation
- Performance characteristics analysis
- **BatchTool Usage Analysis**: Detailed breakdown of parallel vs sequential tool usage
- **Parallelization Pattern Compliance**: Validation against required patterns
- **Parallel Task Coordination**: Analysis of concurrent task management
- **Efficiency Metrics**: Measurement of parallel execution performance
- **Symmetries Analysis**: Comprehensive mapping of all identified symmetries
- **Symmetric Testing Implementation**: Detailed analysis of symmetric test templates and patterns
- **Cross-Component Bug Detection**: Analysis of symmetric bug detection effectiveness
- **Testing Pattern Compliance**: Validation of symmetric testing pattern implementation

**Gaps Report** (steps[X-Y]-interim-report-gaps.md):
- Identified deviations from ARCHITECTURE_FLOW.md
- Missing components from 2_KEY_MODULES.md
- Unaddressed risks from 3_RISK_FACTORS.md
- Implementation shortcuts that need correction
- Technical debt introduced during implementation
- Testing gaps requiring attention
- Documentation inconsistencies
- **Parallelization Gaps**: Missed opportunities for BatchTool usage
- **Sequential Pattern Issues**: Operations that should be parallel but aren't
- **Batch Optimization Opportunities**: Ways to improve parallel execution
- **Parallel Task Deficiencies**: Areas where minimum 5 parallel tasks weren't launched
- **Symmetries Testing Gaps**: Missed opportunities for symmetric testing strategies
- **Cross-Component Testing Deficiencies**: Areas where symmetric bug detection wasn't implemented
- **Testing Efficiency Shortfalls**: Gaps in leveraging symmetries for testing optimization
- **Pattern-Based Testing Gaps**: Missing symmetric test templates and patterns

**NEW: Parallelization Analysis Report** (steps[X-Y]-interim-report-parallelization.md):
- **Tool Usage Audit**: Complete analysis of all tool invocations
- **BatchTool Compliance**: Verification of batch operation usage
- **Parallel Task Distribution**: Analysis of concurrent task allocation
- **Sequential Operation Justification**: Documentation of truly sequential operations
- **Parallelization Opportunities**: Identified improvements for future phases
- **Efficiency Measurements**: Quantitative analysis of parallel execution benefits
- **Pattern Compliance Matrix**: Validation against all required parallelization patterns
- **Recommendations**: Specific actions to improve parallelization in remaining work

**NEW: Symmetries Testing Analysis Report** (steps[X-Y]-interim-report-symmetries.md):
- **Symmetry Mapping**: Complete identification and mapping of all symmetric components
- **Symmetric Testing Coverage**: Analysis of symmetric test template implementation
- **Cross-Component Bug Detection**: Effectiveness of symmetric bug detection strategies
- **Testing Efficiency Metrics**: Quantified improvements from symmetry exploitation
- **Pattern-Based Testing Analysis**: Validation of symmetric testing pattern compliance
- **Differential Testing Results**: Analysis of symmetric component comparison testing
- **Symmetry Violation Detection**: Identification of unintentional asymmetries
- **Testing Optimization Recommendations**: Specific actions to improve symmetric testing strategies

### 8. Checkpoint Execution Protocol
**STEP-BY-STEP VALIDATION PROCESS:**

1. **Pause Implementation**: Stop all parallel tasks
2. **BatchTool Parallelization Audit**: Analyze all tool usage for parallelization compliance
3. **Symmetries Analysis**: Identify and map all symmetric modules, phases, and components
4. **Symmetric Testing Validation**: Verify symmetric test templates and cross-component bug detection
5. **Architecture Review**: Compare against plan_wholistic files
6. **Drift Analysis**: Identify any deviations or assumptions
7. **API Verification**: Confirm real API usage, not mocks
8. **Failure Mode Testing**: Execute edge case scenarios
9. **Human Usage Simulation**: Test with realistic user behaviors
10. **Parallelization Gap Analysis**: Identify missed parallel execution opportunities
11. **Symmetry-Based Testing Efficiency**: Measure testing efficiency improvements through symmetry exploitation
12. **Report Generation**: Create all interim reports plus parallelization and symmetries analysis
13. **Gap Remediation**: Fix identified issues before proceeding
14. **Validation Confirmation**: Verify all checkpoints passed including BatchTool and symmetries compliance
15. **Implementation Resume**: Continue with validated parallel-first and symmetry-optimized approach

### 9. Checkpoint Success Criteria
**MUST ACHIEVE BEFORE CONTINUING:**
- ✅ **BatchTool Parallelization Compliance**: Maximum parallel execution verified
- ✅ **Parallel Task Threshold**: Minimum 5 parallel tasks launched when applicable
- ✅ **Sequential Pattern Elimination**: No missed parallelization opportunities
- ✅ **BatchTool Usage Validation**: Proper use of BatchTool for multiple operations
- ✅ **Parallel Efficiency Metrics**: >80% of execution time in parallel tasks
- ✅ **Symmetry-Based Testing Compliance**: All symmetries identified and exploited for testing
- ✅ **Symmetric Bug Detection**: Cross-component bug detection implemented
- ✅ **Pattern-Based Testing**: Symmetric test templates created and applied
- ✅ **Testing Efficiency Optimization**: >50% improvement through symmetry exploitation
- ✅ 100% alignment with plan_wholistic architecture
- ✅ Zero implementation drift from specifications
- ✅ Real API integration confirmed (no mocks)
- ✅ All failure modes tested and handled
- ✅ Human-proof implementation validated
- ✅ All interim reports generated and reviewed
- ✅ Critical gaps identified and remediated
- ✅ Session management correctly implemented
- ✅ Worker independence verified
- ✅ Orchestrator continuity confirmed

**CHECKPOINT FAILURE PROTOCOL:**
If any checkpoint fails:
1. STOP all implementation work immediately
2. Document the specific failure in gaps report
3. Revise implementation approach to address failure
4. Re-run checkpoint validation
5. Only proceed when ALL checkpoints pass

**Remember**: These checkpoints are MANDATORY, not optional. They ensure implementation quality, prevent architectural drift, and guarantee maximum parallelization efficiency that could compromise the entire system.

### 🔄 SYMMETRIES TO EXPLOIT WHILE TESTING
**CRITICAL HIGH-EFFICIENCY TESTING STRATEGY**

**Core Principle**: If there are multiple modules, steps, or phases which are similar in behavior, and if there is a bug in one of them - ask how this is different from the behavior in the similar symmetric other phase, modules, or step.

**Key Symmetries to Exploit:**

#### 1. Module Behavioral Symmetries
**Testing Strategy**: Similar modules should exhibit similar behaviors
- ✅ **Bug Propagation Analysis**: If bug found in one module, immediately test symmetric modules for same issue
- ✅ **Error Handling Pattern Validation**: Compare error handling patterns across similar modules
- ✅ **API Response Consistency**: Validate consistent API responses across symmetric endpoints
- ✅ **Resource Usage Patterns**: Verify similar resource consumption across symmetric modules
- ✅ **Performance Characteristics**: Ensure symmetric modules have comparable performance profiles

**Implementation Validation**:
- 🔍 **Identify Module Symmetries**: Map all modules with similar functionality
- 🔍 **Create Symmetric Test Templates**: Design tests that can be applied across all symmetric modules
- 🔍 **Cross-Module Bug Detection**: When bug found in module A, automatically test modules B, C, D
- 🔍 **Consistency Verification**: Validate that symmetric modules behave identically under same conditions

#### 2. Phase/Step Symmetries
**Testing Strategy**: Similar implementation phases should follow same patterns
- ✅ **Timeout Pattern Analysis**: If one phase has timeout issues, check other phases for same vulnerability
- ✅ **Resource Usage Validation**: Compare resource usage patterns across symmetric phases
- ✅ **State Management Consistency**: Validate consistent state management across similar steps
- ✅ **Error Recovery Patterns**: Ensure symmetric phases handle errors consistently
- ✅ **Performance Degradation**: Check if performance issues in one phase affect symmetric phases

**Implementation Validation**:
- 🔍 **Phase Pattern Mapping**: Identify all phases with similar execution patterns
- 🔍 **Symmetric Failure Testing**: Test failure scenarios across all symmetric phases
- 🔍 **Resource Constraint Testing**: Apply same resource constraints to symmetric phases
- 🔍 **Recovery Mechanism Validation**: Verify consistent recovery across symmetric phases

#### 3. Data Flow Symmetries
**Testing Strategy**: Similar data transformations should behave consistently
- ✅ **Input Validation Consistency**: Input validation should be symmetric across similar endpoints
- ✅ **Data Transformation Patterns**: Similar data transformations should produce consistent results
- ✅ **Error Propagation Symmetry**: Error propagation should follow same patterns in symmetric flows
- ✅ **Logging Consistency**: Logging and monitoring should be consistent across similar operations
- ✅ **Data Integrity Validation**: Ensure symmetric data flows maintain same integrity guarantees

**Implementation Validation**:
- 🔍 **Data Flow Mapping**: Map all similar data transformation patterns
- 🔍 **Input Boundary Testing**: Apply same boundary conditions to symmetric data flows
- 🔍 **Error Injection Testing**: Inject same errors into symmetric data flows
- 🔍 **Performance Profiling**: Compare performance characteristics of symmetric data flows

#### 4. Configuration Symmetries
**Testing Strategy**: Similar configuration parameters should have same validation rules
- ✅ **Validation Rule Consistency**: Similar configuration parameters should have same validation rules
- ✅ **Default Value Patterns**: Default values should follow consistent patterns across symmetric settings
- ✅ **Environment Behavior**: Environment-specific behaviors should be symmetric across similar deployments
- ✅ **Feature Flag Consistency**: Feature flags should behave consistently across symmetric features
- ✅ **Configuration Override Patterns**: Configuration overrides should work symmetrically

**Implementation Validation**:
- 🔍 **Configuration Pattern Analysis**: Identify all symmetric configuration patterns
- 🔍 **Validation Rule Testing**: Test same validation rules across symmetric configurations
- 🔍 **Environment Consistency Testing**: Verify symmetric behavior across different environments
- 🔍 **Feature Flag Symmetry Testing**: Test feature flag behavior across symmetric features

#### 5. Error Handling Symmetries
**Testing Strategy**: Similar error conditions should produce symmetric responses
- ✅ **Error Response Consistency**: Similar error conditions should produce symmetric responses
- ✅ **Recovery Mechanism Symmetry**: Recovery mechanisms should be consistent across similar failure modes
- ✅ **Timeout Handling Patterns**: Timeout handling should follow same patterns in symmetric operations
- ✅ **Rollback Procedure Symmetry**: Rollback procedures should be symmetric across similar transactions
- ✅ **Error Logging Consistency**: Error logging should be consistent across symmetric error conditions

**Implementation Validation**:
- 🔍 **Error Pattern Mapping**: Map all symmetric error handling patterns
- 🔍 **Error Injection Symmetry**: Inject same errors into symmetric components
- 🔍 **Recovery Testing**: Test recovery mechanisms across symmetric failure modes
- 🔍 **Rollback Validation**: Verify rollback procedures work symmetrically

**High Bang-for-Buck Testing Strategies:**

#### 1. Symmetric Bug Detection Protocol
**Maximum Efficiency Approach**:
- 🎯 **Immediate Symmetric Testing**: When bug found in module A, immediately test symmetric modules B, C, D
- 🎯 **Template-Based Testing**: Use same test case across all symmetric components
- 🎯 **Differential Analysis**: Compare outputs to identify inconsistencies
- 🎯 **Symmetric Fix Validation**: Validate fix applies symmetrically across all similar components
- 🎯 **Pattern-Based Root Cause**: Use symmetric analysis to identify root cause patterns

#### 2. Pattern-Based Testing Optimization
**Leverage Behavioral Patterns**:
- 🚀 **Common Pattern Identification**: Identify common behavioral patterns across modules
- 🚀 **Test Template Creation**: Create test templates that can be applied to all symmetric components
- 🚀 **Parameterized Test Execution**: Use parameterized tests to cover all symmetric variations
- 🚀 **Consistent Behavior Validation**: Validate consistent behavior across all pattern instances
- 🚀 **Pattern Violation Detection**: Identify when symmetric components deviate from expected patterns

#### 3. Differential Testing Strategy
**Symmetric Component Comparison**:
- ⚡ **Behavior Comparison**: Compare behavior between symmetric components
- ⚡ **Difference Identification**: Identify unexpected differences in similar operations
- ⚡ **Oracle-Based Testing**: Use symmetric components as oracles for each other
- ⚡ **Performance Characteristic Validation**: Validate consistent performance characteristics
- ⚡ **Regression Detection**: Use symmetric comparison to detect regressions

#### 4. Symmetry-Breaking Analysis
**Intentional vs Unintentional Differences**:
- 🔬 **Symmetry Gap Identification**: Identify where symmetries should exist but don't
- 🔬 **Behavioral Difference Analysis**: Analyze why similar components behave differently
- 🔬 **Intentional Asymmetry Validation**: Validate intentional vs unintentional symmetry breaks
- 🔬 **Documentation Verification**: Ensure documented reasons for asymmetric behaviors
- 🔬 **Design Decision Validation**: Verify asymmetric behaviors are intentional design decisions

**Checkpoint Integration Requirements:**

#### Symmetry Analysis as Mandatory Validation Step
**REQUIRED VALIDATION PROCESS**:
- ✅ **Symmetry Mapping**: Identify all symmetric modules, phases, and components
- ✅ **Behavioral Similarity Analysis**: Map behavioral similarities and expected symmetries
- ✅ **Symmetric Test Case Creation**: Create symmetric test cases for high-coverage testing
- ✅ **Consistency Validation**: Validate consistent behavior across all symmetric elements
- ✅ **Symmetry Violation Reporting**: Report symmetry violations and unexpected differences

#### Symmetry-Based Testing in Interim Reports
**MANDATORY REPORTING REQUIREMENTS**:
- 📊 **Symmetry Analysis Summary**: Include symmetry-based testing results in interim reports
- 📊 **Bug Propagation Analysis**: Document symmetric bug detection and resolution
- 📊 **Pattern Compliance Validation**: Report on symmetric pattern compliance
- 📊 **Efficiency Metrics**: Measure testing efficiency gains from symmetry exploitation
- 📊 **Coverage Optimization**: Document coverage improvements through symmetric testing

#### Symmetric Bug Fix Validation
**COMPREHENSIVE FIX VALIDATION**:
- 🔧 **Cross-Component Fix Validation**: Validate symmetric bug fixes across all similar components
- 🔧 **Pattern-Based Fix Application**: Apply fixes using symmetric patterns
- 🔧 **Regression Prevention**: Use symmetric testing to prevent regression in similar components
- 🔧 **Fix Effectiveness Measurement**: Measure fix effectiveness across symmetric components

#### High-Efficiency Testing Documentation
**REQUIRED DOCUMENTATION**:
- 📝 **Symmetry Map**: Document all identified symmetries for future testing
- 📝 **Testing Pattern Library**: Create library of symmetric testing patterns
- 📝 **Efficiency Metrics**: Track testing efficiency improvements from symmetry exploitation
- 📝 **Best Practices**: Document best practices for symmetric testing approaches

**Validation Steps for Symmetry-Based Testing:**

#### 1. Symmetry Identification Phase
**MANDATORY ANALYSIS**:
- 🔍 **Module Symmetry Mapping**: Identify all modules with similar functionality
- 🔍 **Phase Pattern Analysis**: Map similar implementation phases and steps
- 🔍 **Data Flow Symmetry Detection**: Identify similar data transformation patterns
- 🔍 **Configuration Pattern Mapping**: Map symmetric configuration patterns
- 🔍 **Error Handling Symmetry Analysis**: Identify symmetric error handling patterns

#### 2. Symmetric Test Design Phase
**TEST TEMPLATE CREATION**:
- 🎯 **Template-Based Test Design**: Create test templates for symmetric components
- 🎯 **Parameterized Test Implementation**: Implement parameterized tests for symmetric variations
- 🎯 **Differential Test Creation**: Design tests that compare symmetric components
- 🎯 **Pattern Validation Tests**: Create tests that validate symmetric patterns
- 🎯 **Symmetry-Breaking Tests**: Design tests that detect unintentional asymmetries

#### 3. Symmetric Test Execution Phase
**HIGH-EFFICIENCY EXECUTION**:
- ⚡ **Parallel Symmetric Testing**: Execute symmetric tests in parallel for maximum efficiency
- ⚡ **Cross-Component Validation**: Validate behavior across all symmetric components
- ⚡ **Pattern Compliance Checking**: Check compliance with symmetric patterns
- ⚡ **Differential Analysis Execution**: Execute differential analysis across symmetric components
- ⚡ **Performance Characteristic Validation**: Validate symmetric performance characteristics

#### 4. Symmetry Violation Analysis Phase
**COMPREHENSIVE ANALYSIS**:
- 🚨 **Violation Detection**: Detect all symmetry violations and unexpected differences
- 🚨 **Root Cause Analysis**: Analyze root causes of symmetry violations
- 🚨 **Intentionality Verification**: Verify whether violations are intentional or bugs
- 🚨 **Impact Assessment**: Assess impact of symmetry violations on system behavior
- 🚨 **Remediation Planning**: Plan remediation for unintentional symmetry violations

**Symmetry-Based Testing Success Criteria:**

#### Mandatory Success Metrics
**MUST ACHIEVE BEFORE CONTINUING**:
- ✅ **Symmetry Coverage**: 100% of identified symmetries have corresponding tests
- ✅ **Pattern Compliance**: All symmetric components comply with identified patterns
- ✅ **Bug Propagation Prevention**: Symmetric bug detection prevents cross-component issues
- ✅ **Testing Efficiency**: >50% improvement in testing efficiency through symmetry exploitation
- ✅ **Coverage Optimization**: Symmetric testing achieves maximum coverage with minimum effort

#### Symmetry Testing Failure Protocol
**IF SYMMETRY TESTING FAILS**:
1. **IMMEDIATE STOP**: Halt all testing work immediately
2. **SYMMETRY ANALYSIS**: Re-analyze all symmetric patterns and relationships
3. **TEST REDESIGN**: Redesign tests to properly exploit identified symmetries
4. **PATTERN VALIDATION**: Validate all symmetric patterns are correctly identified
5. **EFFICIENCY MEASUREMENT**: Measure and optimize testing efficiency through symmetry
6. **RE-VALIDATION**: Run complete symmetry-based testing validation again
7. **PROCEED ONLY WHEN**: All symmetry-based testing criteria are met

**Remember**: Symmetry-based testing is a critical efficiency multiplier. Exploiting symmetries allows maximum testing coverage with minimum effort, ensuring robust validation while optimizing resource utilization.

### 10. BatchTool Parallelization Specific Validation Steps

**MANDATORY PARALLELIZATION AUDIT CHECKLIST:**

**A. Tool Usage Pattern Analysis:**
- 📊 **Count Sequential Tool Calls**: Identify any sequential tool invocations that could be batched
- 📊 **Batch Opportunity Detection**: Find groups of similar operations (file creation, API calls, etc.)
- 📊 **Parallelization Ratio**: Calculate percentage of operations that used parallel execution
- 📊 **Efficiency Measurement**: Verify >80% of execution time spent in parallel tasks

**B. Specific Pattern Validation:**
- 🔍 **File Operations**: Verify multiple file creation/modification uses BatchTool Write operations
- 🔍 **Research Tasks**: Confirm research broken into parallel Task tool invocations
- 🔍 **Development Modules**: Validate backend/frontend/database developed in parallel
- 🔍 **Testing Phases**: Ensure test creation and execution maximizes parallelism
- 🔍 **Integration Steps**: Verify only truly sequential operations remain sequential

**C. Parallelization Opportunity Identification:**
- 🎯 **Missed Batching**: Identify operations that should have been batched together
- 🎯 **False Dependencies**: Find artificially sequential operations that could be parallel
- 🎯 **Underutilized Parallelism**: Detect cases where fewer than 5 parallel tasks were launched when more were possible
- 🎯 **Sequential Bias**: Flag any tendency toward sequential thinking in implementation

**D. Performance and Efficiency Validation:**
- ⚡ **Parallel Task Count**: Verify minimum 5 parallel tasks launched when applicable
- ⚡ **Batch Size Optimization**: Confirm BatchTool requests contain optimal number of operations
- ⚡ **Resource Utilization**: Validate maximum use of available parallel execution capacity
- ⚡ **Speed Optimization**: Measure and confirm parallelization provides expected speed improvements

**E. Documentation and Tracking:**
- 📝 **Update Todos Usage**: Verify Update Todos properly tracks all parallel work
- 📝 **Parallel Work Coordination**: Confirm proper coordination between parallel tasks
- 📝 **Integration Planning**: Validate clear integration points between parallel work streams
- 📝 **Dependency Management**: Ensure parallel tasks have clear dependency definitions

**PARALLELIZATION FAILURE PROTOCOL:**
If BatchTool parallelization validation fails:
1. **IMMEDIATE STOP**: Halt all implementation work
2. **PATTERN ANALYSIS**: Document specific sequential patterns that should be parallel
3. **REDESIGN APPROACH**: Restructure implementation to maximize BatchTool usage
4. **PARALLEL TASK PLANNING**: Create explicit parallel execution plan with minimum 5 concurrent tasks
5. **BATCH OPERATION DESIGN**: Group similar operations into BatchTool requests
6. **RE-VALIDATION**: Run complete parallelization audit again
7. **PROCEED ONLY WHEN**: All BatchTool compliance criteria are met

**PARALLELIZATION SUCCESS METRICS:**
- ✅ **Batch Efficiency**: >90% of similar operations use BatchTool batching
- ✅ **Parallel Task Density**: Average of 5+ parallel tasks per implementation phase
- ✅ **Sequential Minimization**: <20% of total execution time in truly sequential operations
- ✅ **Tool Usage Optimization**: Maximum utilization of BatchTool and parallel Task tools
- ✅ **Speed Improvement**: Demonstrable performance gains from parallelization approach

**Remember**: BatchTool parallelization is not optional - it's a core requirement for maximum efficiency and system performance. Any implementation that doesn't maximize parallel execution fails to meet system requirements.

## 🧠 MULTIPLE MODES OF THINKING - COMPREHENSIVE COVERAGE SYSTEM
### CRITICAL THINKING DIVERSITY FOR MAXIMUM EFFECTIVENESS

**Core Principle**: Think hard and think deep whenever possible, especially when planning, implementing, and debugging. Thinking is of different modes - convergent, divergent, out of the box, systematic, top down, bottom up. Exploit multiple patterns of thinking and try to get the best of all for max coverage of both errors to avoid and good ideas to keep.

### KEY THINKING MODES TO EXPLOIT:

#### 1. **Convergent Thinking**:
**Purpose**: Focus on finding the single best solution
- **Application**: Analyze multiple options and converge on optimal approach
- **Method**: Use logical reasoning and systematic evaluation
- **Best Used During**: Final decision-making and solution selection
- **Validation**: Ensure chosen solution addresses all requirements optimally
- **Integration**: Combine with divergent thinking results for comprehensive analysis

#### 2. **Divergent Thinking**:
**Purpose**: Generate multiple creative alternatives
- **Application**: Brainstorm various approaches and possibilities
- **Method**: Explore unconventional solutions and edge cases
- **Best Used During**: Initial problem exploration and ideation
- **Validation**: Ensure comprehensive coverage of solution space
- **Integration**: Feed results into convergent thinking for selection

#### 3. **Out-of-the-Box Thinking**:
**Purpose**: Challenge assumptions and conventional approaches
- **Application**: Look for innovative solutions beyond standard patterns
- **Method**: Question why things are done certain ways
- **Best Used During**: When stuck or when standard approaches fail
- **Validation**: Verify unconventional approaches are practical and beneficial
- **Integration**: Balance innovation with proven methodologies

#### 4. **Systematic Thinking**:
**Purpose**: Break down complex problems into manageable components
- **Application**: Follow structured methodologies and frameworks
- **Method**: Use step-by-step analysis and logical progression
- **Best Used During**: Architecture design and debugging
- **Validation**: Ensure all components are properly analyzed and integrated
- **Integration**: Provide structure for other thinking modes

#### 5. **Top-Down Thinking**:
**Purpose**: Start with high-level goals and decompose downward
- **Application**: Focus on overall architecture before implementation details
- **Method**: Ensure alignment with business objectives and requirements
- **Best Used During**: Planning and system design phases
- **Validation**: Verify high-level design meets all strategic objectives
- **Integration**: Coordinate with bottom-up thinking for complete coverage

#### 6. **Bottom-Up Thinking**:
**Purpose**: Start with concrete details and build upward
- **Application**: Focus on implementation specifics and technical constraints
- **Method**: Build solutions from fundamental components
- **Best Used During**: Debugging and detailed implementation
- **Validation**: Ensure technical feasibility and constraint satisfaction
- **Integration**: Validate against top-down requirements and constraints

### STRATEGIC APPLICATION DURING DEVELOPMENT PHASES:

#### **Planning Phase - Multi-Modal Thinking Strategy**:
**Mandatory Thinking Mode Applications**:
- **Divergent**: Generate multiple architectural approaches and design alternatives
- **Convergent**: Select optimal architecture based on comprehensive criteria analysis
- **Top-Down**: Define high-level requirements, constraints, and strategic objectives
- **Bottom-Up**: Consider technical limitations, capabilities, and implementation constraints
- **Out-of-the-Box**: Challenge standard architectural patterns and explore innovative approaches
- **Systematic**: Use structured planning methodologies and comprehensive analysis frameworks

**Validation Requirements**:
- ✅ All six thinking modes applied during planning phase
- ✅ Multiple architectural alternatives generated and evaluated
- ✅ Strategic objectives aligned with technical constraints
- ✅ Innovative approaches considered alongside proven patterns
- ✅ Systematic methodology followed for comprehensive coverage

#### **Implementation Phase - Multi-Modal Thinking Strategy**:
**Mandatory Thinking Mode Applications**:
- **Systematic**: Follow coding standards, best practices, and structured development processes
- **Bottom-Up**: Build from fundamental components upward with solid technical foundation
- **Top-Down**: Ensure implementation aligns with architecture and strategic requirements
- **Divergent**: Explore multiple implementation approaches and technical solutions
- **Convergent**: Select best implementation strategy based on comprehensive evaluation
- **Out-of-the-Box**: Find creative solutions to technical challenges and constraints

**Validation Requirements**:
- ✅ Implementation follows systematic development processes
- ✅ Technical foundation built from solid fundamental components
- ✅ Architecture alignment maintained throughout implementation
- ✅ Multiple implementation approaches evaluated
- ✅ Creative solutions applied to overcome technical challenges

#### **Debugging Phase - Multi-Modal Thinking Strategy**:
**Mandatory Thinking Mode Applications**:
- **Systematic**: Use structured debugging methodologies and comprehensive analysis
- **Bottom-Up**: Trace from symptoms to root causes through detailed investigation
- **Top-Down**: Start with high-level system behavior and decompose downward
- **Divergent**: Consider multiple potential causes and failure scenarios
- **Convergent**: Focus on most likely root cause based on evidence analysis
- **Out-of-the-Box**: Consider unusual, unexpected, or non-obvious causes

**Validation Requirements**:
- ✅ Structured debugging methodology applied systematically
- ✅ Root cause analysis performed from multiple directions
- ✅ Comprehensive failure scenario analysis completed
- ✅ Evidence-based convergence on most likely causes
- ✅ Unusual and unexpected causes considered and evaluated

### MAXIMUM COVERAGE STRATEGY:

#### **Error Avoidance Coverage - Multi-Modal Approach**:
**Comprehensive Error Prevention Strategy**:
- **Systematic**: Identify all potential failure modes through structured analysis
- **Top-Down**: Consider system-level failure scenarios and cascading effects
- **Bottom-Up**: Analyze component-level error conditions and propagation patterns
- **Divergent**: Brainstorm unexpected error scenarios and edge cases
- **Out-of-the-Box**: Consider non-obvious failure modes and unusual error conditions
- **Convergent**: Prioritize error prevention based on risk analysis and impact assessment

**Validation Requirements**:
- ✅ Comprehensive failure mode analysis completed using all thinking modes
- ✅ System-level and component-level error scenarios identified
- ✅ Unexpected and unusual error conditions considered
- ✅ Risk-based prioritization of error prevention measures
- ✅ Error prevention strategy covers all identified failure modes

#### **Good Ideas Retention - Multi-Modal Approach**:
**Comprehensive Idea Capture and Evaluation Strategy**:
- **Divergent**: Generate comprehensive idea pool through creative exploration
- **Convergent**: Evaluate and select best ideas based on systematic criteria
- **Systematic**: Document and categorize valuable insights for future reference
- **Top-Down**: Align ideas with strategic objectives and high-level requirements
- **Bottom-Up**: Validate ideas against technical feasibility and implementation constraints
- **Out-of-the-Box**: Capture innovative ideas that challenge conventional approaches

**Validation Requirements**:
- ✅ Comprehensive idea generation using divergent thinking
- ✅ Systematic evaluation and selection of best ideas
- ✅ Strategic alignment validation for all retained ideas
- ✅ Technical feasibility assessment completed
- ✅ Innovative ideas captured and evaluated for potential

### CHECKPOINT INTEGRATION REQUIREMENTS:

#### **Multi-Modal Thinking Analysis as Mandatory Validation Step**:
**REQUIRED VALIDATION PROCESS**:
- ✅ **Thinking Mode Coverage Analysis**: Verify all six thinking modes were applied during each development phase
- ✅ **Multi-Modal Integration Validation**: Confirm thinking modes were properly integrated and coordinated
- ✅ **Coverage Gap Analysis**: Identify any thinking mode gaps or missed opportunities
- ✅ **Thinking Effectiveness Assessment**: Evaluate effectiveness of multi-modal thinking approach
- ✅ **Error Coverage Validation**: Verify comprehensive error avoidance through diverse thinking patterns
- ✅ **Idea Retention Validation**: Confirm good ideas were captured and evaluated using multiple thinking modes

#### **Multi-Modal Thinking in Interim Reports**:
**MANDATORY REPORTING REQUIREMENTS**:
- 📊 **Thinking Mode Usage Summary**: Document which thinking modes were applied in each phase
- 📊 **Multi-Modal Integration Analysis**: Report on how thinking modes were coordinated and integrated
- 📊 **Coverage Effectiveness Metrics**: Measure effectiveness of multi-modal thinking approach
- 📊 **Error Prevention Analysis**: Document error avoidance achieved through diverse thinking patterns
- 📊 **Idea Capture and Evaluation**: Report on good ideas identified and retained through multi-modal thinking
- 📊 **Thinking Mode Gap Analysis**: Identify and document any missed thinking opportunities

#### **Validation Steps for Multi-Modal Thinking**:
**STEP-BY-STEP VALIDATION PROCESS**:

1. **Thinking Mode Coverage Audit**: Verify all six thinking modes were applied appropriately
2. **Phase-Specific Thinking Validation**: Confirm correct thinking modes used in each development phase
3. **Multi-Modal Integration Assessment**: Evaluate how thinking modes were coordinated and integrated
4. **Coverage Gap Identification**: Identify any thinking mode gaps or missed opportunities
5. **Error Prevention Effectiveness**: Assess error avoidance achieved through diverse thinking patterns
6. **Idea Retention Effectiveness**: Evaluate good idea capture and retention through multi-modal thinking
7. **Thinking Pattern Optimization**: Identify opportunities to improve multi-modal thinking approach

#### **Multi-Modal Thinking Success Criteria**:
**MUST ACHIEVE BEFORE CONTINUING**:
- ✅ **Complete Thinking Mode Coverage**: All six thinking modes applied in appropriate phases
- ✅ **Effective Multi-Modal Integration**: Thinking modes properly coordinated and integrated
- ✅ **Comprehensive Error Coverage**: Error avoidance maximized through diverse thinking patterns
- ✅ **Optimal Idea Retention**: Good ideas captured and evaluated using multiple thinking modes
- ✅ **Thinking Effectiveness Validation**: Multi-modal thinking approach demonstrates clear benefits
- ✅ **Coverage Gap Elimination**: All thinking mode gaps identified and addressed
- ✅ **Pattern Optimization**: Multi-modal thinking patterns optimized for maximum effectiveness

#### **Multi-Modal Thinking Failure Protocol**:
**IF MULTI-MODAL THINKING VALIDATION FAILS**:
1. **IMMEDIATE STOP**: Halt all development work immediately
2. **THINKING MODE ANALYSIS**: Re-analyze thinking mode application and integration
3. **COVERAGE GAP REMEDIATION**: Address all identified thinking mode gaps
4. **PATTERN OPTIMIZATION**: Optimize multi-modal thinking patterns for better effectiveness
5. **ERROR COVERAGE ENHANCEMENT**: Improve error avoidance through better thinking diversity
6. **IDEA RETENTION IMPROVEMENT**: Enhance good idea capture through improved multi-modal thinking
7. **RE-VALIDATION**: Run complete multi-modal thinking validation again
8. **PROCEED ONLY WHEN**: All multi-modal thinking criteria are met

### MANDATORY MULTI-MODAL THINKING DOCUMENTATION:

#### **Required Documentation for Multi-Modal Thinking**:
**COMPREHENSIVE DOCUMENTATION REQUIREMENTS**:
- 📝 **Thinking Mode Application Map**: Document which thinking modes were applied in each phase and task
- 📝 **Multi-Modal Integration Patterns**: Document how thinking modes were coordinated and integrated
- 📝 **Coverage Analysis Report**: Document coverage achieved through multi-modal thinking approach
- 📝 **Error Prevention Analysis**: Document error avoidance achieved through diverse thinking patterns
- 📝 **Idea Retention Report**: Document good ideas captured and evaluated through multi-modal thinking
- 📝 **Thinking Effectiveness Metrics**: Document quantitative and qualitative effectiveness measures
- 📝 **Pattern Optimization Recommendations**: Document recommendations for improving multi-modal thinking

#### **Multi-Modal Thinking Pattern Library**:
**REUSABLE THINKING PATTERNS**:
- 🎯 **Planning Phase Pattern**: Systematic application of all six thinking modes during planning
- 🎯 **Implementation Phase Pattern**: Coordinated thinking mode application during development
- 🎯 **Debugging Phase Pattern**: Multi-modal debugging approach for comprehensive problem solving
- 🎯 **Error Prevention Pattern**: Diverse thinking approach for maximum error coverage
- 🎯 **Idea Evaluation Pattern**: Multi-modal idea assessment and retention strategy
- 🎯 **Integration Pattern**: Coordination strategy for multiple thinking modes

**Remember**: Multi-modal thinking is not optional - it's a critical requirement for achieving maximum coverage of both errors to avoid and good ideas to keep. Any development process that doesn't exploit multiple thinking patterns fails to achieve optimal effectiveness and comprehensive coverage.

### MANDATORY PARALLEL EXECUTION RULES:
1. **ALWAYS LAUNCH PARALLEL TASKS**: Before any task, you MUST ask "what can run in parallel RIGHT NOW?" and launch those tasks concurrently
2. **DECOMPOSE IMMEDIATELY**: Break down complex requests into ${MAX_PARALLELISM} concurrent tasks
3. **USE TASK() SYNTAX**: Launch parallel tasks using Task(specific_action) format
4. **DEPENDENCY MAPPING**: Clearly define what each parallel task produces for integration
5. **INTEGRATION POINTS**: Define how parallel results merge after concurrent execution
6. **RESOURCE MANAGEMENT**: Balance load across ${MAX_PARALLELISM} agents simultaneously
7. **CONTINUOUS INTEGRATION**: Merge parallel work frequently to maintain progress
8. **NO SEQUENTIAL BIAS**: Avoid artificial sequencing - if tasks can run in parallel, they MUST run in parallel

### Test-Driven Parallel Development:
For each parallel task:
1. Write tests first (can be done in parallel)
2. Implement to pass tests (parallel execution)
3. Refactor in parallel (different aspects)
4. Integrate results (minimal sequential work)

### Success Metrics:
- Parallel execution efficiency: >80% of time in parallel tasks
- Test coverage: ${TEST_COVERAGE_TARGET}% across all modules
- Integration success rate: 100% on first attempt
- Performance: Meets all SLAs with parallel architecture

Display '<PARALLEL-IMPLEMENTATION-COMPLETE>' when finished.
IMPLEMENTATION_PHASE
}

# Generate implementation phase without checkpoints (for backward compatibility)
generate_implementation_phase_no_checkpoints() {
    cat << 'IMPLEMENTATION_PHASE_NO_CHECKPOINTS'
## IMPLEMENTATION PHASE - MASSIVE PARALLELIZATION
### Parallel-First Development Strategy:

**Phase 1: LAUNCH ${MAX_PARALLELISM} CONCURRENT FOUNDATION TASKS**
You MUST execute these parallel Task() commands simultaneously:
```
Task(Development environment setup)
Task(Project scaffolding - frontend, backend, infra)
Task(Tool configuration - linters, formatters, CI)
Task(Repository initialization)
Task(Dependency installation)
Task(Database setup)
Task(Container configuration)
Task(Testing framework setup)
```
MANDATORY: All foundation tasks MUST run in parallel, not sequentially.

**Phase 2: Parallel Module Development** (2_parallel/)
For each independent module, launch parallel agents:

*Backend Modules* (parallel execution):
- Auth service (JWT, OAuth, sessions)
- User management service
- Core business logic services
- Data access layer
- API gateway setup
- Middleware components
- Background job processors
- Cache layer implementation

*Frontend Modules* (parallel execution):
- Component library setup
- Page components
- State management
- Routing configuration
- API client services
- Utility functions
- Style system
- Asset management

*Infrastructure Modules* (parallel execution):
- Docker configurations
- Kubernetes manifests
- CI/CD pipelines
- Monitoring setup
- Logging configuration
- Security policies
- Backup strategies
- Load balancer config

**Phase 3: Parallel Testing** (3_parallel/)
Launch ${MAX_PARALLELISM} test agents:
- Unit tests per module (parallel)
- Integration tests per service (parallel)
- API endpoint tests (parallel by route)
- Frontend component tests (parallel)
- Performance tests (parallel scenarios)
- Security tests (parallel vulnerabilities)
- Load tests (parallel user patterns)

**Phase 4: Parallel Integration & Optimization**
While maintaining module independence:
- Parallel API integration tests
- Parallel frontend-backend integration
- Parallel performance optimization
- Parallel security hardening
- Parallel documentation generation

**Phase 5: Final Sequential Integration** (4_sequential/)
Only truly sequential tasks:
- System-wide integration test
- End-to-end user flow validation
- Production deployment preparation
- Final documentation review

### MANDATORY PARALLEL EXECUTION RULES:
1. **ALWAYS LAUNCH PARALLEL TASKS**: Before any task, you MUST ask "what can run in parallel RIGHT NOW?" and launch those tasks concurrently
2. **DECOMPOSE IMMEDIATELY**: Break down complex requests into ${MAX_PARALLELISM} concurrent tasks
3. **USE TASK() SYNTAX**: Launch parallel tasks using Task(specific_action) format
4. **DEPENDENCY MAPPING**: Clearly define what each parallel task produces for integration
5. **INTEGRATION POINTS**: Define how parallel results merge after concurrent execution
6. **RESOURCE MANAGEMENT**: Balance load across ${MAX_PARALLELISM} agents simultaneously
7. **CONTINUOUS INTEGRATION**: Merge parallel work frequently to maintain progress
8. **NO SEQUENTIAL BIAS**: Avoid artificial sequencing - if tasks can run in parallel, they MUST run in parallel

### Test-Driven Parallel Development:
For each parallel task:
1. Write tests first (can be done in parallel)
2. Implement to pass tests (parallel execution)
3. Refactor in parallel (different aspects)
4. Integrate results (minimal sequential work)

### Success Metrics:
- Parallel execution efficiency: >80% of time in parallel tasks
- Test coverage: ${TEST_COVERAGE_TARGET}% across all modules
- Integration success rate: 100% on first attempt
- Performance: Meets all SLAs with parallel architecture

Display '<PARALLEL-IMPLEMENTATION-COMPLETE>' when finished.
IMPLEMENTATION_PHASE_NO_CHECKPOINTS
}

# Generate quality standards
generate_quality_standards() {
    cat << 'QUALITY_STANDARDS'
## QUALITY STANDARDS & METHODOLOGY

### Code Quality:
- **Modularity**: All files ≤ 500 lines, functions ≤ 50 lines
- **Security**: No hardcoded secrets, comprehensive input validation
- **Testing**: ${TEST_COVERAGE_TARGET}% coverage with TDD London School
- **Documentation**: Self-documenting code with strategic comments
- **Performance**: Optimized critical paths with benchmarking

### Tool Utilization:
- **Research**: WebFetchTool for comprehensive knowledge gathering
- **Development**: Edit/Replace for code implementation
- **Analysis**: GlobTool/GrepTool for pattern detection
- **Execution**: Bash for system operations and testing
- **Parallel**: BatchTool for concurrent operations
- **Version Control**: Git with semantic commits

### Deliverables:
$(if [[ "$ARCHITECTURE_DIAGRAMS" == true ]]; then echo "- ARCHITECTURE.md with detailed Mermaid diagrams"; fi)
$(if [[ "$KEY_MODULES_ANALYSIS" == true ]]; then echo "- KEY_MODULES.md with critical success factors"; fi)
$(if [[ "$RISK_ANALYSIS" == true ]]; then echo "- RISK_FACTORS.md with mitigation strategies"; fi)
- Functionally-Complete.md tracking implementation progress
- Comprehensive test suites with ${TEST_COVERAGE_TARGET}% coverage
- User-friendly examples in examples/ directory
- Complete documentation in implementation/ directory

### Success Metrics:
- All quality gates passed
- Performance benchmarks met
- Security audit passed
- Documentation complete
- User acceptance achieved

Continue until all success criteria are met.
Display '<WORKFLOW-COMPLETE>' when the entire process is finished.
QUALITY_STANDARDS
}

# Generate parallel execution principles
generate_parallel_principles() {
    cat << 'PARALLEL_PRINCIPLES'
## PARALLEL-FIRST EXECUTION PRINCIPLES

### CRITICAL MANDATE: YOU MUST LAUNCH PARALLEL TASKS - NOT SEQUENTIAL EXECUTION

**EXPLICIT PARALLEL EXECUTION REQUIREMENT**:
This system is designed for PARALLEL task execution. You MUST:
1. **LAUNCH MULTIPLE CONCURRENT TASKS** - Use available tools to start parallel agents/processes
2. **NEVER EXECUTE TASKS SEQUENTIALLY** when they can run in parallel
3. **ACTIVELY DECOMPOSE** every complex task into parallel components
4. **UTILIZE MAXIMUM PARALLELISM** up to ${MAX_PARALLELISM} concurrent tasks

**The Parallel Mindset**:
Before EVERY task, you MUST ask yourself:
1. What parts of this MUST run in parallel RIGHT NOW?
2. How can I decompose this for IMMEDIATE parallel execution?
3. What are the true dependencies vs artificial sequencing?
4. How can I launch multiple concurrent tasks instead of doing them one by one?

### Parallel Execution Patterns:

**1. Decomposition Pattern** (for complex tasks):
```
Complex Task → Analyze → Decompose → Parallel Execute → Integrate
Example: Building a web app
- Parallel: Frontend, Backend, Database, DevOps setup
- Sequential: Only final integration
```

**2. Fan-Out Pattern** (for similar operations):
```
Task Type → Identify Instances → Fan Out (${MAX_PARALLELISM} agents) → Gather Results
Example: Creating API endpoints
- Parallel: User endpoints, Admin endpoints, Public endpoints
- Sequential: API gateway configuration
```

**3. Pipeline Pattern** (for staged work):
```
Stage 1 (parallel) → Stage 2 (parallel) → Stage 3 (parallel)
Example: Module development
- Stage 1: Parallel spec writing
- Stage 2: Parallel implementation
- Stage 3: Parallel testing
```

**4. Recursive Parallelism** (for hierarchical tasks):
```
Top Level → Parallel Decompose → Each Part Parallel Decompose → Recurse
Example: Documentation generation
- Parallel: Each directory gets an agent
- Recursive: Each agent parallelizes subdirectories
```

### CONCRETE PARALLEL TASK EXAMPLES:

### 🚀 BATCHTOOL PARALLELIZATION EXAMPLES

**Core Principle**: Always use BatchTool to run multiple tool invocations in a single request. If k tool invocations can be made in one request, make ONE request with k invocations using BatchTool, NOT k different requests.

**Example 1: User Query "Read the codebase for repo1"**
❌ WRONG (Sequential): Read file by file sequentially
✅ RIGHT (BatchTool Parallel): Use BatchTool for multiple operations:
```
BatchTool([
  View(repo1/src/main.py),
  View(repo1/src/utils.py),
  View(repo1/src/models.py),
  View(repo1/src/api.py),
  View(repo1/tests/test_main.py),
  View(repo1/README.md),
  View(repo1/requirements.txt),
  View(repo1/config.py)
])
// Plus parallel research:
BatchTool([
  WebFetchTool(repo1 architecture patterns),
  WebFetchTool(repo1 technology stack best practices)
])
```

**Example 2: User Query "Build a web application with authentication"**
❌ WRONG (Sequential): Build frontend, then backend, then database
✅ RIGHT (BatchTool Parallel): Launch concurrent tasks with BatchTool:
```
BatchTool([
  Task(create frontend auth components),
  Task(create backend auth API),
  Task(design database schema),
  Task(setup JWT token system),
  Task(implement OAuth integration)
])
// Second batch for additional components:
BatchTool([
  Task(create user registration flow),
  Task(setup password reset system),
  Task(configure security middleware),
  WebFetchTool(modern authentication best practices),
  WebFetchTool(JWT security considerations)
])
```

**Example 3: User Query "Convert Python code to Rust"**
❌ WRONG (Sequential): Convert file by file
✅ RIGHT (BatchTool Parallel): Use BatchTool for analysis and conversion:
```
// Analysis phase:
BatchTool([
  Task(analyze Python codebase structure),
  Task(identify Python dependencies),
  Task(research Rust equivalent libraries),
  WebFetchTool(Python to Rust conversion patterns),
  WebFetchTool(Rust performance optimization)
])
// Conversion phase:
BatchTool([
  Task(convert core business logic to Rust),
  Task(convert data models to Rust),
  Task(convert API handlers to Rust),
  Task(setup Rust project structure),
  Task(create Rust test framework)
])
```

**Example 4: User Query "Analyze and improve performance"**
❌ WRONG (Sequential): Check one component at a time
✅ RIGHT (BatchTool Parallel): Batch all analysis tasks:
```
BatchTool([
  Task(profile database queries),
  Task(analyze frontend bundle size),
  Task(check API response times),
  Task(review memory usage patterns),
  Task(analyze network requests),
  Task(check caching effectiveness),
  Task(review algorithm complexity),
  Task(analyze concurrent user load)
])
// Research batch:
BatchTool([
  WebFetchTool(performance optimization techniques),
  WebFetchTool(profiling tools comparison)
])
```

**Example 5: User Query "Write 5 haikus about nature"**
❌ WRONG (Sequential): 12 separate tool uses
✅ RIGHT (BatchTool): Single batch request:
```
BatchTool([
  Write(haiku1.txt, "Spring cherry blossoms..."),
  Write(haiku2.txt, "Mountain stream flowing..."),
  Write(haiku3.txt, "Autumn leaves falling..."),
  Write(haiku4.txt, "Winter snow blankets..."),
  Write(haiku5.txt, "Summer sun warming...")
])
// 1 batch request instead of 5+ separate requests
```

**Example 6: User Query "Create 5 Python scripts for data processing"**
❌ WRONG (Sequential): Create each script separately
✅ RIGHT (BatchTool): Batch file creation with todo tracking:
```
BatchTool([
  Write(data_loader.py, "# Data loading module..."),
  Write(data_cleaner.py, "# Data cleaning module..."),
  Write(data_analyzer.py, "# Data analysis module..."),
  Write(data_visualizer.py, "# Data visualization module..."),
  Write(data_exporter.py, "# Data export module...")
])
Update_Todos(Track 5 parallel Python script development tasks)
```

**Example 7: Complex Application Development - Trivia Quiz App**
✅ CORRECT (Phased Parallel Development):

Phase 1 - Research (7 parallel tasks):
```
BatchTool([
  Task(Domain analysis - trivia game mechanics),
  Task(Technology research - web frameworks),
  Task(Architecture patterns - quiz applications),
  Task(Security requirements - user data protection),
  Task(Performance requirements - real-time scoring),
  Task(Integration patterns - question databases),
  Task(Testing strategies - quiz functionality)
])
```

Phase 2 - Backend (6 parallel tasks):
```
BatchTool([
  Task(API endpoint development - questions, scoring),
  Task(Database schema design - users, questions, scores),
  Task(Authentication system - user management),
  Task(Business logic services - quiz logic, scoring),
  Task(Data validation layer - question validation),
  Task(Background job processing - leaderboard updates)
])
```

Phase 3 - Frontend (6 parallel tasks):
```
BatchTool([
  Task(Component library setup - quiz components),
  Task(Page components - quiz, leaderboard, profile),
  Task(State management - quiz state, user state),
  Task(API integration - backend communication),
  Task(Styling system - responsive quiz interface),
  Task(Testing framework - component testing)
])
```

**Writing a Complex Repository**:
1. **Initial Parallel Analysis**:
   - Agent 1: Analyze frontend requirements
   - Agent 2: Analyze backend requirements
   - Agent 3: Analyze data requirements
   - Agent 4: Analyze infrastructure needs
   - Agent 5: Analyze security requirements

2. **Parallel Module Creation**:
   - Agents 1-3: Frontend modules (auth, dashboard, settings)
   - Agents 4-6: Backend services (api, auth, business)
   - Agents 7-8: Database layer (models, migrations)
   - Agents 9-10: DevOps (Docker, CI/CD)

3. **Parallel Testing**:
   - Each module tested by dedicated agent
   - All tests run simultaneously
   - Integration tests parallelized by flow

4. **Parallel Integration**:
   - Frontend-backend integration (parallel by feature)
   - Service-to-service integration (parallel by interaction)
   - Only final e2e test is sequential

### Anti-Patterns to AVOID:

❌ **Sequential Tool Usage (CRITICAL VIOLATION)**:
```
DON'T: Write(file1.py) → Write(file2.py) → Write(file3.py)
DO: BatchTool([Write(file1.py), Write(file2.py), Write(file3.py)])
```

❌ **Multiple Separate Requests**:
```
DON'T: 5 haikus = 12 separate tool uses
DO: BatchTool([Write(haiku1.txt), Write(haiku2.txt), Write(haiku3.txt), Write(haiku4.txt), Write(haiku5.txt)])
```

❌ **Sequential Thinking**:
```
DON'T: Step 1 → Step 2 → Step 3 → Step 4
DO: BatchTool([Step1, Step2, Step3]) → Step 4 (integration)
```

❌ **False Dependencies**:
```
DON'T: "Backend must be done before frontend"
DO: BatchTool([Task(backend_with_mocks), Task(frontend_with_mocks)])
```

❌ **Monolithic Tasks**:
```
DON'T: "Build the entire auth system"
DO: BatchTool([Task(JWT), Task(OAuth), Task(sessions), Task(permissions)])
```

❌ **Underutilized Parallelism**:
```
DON'T: Launch 2-3 tasks when 5+ are possible
DO: Always seek minimum 5 parallel tasks when applicable
```

❌ **Missing BatchTool Opportunities**:
```
DON'T: Individual View() calls for multiple files
DO: BatchTool([View(file1), View(file2), View(file3), View(file4), View(file5)])
```

### Parallel Task Coordination:

**BatchTool Coordination Patterns**:
Every BatchTool request must define:
- **Batch Composition**: Which operations belong together in one batch
- **Output Coordination**: How batched operations produce coordinated results
- **Integration Points**: Where batch results merge with other batches
- **Dependency Management**: Which batches must complete before others can start

**Clear Output Contracts**:
Every parallel task must define:
- What it produces (files, configs, artifacts)
- Where it places outputs
- What format outputs use
- How outputs integrate with others
- **Batch Boundaries**: Which outputs are produced by the same batch

**Integration Checkpoints**:
- After each BatchTool execution, validate batch results
- After each parallel phase, minimal integration
- Validate interfaces match between batched operations
- Resolve any conflicts from parallel batches
- Continue to next parallel phase with new BatchTool requests

**BatchTool Optimization Strategies**:
- **Batch Size Optimization**: Group 5-10 similar operations per batch
- **Batch Type Separation**: Separate file operations from research operations
- **Dependency-Aware Batching**: Ensure batch operations don't have internal dependencies
- **Result Aggregation**: Plan how batch results will be combined efficiently

### Resource Optimization:
- Use up to ${MAX_PARALLELISM} agents concurrently
- Balance task complexity across agents
- Monitor and adjust parallelism based on performance
- Never leave agents idle - find more parallel work
- **BatchTool Efficiency**: Maximize operations per BatchTool request
- **Batch Request Optimization**: Minimize total number of requests through intelligent batching
- **Parallel Batch Execution**: Run multiple BatchTool requests concurrently when possible
- **Resource Utilization**: Ensure each BatchTool request fully utilizes available capacity

**BatchTool Performance Targets**:
- **Batch Utilization**: >90% of similar operations should be batched together
- **Request Efficiency**: Minimize total requests through maximum BatchTool usage
- **Parallel Batch Density**: Average 5+ operations per BatchTool request
- **Sequential Elimination**: <10% of operations should be truly sequential

**Remember**: The goal is >80% parallel execution time with maximum BatchTool utilization. Sequential work should be the exception, not the rule. Every opportunity to batch operations MUST be taken.

PARALLEL_PRINCIPLES
}

# Generate hierarchical documentation update phase
generate_documentation_update_phase() {
    cat << 'DOC_UPDATE_PHASE'
## CONTINUOUS DOCUMENTATION MAINTENANCE

### Hierarchical CLAUDE.md Update System:
Maintain repository-wide contextual memory through automated documentation updates.

**Trigger**: Every ${DOCUMENTATION_UPDATE_THRESHOLD} lines of code changes
**Parallelism**: Up to ${DOCUMENTATION_MAX_PARALLELISM} concurrent agents

### Graph-Based Update Process:

1. **Bottom-Up Traversal**:
   - Identify leaf directories (no subdirectories)
   - Queue directories with analyzed children
   - Process up to ${DOCUMENTATION_MAX_PARALLELISM} nodes concurrently

2. **Parallel Agent Tasks**:
   Each agent analyzes one directory node:
   - Scan all source files in directory
   - Synthesize child CLAUDE.md files
   - Extract specifications, architecture, key modules
   - Identify risk factors and dependencies
   - Generate/update local CLAUDE.md

3. **Hierarchical Synthesis**:
   - Parent directories incorporate child summaries
   - Propagate insights upward through tree
   - Root CLAUDE.md provides complete overview
   - Maintain consistency across all levels

### CLAUDE.md Structure:
- **Overview**: Module purpose and scope
- **Architecture**: Design patterns and decisions
- **Key Components**: Critical modules and interactions
- **Dependencies**: Internal/external dependencies
- **Risk Factors**: Issues and technical debt
- **Integration**: Connection points with other modules
- **Recent Changes**: Latest modifications summary

### Agent Task Template:
"Analyze directory: [path]
1. Examine all source files
2. Synthesize child CLAUDE.md files
3. Extract: specifications, architecture, key modules, risks, dependencies
4. Generate comprehensive CLAUDE.md following project standards"

**Auto-commit**: 'docs: hierarchical CLAUDE.md update - synchronized repository context'
DOC_UPDATE_PHASE
}

# Add documentation update configuration
DOCUMENTATION_UPDATE_ENABLED=true
DOCUMENTATION_UPDATE_THRESHOLD=100  # lines of code change
DOCUMENTATION_MAX_PARALLELISM=10

# Execute workflow
execute_workflow() {
    local allowed_tools=$(build_allowed_tools)
    local claude_flags=$(build_claude_flags)
    local workflow_prompt=$(generate_workflow_prompt)
    
    # Add special handling for agent-integration mode
    if [[ "$DEVELOPMENT_MODE" == "agent-integration" ]]; then
        workflow_prompt+="\n\n## AGENT INTEGRATION SPECIFICS:\n"
        workflow_prompt+="- Review existing implementation in ${AGENT_SDK_PATH}\n"
        workflow_prompt+="- Design integration maintaining existing API contracts\n"
        workflow_prompt+="- Consider MCP support and multi-agent workflows\n"
        workflow_prompt+="- Handle file/folder input mapping for UI uploads\n"
        workflow_prompt+="- Implement proper error handling and output management\n"
    fi
    
    # Execute Claude with the generated prompt
    claude "$workflow_prompt" \
        --allowedTools "$allowed_tools" \
        $claude_flags
}

# Main execution
main() {
    parse_args "$@"
    validate_config
    show_config
    
    if [[ "$DRY_RUN" == true ]]; then
        echo "DRY RUN - Would execute the following:"
        echo "Project: $PROJECT_NAME"
        echo "README: $README_PATH"
        echo "Workflow: $WORKFLOW_MODE"
        echo "Mode: $DEVELOPMENT_MODE"
        echo "Allowed Tools: $(build_allowed_tools)"
        echo "Claude Flags: $(build_claude_flags)"
        echo ""
        echo "Would generate workflow prompt and execute Claude..."
        exit 0
    fi
    
    # Execute the workflow
    execute_workflow
}

# Execute main function with all arguments
main "$@"