# Execution Patterns # Unified workflow system, MCP orchestration, git operations, and execution lifecycle ## Legend @include universal-constants.yml#Universal_Legend ## Universal Execution Lifecycle ```yaml Standard_Lifecycle: Pre_Execution: Risk_Assessment: Calculate: "Assess operation risk level" Factors: ["Data loss potential", "Irreversibility", "Scope", "Security"] Actions: Low: "Proceed w/ monitoring" Medium: "Warn & log" High: "Require confirmation" Critical: "Block & alert" Environment_Validation: Check: ["Required tools", "Permissions", "Resources", "Dependencies"] Verify: ["Git state", "Network access", "Disk space", "Memory"] MCP_Health: "Test server connectivity & response" State_Preparation: TodoList_Triggers: "@include task-management-patterns.yml#Auto_Trigger_Rules" Checkpoint: "@include recovery-state-patterns.yml#Automatic_Triggers" Cache: "Previous results for efficiency" Lock: "Prevent concurrent modifications" MCP_Cache_Init: "@include mcp-cache-patterns.yml#Cache_Storage" During_Execution: Progress_Monitoring: Track: ["Operation progress", "Resource usage", "Error rates", "Token consumption"] Alert: ["Performance degradation", "Approaching limits", "Anomalies", "MCP failures"] Dynamic_Optimization: Adapt: ["Adjust parallelism", "Switch strategies", "Cache results", "Fallback to native"] Fallback: ["Use alternatives if primary fails", "Degrade gracefully"] Error_Handling: "@include recovery-state-patterns.yml#Recovery_Framework" Post_Execution: Verification: Confirm: ["Expected outcomes achieved", "No side effects", "State consistent"] Validate: ["Output quality", "Performance metrics", "Security compliance"] Cleanup: Remove: ["Temp files", "Locks", "Cached data"] Update: ["Audit logs", "Metrics", "Documentation"] Reporting: Generate: ["Success/failure report", "Performance metrics", "Recommendations"] Store: ".claudedocs/lifecycle/execution-{timestamp}.md" ``` ## MCP Server Registry & Orchestration ```yaml Servers: Context7: Purpose: "Library documentation and code examples" Best_For: ["API usage", "framework patterns", "library integration"] Token_Cost: "Low-Medium usage" Capabilities: - resolve-library-id: "Find Context7-compatible library ID" - get-library-docs: "Fetch up-to-date documentation" Success_Rate: "Very high for popular libraries" Fallback: "WebSearch official docs" Sequential: Purpose: "Step-by-step complex problem solving" Best_For: ["Architecture", "debugging", "system design", "root cause analysis"] Token_Cost: "Medium-High usage" Capabilities: - sequentialthinking: "Adaptive multi-step reasoning" Success_Rate: "High for complex problems" Fallback: "Native step-by-step analysis" Magic: Purpose: "UI component generation with 21st.dev" Best_For: ["React/Vue components", "UI patterns", "prototypes"] Token_Cost: "Medium usage" Capabilities: - 21st_magic_component_builder: "Generate UI components" - 21st_magic_component_refiner: "Improve existing components" - 21st_magic_component_inspiration: "Search component library" - logo_search: "Find company logos in TSX/JSX/SVG" Success_Rate: "High for common components" Fallback: "Search existing components in project" Puppeteer: Purpose: "Browser automation and testing" Best_For: ["E2E tests", "screenshots", "web scraping", "performance testing"] Token_Cost: "Low (minimal tokens, mostly actions)" Capabilities: - connect_active_tab: "Connect to Chrome debugging" - navigate: "Navigate to URLs" - screenshot: "Capture page/element screenshots" - click: "Click elements" - fill: "Fill form inputs" - evaluate: "Execute JavaScript" Success_Rate: "Very high for standard web interactions" Fallback: "Manual testing guidance" MCP_Parallel_Execution: "@include mcp-cache-patterns.yml#Parallel_MCP_Execution" MCP_Cache_Integration: Context7_Caching: "@include mcp-cache-patterns.yml#Context7_Cache" Sequential_Caching: "@include mcp-cache-patterns.yml#Sequential_Cache" Magic_Caching: "@include mcp-cache-patterns.yml#Magic_Cache" Performance: "@include mcp-cache-patterns.yml#Cache_Performance_Optimization" MCP_Control_Flags: Individual: --c7: "Enable Context7 only" --no-c7: "Disable Context7" --seq: "Enable Sequential only" --no-seq: "Disable Sequential" --magic: "Enable Magic only" --no-magic: "Disable Magic" --pup: "Enable Puppeteer only" --no-pup: "Disable Puppeteer" Combined: --all-mcp: "Enable all MCP servers" --no-mcp: "Disable all MCP servers (native tools only)" Priority: "Explicit flags > Command defaults > Context triggers" Override: "--no-mcp overrides all individual flags" ``` ## Chain Execution Patterns ```yaml Execution_Types: Sequential: "A→B→C | Linear progression w/ context handoff" Parallel: "A&B&C | Concurrent execution w/ result aggregation" Conditional: "A&&B||C | Success/failure branching paths" Iterative: "A→B→check→A | Loop until condition met" Chain_Control: Success_Rules: Continue: "Pass enriched context to next command" Cache: "Store intermediate results for reuse" Skip: "Skip redundant operations if cached" Failure_Rules: Critical: "STOP: Halt chain, preserve context" Recoverable: "RETRY: 3 attempts w/ exponential backoff" Non_Critical: "CONTINUE: Log warning, proceed degraded" Validation: "BRANCH: Alternative path or manual fix" Context_Flow: Persist: "Maintain context throughout chain" Selective: "Pass only relevant results between commands" Cleanup: "Clear context after chain completion" Checkpoint: "Auto-save state before critical ops" Intelligent_MCP_Selection: Command_Defaults: analyze + --architecture: "Suggest --seq for system analysis" build + --react: "Suggest --magic for UI components" test + --e2e: "Suggest --pup for browser testing" explain + library_name: "Suggest --c7 for documentation" design + --api: "Suggest --seq --c7 for comprehensive design" troubleshoot + --investigate: "Suggest --seq for root cause analysis" improve + --performance: "Suggest --seq --pup for optimization analysis" Context_Triggers: Import_Errors: "→ C7 lookup REQUIRED" Complex_Debugging: "→ Sequential thinking" UI_Requests: "→ Magic builder" E2E_Testing: "→ Puppeteer automation" ## Automatic MCP Context Detection ```yaml Context_Detection_Patterns: Library_References: Triggers: - "import .* from ['\"][^./].*['\"]" # Non-relative imports - "require\\(['\"][^./].*['\"]\\)" # CommonJS external - "from \\w+ import" # Python external - "@\\w+/" # Scoped packages Action: "→ C7 resolve-library-id REQUIRED" Blocking: "Implementation blocked until documentation found" Complex_Problem_Indicators: Keywords: ["architecture", "design", "system", "complex", "debug", "investigate", "root cause", "bottleneck"] Error_Patterns: ["multiple errors", "cascading failures", "performance degradation"] Scope_Indicators: ["multi-file", "cross-component", "system-wide"] Action: "→ Sequential thinking RECOMMENDED" UI_Component_Requests: Keywords: ["button", "form", "modal", "dialog", "dropdown", "table", "chart", "dashboard", "component"] Framework_Mentions: ["react", "vue", "svelte", "angular"] File_Types: ["*.tsx", "*.jsx", "*.vue", "*.svelte"] Action: "→ Magic builder RECOMMENDED" Browser_Automation_Needs: Keywords: ["screenshot", "e2e", "integration test", "browser", "selenium", "automation"] Test_Patterns: ["cypress", "playwright", "puppeteer", "webdriver"] Action: "→ Puppeteer automation RECOMMENDED" Research_Requirements: External_Library_Detection: Pattern: "Any import/require from non-relative path" Rule: "CRITICAL → Research REQUIRED before implementation" Process: 1: "C7 resolve-library-id with detected library name" 2: "If not found → WebSearch '[library] official documentation'" 3: "Extract: Installation, basic usage, common patterns" 4: "Block implementation if confidence < 90%" Unknown_Pattern_Detection: Triggers: ["unfamiliar syntax", "new framework", "unknown API"] Phrases_To_Block: ["might work", "probably", "I think", "typical pattern"] Required_Instead: "Documentation confirms", "Official source states" Action: "Research → Verify → Document source → Implement" Low_Confidence_Indicators: Uncertainty_Language: ["maybe", "should", "typically", "usually"] Missing_Evidence: "No source citation available" Action: "BLOCK implementation until research complete" Auto_Activation_Rules: Command_Based: /build + UI_keywords: "Suggest --magic for component generation" /analyze + complexity_indicators: "Suggest --seq for deep analysis" /test + browser_keywords: "Suggest --pup for automation" /explain + library_name: "Suggest --c7 for documentation" File_Based: "*.tsx|*.jsx": "Frontend context → --magic available" "*.test.*|*.spec.*": "Testing context → --pup available" "*api*|*server*": "Backend context → --seq for design" Error_Based: "ModuleNotFoundError": "→ C7 lookup REQUIRED" "TypeError": "→ Sequential analysis RECOMMENDED" "Build failures": "→ Sequential troubleshooting" Override_Controls: User_Flags_Priority: "Explicit flags > Auto-detection > Defaults" Disable_All: "--no-mcp overrides all auto-detection" Selective_Disable: "--no-c7, --no-seq, --no-magic, --no-pup" Force_Enable: "--c7, --seq, --magic, --pup override context detection" ``` Synergistic_Patterns: --magic + --pup: "Generate UI components and test immediately" --seq + --c7: "Complex analysis with authoritative documentation" --seq + --think-hard: "Deep architectural analysis with documentation" --c7 + --uc: "Research with compressed output for token efficiency" ``` ## Development Workflows ```yaml Full_Stack_Development: Chain: "load→analyze→design→build→test→scan→deploy" Flags: ["--think", "--magic", "--validate"] MCP_Usage: ["--c7 for docs", "--magic for UI", "--seq for design"] Time: "Typical development session" Context_Handoff: load→analyze: "Project understanding" analyze→design: "Issues & architecture" design→build: "Patterns & structure" build→test: "Implementation" test→scan: "Coverage & results" scan→deploy: "Security validation" Feature_Implementation: Chain: "analyze --code→design --feature→build --feature→test→git --commit" Flags: ["--think", "--magic"] MCP_Usage: ["--magic for components", "--c7 for patterns"] Time: "Moderate duration" Bug_Investigation_Fix: Chain: "troubleshoot --investigate→analyze --code→improve --quality→test→git --commit" Flags: ["--think-hard", "--seq"] MCP_Usage: ["--seq for investigation", "--c7 for solutions"] Time: "Variable duration" Tech_Debt_Reduction: Chain: "analyze --architecture→design --refactor→improve --quality→test→document" Flags: ["--think-hard", "--refactor", "--quality"] MCP_Usage: ["--seq for analysis", "--c7 for patterns"] Time: "Extended session" ``` ## Git Integration Patterns ```yaml Git_Workflows: Auto_Safety_Checks: Before_Commit: - "git status → Verify intended files" - "git diff --staged → Review changes" - "Run tests if available" - "Check for secrets/credentials" Before_Push: - "Verify target branch & remote" - "Check for force push implications" - "Ensure CI/CD readiness" Before_Merge: - "Test for conflicts" - "Verify branch policies" - "Check approval requirements" Commit_Standards: Format: "{type}: {description}\n\n{body}\n\n🤖 Generated with [Claude Code]\n\nCo-Authored-By: Claude" Types: ["feat", "fix", "docs", "style", "refactor", "test", "chore"] Validation: - "Type matches change nature" - "Description < 50 chars" - "Body explains why, not what" Branch_Management: Strategy: Feature: "feature/{description}" Bugfix: "bugfix/{description}" Release: "release/{version}" Hotfix: "hotfix/{description}" Protection: Main: "No direct push, PR required" Release: "Admin approval required" Feature: "Auto-delete after merge" Conflict_Resolution: Detection: "Auto-detect during pull/merge" Strategies: Simple: "Auto-resolve if non-overlapping" Complex: "Interactive 3-way merge" Binary: "Choose version explicitly" Recovery: Abort: "git merge --abort → restore state" Stash: "git stash → try different approach" Branch: "Create conflict-resolution branch" ``` ## Checkpoint & Recovery System ```yaml Checkpoint_Integration: "@include recovery-state-patterns.yml#Checkpoint_Structure" "@include recovery-state-patterns.yml#Automatic_Triggers" "@include recovery-state-patterns.yml#Recovery_Commands" "@include recovery-state-patterns.yml#Recovery_Framework" ``` ## Token Budget Management ```yaml Cost_Categories: Native_Tools: "No token cost" Light_MCP: "Minimal usage" Medium_MCP: "Moderate usage" Heavy_MCP: "Extensive usage" Budget_Escalation: 1: "Native first for simple tasks" 2: "C7 for library questions" 3: "Sequential for complex analysis" 4: "Combine MCPs for synergy" Abort_Conditions: Context_Usage: "High context usage → native tools" Timeout_Errors: "MCP timeout/error → fallback" Diminishing_Returns: "Poor results → stop MCP usage" Failover_Integration: "@include recovery-state-patterns.yml#Standard_Recovery_Patterns" Error_Recovery_Standards: "@include recovery-state-patterns.yml#Standard_Recovery_Patterns" ``` ## Performance & Monitoring ```yaml Performance_Tracking: Metrics: Build_Times: "Track duration trends" Test_Execution: "Monitor suite performance" Bundle_Sizes: "Track asset size changes" Memory_Usage: "Monitor CLI consumption" MCP_Response_Times: "Track server performance" Token_Consumption: "Monitor MCP usage efficiency" Baselines: Initial: "Capture on first run" Update: "Update weekly" Analysis: "Identify regressions" Alert_Thresholds: Build_Time: "Significant increase from baseline" Bundle_Size: "Notable increase from baseline" Test_Time: "Substantial increase from baseline" Memory: "Major increase from baseline" MCP_Timeout: "Extended duration" Storage: ".claudedocs/metrics/performance-{YYYY-MM-DD}.jsonl" Server_Performance: Response_Times: Context7: "Fast response (network dependent)" Sequential: "Moderate duration (complexity dependent)" Magic: "Fast to moderate (component complexity)" Puppeteer: "Fast to moderate (page load dependent)" Resource_Usage: Context7: "Low CPU, Medium Network" Sequential: "High CPU, Low Network" Magic: "Medium CPU, High Network" Puppeteer: "Medium CPU, Low Network" Reliability_Scores: Context7: "Very high (dependent on library availability)" Sequential: "Very high (internal processing)" Magic: "High (external service dependency)" Puppeteer: "Very high (browser dependency)" ``` ## Command Integration ```yaml Chain_Commands: Execute: Predefined: "/chain 'feature-dev' --magic --think" Custom: "/analyze → /build → /test" Conditional: "/test && /deploy || /troubleshoot" Control: Status: "/chain-status | Show current progress" Results: "/chain-results | Show accumulated context" Pause: "/chain-pause | Pause at current step" Resume: "/chain-resume | Continue from pause" Abort: "/chain-abort | Stop and cleanup" Retry: "/chain-retry | Retry failed step" Command_Hooks: Build_Hooks: Pre: ["Clean artifacts", "Verify dependencies", "Set environment", "Check MCP health"] During: ["Monitor progress", "Cache layers", "Handle errors", "Track token usage"] Post: ["Verify output", "Run smoke tests", "Update manifests", "Log MCP performance"] Test_Hooks: Pre: ["Reset test data", "Start services", "Clear caches", "Connect Puppeteer if needed"] During: ["Track coverage", "Monitor performance", "Capture logs", "Handle browser events"] Post: ["Generate reports", "Clean test data", "Archive results", "Disconnect browser"] Deploy_Hooks: Pre: ["Verify environment", "Check permissions", "Backup current", "Validate with Sequential"] During: ["Monitor health", "Track progress", "Handle rollback", "Log deployment events"] Post: ["Verify deployment", "Run health checks", "Update docs", "Generate deployment report"] ``` ## Estimation Methodology ```yaml Estimation_Methodology: Time_Estimation_Framework: Development_Phases: Planning: "Requirements analysis & design: 10-15% of total" Implementation: "Core development work: 50-60% of total" Testing: "Unit, integration & system testing: 15-25% of total" Integration: "System integration & deployment: 5-10% of total" Buffer: "Unknown unknowns & contingency: 10-20% of total" Complexity_Scoring: Low_Complexity: "Well-understood, established patterns: 1-3 days" Medium_Complexity: "Some unknowns, moderate integration: 3-10 days" High_Complexity: "Research required, complex integration: 1-4 weeks" Very_High_Complexity: "New technology, architectural changes: 1-3 months" Team_Velocity_Factors: Solo_Developer: "Multiplier: 1.0 (baseline)" Small_Team_2_3: "Multiplier: 0.8 (coordination overhead)" Medium_Team_4_8: "Multiplier: 0.6 (communication overhead)" Large_Team_9Plus: "Multiplier: 0.4 (significant coordination)" Risk_Assessment_Framework: Technical_Risks: New_Technology: "Learning curve impact: +25-50% time" Complex_Integration: "Multiple system touchpoints: +20-40% time" Performance_Requirements: "Optimization needs: +15-30% time" Legacy_System_Integration: "Technical debt impact: +30-60% time" Resource_Risks: Key_Person_Dependency: "Single expert required: +20-40% time" External_Dependencies: "Third-party deliverables: +10-30% time" Skill_Gap: "Team learning required: +25-50% time" Estimation_Output_Format: Three_Point_Estimation: Optimistic: "Best case scenario (10% probability)" Realistic: "Most likely outcome (50% probability)" Pessimistic: "Worst case scenario (90% probability)" Confidence_Levels: High_Confidence: "Well-understood requirements: ±10%" Medium_Confidence: "Some unknowns present: ±25%" Low_Confidence: "Significant uncertainties: ±50%" Resource_Planning: Developer_Hours: "Total development effort" QA_Hours: "Testing & quality assurance effort" DevOps_Hours: "Deployment & infrastructure setup" Project_Management: "Coordination & communication overhead" ``` --- *Execution Patterns v2 - Unified workflow system, MCP orchestration, git operations, and execution lifecycle*