UNPKG

claude-code-subagents-orchestrator

Version:

Claude Code Sub-agents Orchestrator - A powerful MCP server for orchestrating multiple AI sub-agents for complex task execution in Claude Code

1,366 lines (1,179 loc) โ€ข 45.8 kB
# Comprehensive Usage Examples and Workflow Demonstrations This document provides practical examples of using the Claude Code Subagents Orchestrator for real-world development scenarios. ## Quick Start Examples ### Basic Agent Listing and Installation ```javascript // Connect to the MCP server import { MCPClient } from '@modelcontextprotocol/sdk/client/index.js'; const client = new MCPClient({ name: 'example-app', version: '1.0.0' }); await client.connect({ command: 'node', args: ['path/to/orchestrator/server.js'] }); // List available agents const agents = await client.call('listAgents', {}); console.log(`Found ${agents.totalCount} agents across ${Object.keys(agents.categories).length} categories`); // Install specific agents if needed const installation = await client.call('installAgents', { agents: ['backend-architect', 'frontend-developer', 'devops-engineer'], force: false }); console.log(`Successfully installed: ${installation.summary.successful}/${installation.summary.total} agents`); ``` ### Simple Delegation Example ```javascript // Force delegation to a specialist agent const delegation = await client.call('forceDelegation', { task: 'Design a RESTful API for a social media platform with user authentication, posts, and real-time messaging', targetAgent: 'backend-architect', enforcementLevel: 'strict' }); // Validate that delegation occurred const validation = await client.call('validateDelegation', { originalRequest: { task: 'Design a RESTful API for a social media platform', targetAgent: 'backend-architect' }, response: delegation, expectedAgent: 'backend-architect' }); if (validation.delegationOccurred) { console.log('โœ… Task successfully delegated to backend-architect'); console.log('Evidence:', validation.evidence); } else { console.error('โŒ Delegation failed'); } ``` ## Real-World Workflow Examples ### Example 1: E-Commerce Application Development This example demonstrates building a complete e-commerce application using multiple specialized agents. ```javascript async function buildECommerceApp() { console.log('๐Ÿš€ Starting e-commerce application development...'); // Step 1: Project Analysis and Planning const projectAnalysis = await client.call('analyzeProjectState', { projectPath: './ecommerce-app', includeFileStructure: true, includeDependencies: true }); console.log(`๐Ÿ“Š Project type: ${projectAnalysis.project.type}`); console.log(`๐Ÿ“‹ Recommendations: ${projectAnalysis.recommendations.length}`); // Step 2: Generate Multi-Agent Workflow const workflow = await client.call('generateMultiAgentWorkflow', { task: 'Build a complete e-commerce application with user authentication, product catalog, shopping cart, payment processing, and admin dashboard', complexity: 'high', preferredAgents: ['backend-architect', 'frontend-developer', 'database-expert', 'security-engineer', 'devops-engineer'], constraints: { maxSteps: 12, timeoutMs: 7200000, // 2 hours parallel: true }, context: { technologies: ['Node.js', 'React', 'PostgreSQL', 'Redis'], requirements: ['mobile-responsive', 'payment-integration', 'real-time-updates'], scale: 'medium-enterprise' } }); console.log(`๐Ÿ“‹ Generated workflow with ${workflow.analysis.requiredAgents.length} agents and ${workflow.workflow.steps.length} steps`); console.log(`โฑ๏ธ Estimated duration: ${Math.round(workflow.analysis.estimatedDuration / 60000)} minutes`); const results = []; // Step 3: Execute Backend Architecture console.log('\n๐Ÿ—๏ธ Phase 1: Backend Architecture Design'); const backendDesign = await client.call('forceDelegation', { task: `Design the backend architecture for an e-commerce platform with: - User authentication and authorization - Product catalog management - Shopping cart and order processing - Payment integration (Stripe/PayPal) - Inventory management - Admin dashboard API - Real-time notifications Technical requirements: - Node.js with Express framework - PostgreSQL for primary data - Redis for caching and sessions - JWT authentication - RESTful API design - Microservices architecture consideration`, targetAgent: 'backend-architect', enforcementLevel: 'strict', context: { phase: 'architecture', technologies: workflow.context.technologies, scalability: 'horizontal-scaling' } }); results.push({ phase: 'backend-architecture', agent: 'backend-architect', status: 'completed', output: backendDesign.output }); // Step 4: Database Design console.log('\n๐Ÿ—„๏ธ Phase 2: Database Design'); const databaseDesign = await client.call('forceDelegation', { task: `Design the database schema for the e-commerce platform based on the backend architecture: Required entities: - Users (customers, admins, vendors) - Products (with variants, categories, inventory) - Orders (with items, status, payments) - Shopping carts (persistent, guest support) - Reviews and ratings - Payment transactions - Audit logs Requirements: - PostgreSQL with proper indexing - Data integrity and constraints - Performance optimization - Migration strategy - Backup and recovery plan`, targetAgent: 'database-expert', enforcementLevel: 'strict', context: { phase: 'database-design', dependsOn: ['backend-architecture'], backendSpecs: backendDesign.output } }); results.push({ phase: 'database-design', agent: 'database-expert', status: 'completed', output: databaseDesign.output }); // Step 5: Security Implementation console.log('\n๐Ÿ”’ Phase 3: Security Implementation'); const securityImplementation = await client.call('forceDelegation', { task: `Implement comprehensive security measures for the e-commerce platform: Security requirements: - JWT authentication with refresh tokens - Password hashing and validation - Input validation and sanitization - SQL injection prevention - XSS protection - CSRF protection - Rate limiting - Payment data security (PCI compliance) - Data encryption at rest and in transit - Security headers and HTTPS enforcement Integration with: - Backend architecture specifications - Database schema design - Frontend authentication flow`, targetAgent: 'security-engineer', enforcementLevel: 'strict', context: { phase: 'security', complianceRequirements: ['PCI-DSS', 'GDPR'], authenticationMethod: 'JWT' } }); results.push({ phase: 'security', agent: 'security-engineer', status: 'completed', output: securityImplementation.output }); // Step 6: Frontend Development console.log('\n๐ŸŽจ Phase 4: Frontend Development'); const frontendDevelopment = await client.call('forceDelegation', { task: `Develop the frontend application for the e-commerce platform: Required components and pages: - User authentication (login, register, profile) - Product catalog with search and filters - Product detail pages with reviews - Shopping cart and checkout flow - Order history and tracking - Admin dashboard for product/order management - Responsive design for mobile devices - Real-time notifications Technical requirements: - React with TypeScript - State management (Redux or Context API) - Responsive design (mobile-first) - Performance optimization - Accessibility compliance (WCAG 2.1) - Integration with backend APIs - Payment flow integration - Real-time updates (WebSocket)`, targetAgent: 'frontend-developer', enforcementLevel: 'strict', context: { phase: 'frontend', framework: 'React', stateManagement: 'Redux Toolkit', uiLibrary: 'Material-UI', backendSpecs: backendDesign.output } }); results.push({ phase: 'frontend', agent: 'frontend-developer', status: 'completed', output: frontendDevelopment.output }); // Step 7: DevOps and Deployment console.log('\n๐Ÿš€ Phase 5: DevOps and Deployment'); const devopsDeployment = await client.call('forceDelegation', { task: `Set up DevOps infrastructure and deployment pipeline for the e-commerce platform: Infrastructure requirements: - Docker containerization for all services - Kubernetes or Docker Compose orchestration - CI/CD pipeline (GitHub Actions or GitLab CI) - Environment management (dev, staging, prod) - Database migrations and seeding - Redis configuration for caching - Load balancing and auto-scaling - Monitoring and logging (Prometheus, Grafana) - Backup and disaster recovery - SSL certificates and domain configuration Deployment targets: - AWS, Google Cloud, or Azure - CDN for static assets - Database hosting (managed PostgreSQL) - Redis hosting (managed or self-hosted)`, targetAgent: 'devops-engineer', enforcementLevel: 'strict', context: { phase: 'devops', cloudProvider: 'AWS', containerization: 'Docker', orchestration: 'Kubernetes' } }); results.push({ phase: 'devops', agent: 'devops-engineer', status: 'completed', output: devopsDeployment.output }); // Step 8: Testing Strategy console.log('\n๐Ÿงช Phase 6: Testing Implementation'); const testingImplementation = await client.call('forceDelegation', { task: `Implement comprehensive testing strategy for the e-commerce platform: Testing requirements: - Unit tests for backend API endpoints - Integration tests for database operations - Frontend component testing (React Testing Library) - End-to-end testing (Cypress or Playwright) - Performance testing for critical paths - Security testing for authentication and payments - Load testing for scalability validation - API contract testing - Mobile responsiveness testing Test coverage targets: - Backend: 90%+ code coverage - Frontend: 85%+ component coverage - Critical user flows: 100% e2e coverage Test automation: - CI/CD integration - Automated test runs on PR - Performance regression testing`, targetAgent: 'qa-engineer', enforcementLevel: 'strict', context: { phase: 'testing', testingFrameworks: ['Jest', 'React Testing Library', 'Cypress'], coverageTargets: { backend: 90, frontend: 85 } } }); results.push({ phase: 'testing', agent: 'qa-engineer', status: 'completed', output: testingImplementation.output }); // Step 9: Final Integration and Validation console.log('\n๐Ÿ”— Phase 7: Final Integration'); // Validate all phases completed successfully const completedPhases = results.filter(r => r.status === 'completed'); const totalPhases = results.length; if (completedPhases.length === totalPhases) { console.log(`โœ… All ${totalPhases} phases completed successfully!`); // Generate final deployment guide const deploymentGuide = await client.call('generateRecoveryPrompt', { executionContext: { task: 'E-commerce application development', completedPhases: results.map(r => r.phase), agents: results.map(r => r.agent) }, failedStep: 'none', errorDetails: { message: 'All phases completed - generate deployment guide', code: 'SUCCESS' }, recoveryOptions: ['finalize'] }); console.log('\n๐Ÿ“š Final deliverables generated:'); results.forEach(result => { console.log(` โœ… ${result.phase} (${result.agent})`); }); return { success: true, phases: results, totalDuration: Date.now() - startTime, deploymentGuide: deploymentGuide }; } else { console.error(`โŒ ${totalPhases - completedPhases.length} phases failed`); // Generate recovery strategy for failed phases const failedPhases = results.filter(r => r.status !== 'completed'); const recovery = await client.call('generateRecoveryPrompt', { executionContext: { task: 'E-commerce application development', completedPhases: completedPhases.map(r => r.phase), failedPhases: failedPhases.map(r => r.phase) }, failedStep: failedPhases[0]?.phase || 'unknown', errorDetails: { message: `${failedPhases.length} phases failed`, code: 'PARTIAL_COMPLETION' }, recoveryOptions: ['retry', 'alternative'] }); return { success: false, completedPhases, failedPhases, recovery }; } } // Execute the e-commerce workflow const startTime = Date.now(); const result = await buildECommerceApp(); if (result.success) { console.log(`\n๐ŸŽ‰ E-commerce application development completed in ${Math.round(result.totalDuration / 60000)} minutes`); } else { console.log(`\nโš ๏ธ Partial completion - ${result.completedPhases.length} phases successful`); console.log('Recovery strategy:', result.recovery.recoveryStrategy); } ``` ### Example 2: Legacy System Migration This example shows how to orchestrate a complex legacy system migration using multiple agents. ```javascript async function migrateLegacySystem() { console.log('๐Ÿ”„ Starting legacy system migration workflow...'); // Step 1: Legacy System Analysis const legacyAnalysis = await client.call('forceDelegation', { task: `Analyze the legacy monolithic application for migration to microservices: Analysis requirements: - Architecture assessment of current monolith - Identify business domain boundaries - Database dependency analysis - Performance bottleneck identification - Security vulnerability assessment - Integration point mapping - Data flow analysis - Risk assessment for migration Current system context: - Java Spring Boot monolith - MySQL database - 5 years of technical debt - 50+ API endpoints - 10+ business modules - High coupling between components`, targetAgent: 'backend-architect', enforcementLevel: 'strict', context: { migrationPhase: 'analysis', currentTech: ['Java', 'Spring Boot', 'MySQL'], targetTech: ['Node.js', 'PostgreSQL', 'Docker', 'Kubernetes'] } }); // Step 2: Migration Strategy Planning const migrationStrategy = await client.call('forceDelegation', { task: `Develop a comprehensive migration strategy based on the legacy analysis: Strategy requirements: - Phase-by-phase migration plan - Service decomposition strategy - Data migration approach - Zero-downtime migration techniques - Rollback strategies for each phase - Risk mitigation plans - Timeline and resource estimation - Success criteria definition Migration approach: - Strangler Fig pattern implementation - Database decomposition strategy - API gateway introduction - Service mesh consideration - Monitoring and observability setup`, targetAgent: 'solution-architect', enforcementLevel: 'strict', context: { migrationPhase: 'strategy', dependsOn: 'legacy-analysis', approach: 'strangler-fig-pattern' } }); // Step 3: Infrastructure Preparation const infrastructureSetup = await client.call('forceDelegation', { task: `Prepare the infrastructure for the microservices migration: Infrastructure requirements: - Kubernetes cluster setup - Service mesh implementation (Istio) - API gateway deployment - Monitoring stack (Prometheus, Grafana, Jaeger) - Logging aggregation (ELK stack) - CI/CD pipeline setup - Container registry - Database migration tools - Backup and recovery systems Platform setup: - AWS EKS or Google GKE - Infrastructure as Code (Terraform) - GitOps workflow (ArgoCD) - Security scanning and compliance`, targetAgent: 'devops-engineer', enforcementLevel: 'strict', context: { migrationPhase: 'infrastructure', cloudProvider: 'AWS', orchestration: 'Kubernetes', serviceMesh: 'Istio' } }); // Step 4: First Microservice Implementation const firstMicroservice = await client.call('forceDelegation', { task: `Implement the first microservice as part of the migration strategy: Microservice requirements: - Extract user authentication service - Implement in Node.js with TypeScript - JWT token management - User profile management - Integration with legacy database - API compatibility with monolith - Comprehensive logging and monitoring - Health checks and readiness probes Technical implementation: - Express.js framework - PostgreSQL for user data - Redis for session management - Docker containerization - Kubernetes deployment manifests - OpenAPI documentation`, targetAgent: 'backend-developer', enforcementLevel: 'strict', context: { migrationPhase: 'first-service', serviceName: 'user-authentication', technology: 'Node.js + TypeScript' } }); // Step 5: Data Migration Planning const dataMigration = await client.call('forceDelegation', { task: `Plan and implement data migration for the extracted microservice: Data migration requirements: - Extract user data from legacy MySQL - Transform to new PostgreSQL schema - Implement dual-write pattern during transition - Data consistency validation - Rollback procedures - Performance optimization - Zero-downtime migration execution Migration tools and techniques: - Database migration scripts - Data validation tools - CDC (Change Data Capture) setup - Sync verification processes - Migration monitoring and alerting`, targetAgent: 'data-engineer', enforcementLevel: 'strict', context: { migrationPhase: 'data-migration', sourceDB: 'MySQL', targetDB: 'PostgreSQL', migrationPattern: 'dual-write' } }); // Step 6: Testing and Validation const migrationTesting = await client.call('forceDelegation', { task: `Implement comprehensive testing for the migration: Testing requirements: - Integration testing between microservice and monolith - Data consistency testing - Performance testing (load and stress) - Security testing for new authentication service - End-to-end user journey testing - Rollback procedure testing - Monitoring and alerting validation Test automation: - Automated integration test suite - Performance regression testing - Security vulnerability scanning - Infrastructure testing (chaos engineering)`, targetAgent: 'qa-engineer', enforcementLevel: 'strict', context: { migrationPhase: 'testing', testTypes: ['integration', 'performance', 'security', 'e2e'], automationLevel: 'high' } }); // Step 7: Gradual Rollout const gradualRollout = await client.call('forceDelegation', { task: `Plan and execute gradual rollout of the new microservice: Rollout requirements: - Blue-green deployment strategy - Feature flag implementation - Traffic splitting (canary deployment) - Real-time monitoring and alerting - Automatic rollback triggers - User experience monitoring - Performance metrics tracking Rollout phases: - 5% traffic to new service - 25% traffic if metrics are healthy - 50% traffic with continued monitoring - 100% traffic with legacy service backup - Legacy service decommissioning`, targetAgent: 'devops-engineer', enforcementLevel: 'strict', context: { migrationPhase: 'rollout', strategy: 'blue-green-canary', trafficSplitSteps: [5, 25, 50, 100] } }); console.log('โœ… Legacy system migration workflow completed successfully!'); return { success: true, phases: [ { name: 'Legacy Analysis', status: 'completed' }, { name: 'Migration Strategy', status: 'completed' }, { name: 'Infrastructure Setup', status: 'completed' }, { name: 'First Microservice', status: 'completed' }, { name: 'Data Migration', status: 'completed' }, { name: 'Testing & Validation', status: 'completed' }, { name: 'Gradual Rollout', status: 'completed' } ] }; } ``` ### Example 3: Performance Optimization Project This example demonstrates using multiple specialist agents for a comprehensive performance optimization project. ```javascript async function optimizeApplicationPerformance() { console.log('โšก Starting application performance optimization...'); // Step 1: Performance Analysis and Profiling const performanceAnalysis = await client.call('forceDelegation', { task: `Conduct comprehensive performance analysis of the application: Analysis scope: - Frontend performance metrics (Core Web Vitals) - Backend API response times and throughput - Database query performance and optimization - Network latency and bandwidth usage - Memory usage and garbage collection patterns - CPU utilization and bottlenecks - Cache hit rates and effectiveness - Third-party service dependencies Tools and metrics: - Google Lighthouse for frontend - APM tools (New Relic, DataDog) for backend - Database slow query logs - Browser developer tools analysis - Load testing with k6 or Artillery - Memory profiling tools Current performance baseline: - Page load time: 4.2 seconds - API response time: 800ms average - Database queries: 150ms average - Memory usage: 512MB average`, targetAgent: 'performance-engineer', enforcementLevel: 'strict', context: { optimizationPhase: 'analysis', currentMetrics: { pageLoadTime: 4200, apiResponseTime: 800, dbQueryTime: 150 }, targetMetrics: { pageLoadTime: 2000, apiResponseTime: 300, dbQueryTime: 50 } } }); // Step 2: Frontend Optimization const frontendOptimization = await client.call('forceDelegation', { task: `Optimize frontend performance based on the analysis: Frontend optimization tasks: - Bundle size reduction and code splitting - Image optimization and lazy loading - CSS optimization and critical path - JavaScript minification and tree shaking - Service worker implementation for caching - Preloading and prefetching strategies - Font optimization and loading - Third-party script optimization - Progressive Web App features Specific improvements: - Implement React.lazy() for code splitting - Optimize images with WebP format - Implement virtual scrolling for large lists - Add service worker for offline capability - Optimize CSS delivery and remove unused styles - Implement preconnect for external resources Target improvements: - Reduce bundle size by 40% - Improve LCP (Largest Contentful Paint) to <2s - Achieve CLS (Cumulative Layout Shift) <0.1 - Improve FID (First Input Delay) to <100ms`, targetAgent: 'frontend-developer', enforcementLevel: 'strict', context: { optimizationPhase: 'frontend', framework: 'React', bundler: 'Webpack', targetMetrics: { bundleReduction: 40, lcp: 2000, cls: 0.1, fid: 100 } } }); // Step 3: Backend API Optimization const backendOptimization = await client.call('forceDelegation', { task: `Optimize backend API performance: Backend optimization tasks: - Database query optimization and indexing - API response caching strategy - Connection pooling optimization - Microservice communication optimization - Background job processing improvements - Memory leak identification and fixes - CPU usage optimization - Async/await pattern optimization Specific improvements: - Implement Redis caching for frequent queries - Add database connection pooling - Optimize N+1 query problems - Implement pagination for large datasets - Add compression for API responses - Optimize JSON serialization - Implement request rate limiting - Add database read replicas Target improvements: - Reduce API response time from 800ms to 300ms - Increase throughput by 3x - Reduce database query time by 70% - Improve cache hit rate to 90%`, targetAgent: 'backend-architect', enforcementLevel: 'strict', context: { optimizationPhase: 'backend', technology: 'Node.js + Express', database: 'PostgreSQL', caching: 'Redis' } }); // Step 4: Database Optimization const databaseOptimization = await client.call('forceDelegation', { task: `Optimize database performance: Database optimization tasks: - Query performance analysis and optimization - Index creation and optimization - Database schema optimization - Connection pool tuning - Query plan analysis - Database statistics update - Partition strategy implementation - Read replica configuration Specific improvements: - Create composite indexes for frequent queries - Optimize slow queries identified in analysis - Implement query result caching - Add database monitoring and alerting - Optimize table partitioning strategy - Implement connection pooling - Add read replicas for reporting queries - Optimize database configuration parameters Target improvements: - Reduce query execution time by 70% - Improve index utilization to 95% - Reduce database CPU usage by 50% - Achieve 99.9% uptime`, targetAgent: 'database-expert', enforcementLevel: 'strict', context: { optimizationPhase: 'database', dbType: 'PostgreSQL', currentQueries: 'slow_query_analysis.sql', targetPerformance: { queryTimeReduction: 70, indexUtilization: 95, cpuReduction: 50 } } }); // Step 5: Infrastructure and DevOps Optimization const infrastructureOptimization = await client.call('forceDelegation', { task: `Optimize infrastructure and deployment pipeline: Infrastructure optimization tasks: - Container optimization and resource tuning - Kubernetes resource allocation optimization - CDN configuration and optimization - Load balancer optimization - Auto-scaling configuration - Monitoring and alerting optimization - CI/CD pipeline performance improvement - Security scanning optimization Specific improvements: - Optimize Docker images for smaller size - Configure horizontal pod autoscaling - Implement CDN for static assets - Optimize load balancer health checks - Add performance monitoring dashboards - Implement blue-green deployments - Optimize build pipeline caching - Add performance regression testing Target improvements: - Reduce deployment time by 50% - Improve auto-scaling response time - Achieve 99.99% availability - Reduce infrastructure costs by 30%`, targetAgent: 'devops-engineer', enforcementLevel: 'strict', context: { optimizationPhase: 'infrastructure', platform: 'Kubernetes', cloudProvider: 'AWS', monitoring: 'Prometheus + Grafana' } }); // Step 6: Performance Testing and Validation const performanceTesting = await client.call('forceDelegation', { task: `Implement comprehensive performance testing: Performance testing requirements: - Load testing for normal traffic patterns - Stress testing for peak capacity - Spike testing for traffic surges - Volume testing for large datasets - Endurance testing for memory leaks - Browser performance testing - Mobile performance testing - API performance testing Testing scenarios: - Simulate 1000 concurrent users - Test with 10x normal database load - Validate performance under failover conditions - Test performance with slow network conditions - Validate caching effectiveness - Test auto-scaling behavior Success criteria: - Page load time <2 seconds (95th percentile) - API response time <300ms (95th percentile) - System remains stable under 10x load - No memory leaks during 24-hour test - All Core Web Vitals in green`, targetAgent: 'qa-engineer', enforcementLevel: 'strict', context: { optimizationPhase: 'testing', testingTools: ['k6', 'Artillery', 'Lighthouse CI'], loadTestScenarios: { normalLoad: 100, peakLoad: 1000, stressLoad: 5000 } } }); // Step 7: Monitoring and Alerting Setup const monitoringSetup = await client.call('forceDelegation', { task: `Set up comprehensive performance monitoring: Monitoring requirements: - Real User Monitoring (RUM) implementation - Synthetic monitoring for critical paths - Application Performance Monitoring (APM) - Infrastructure monitoring - Database performance monitoring - Business metrics tracking - Error tracking and alerting - Performance regression detection Specific implementations: - Google Analytics and Core Web Vitals tracking - Datadog or New Relic APM setup - Prometheus metrics collection - Grafana dashboard creation - PagerDuty alerting integration - Performance budget alerts - SLA/SLO monitoring - Automated performance reports Alert thresholds: - Page load time >3 seconds - API response time >500ms - Error rate >1% - CPU usage >80% - Memory usage >85% - Database connections >90% of pool`, targetAgent: 'devops-engineer', enforcementLevel: 'strict', context: { optimizationPhase: 'monitoring', monitoringStack: ['Prometheus', 'Grafana', 'Datadog'], alertingChannels: ['PagerDuty', 'Slack'] } }); console.log('โœ… Performance optimization project completed successfully!'); // Generate performance improvement report const improvementReport = { success: true, phases: [ { name: 'Performance Analysis', status: 'completed', duration: '2 hours' }, { name: 'Frontend Optimization', status: 'completed', duration: '8 hours' }, { name: 'Backend Optimization', status: 'completed', duration: '12 hours' }, { name: 'Database Optimization', status: 'completed', duration: '6 hours' }, { name: 'Infrastructure Optimization', status: 'completed', duration: '4 hours' }, { name: 'Performance Testing', status: 'completed', duration: '6 hours' }, { name: 'Monitoring Setup', status: 'completed', duration: '4 hours' } ], expectedImprovements: { pageLoadTime: { before: '4.2s', after: '<2s', improvement: '52%' }, apiResponseTime: { before: '800ms', after: '<300ms', improvement: '62%' }, databaseQueries: { before: '150ms', after: '<50ms', improvement: '67%' }, bundleSize: { before: '2.1MB', after: '<1.3MB', improvement: '38%' }, coreWebVitals: { before: 'Poor', after: 'Good', improvement: 'Significant' } }, totalEffort: '42 hours', estimatedBusinessImpact: { conversionImprovement: '15-25%', userSatisfaction: '+30%', searchRanking: '+20%', serverCosts: '-30%' } }; return improvementReport; } ``` ## Error Handling and Recovery Examples ### Example 1: Delegation Failure Recovery ```javascript async function robustTaskExecution(task, preferredAgent) { const maxRetries = 3; let retryCount = 0; while (retryCount < maxRetries) { try { console.log(`๐ŸŽฏ Attempt ${retryCount + 1}: Delegating to ${preferredAgent}`); // Attempt delegation const delegation = await client.call('forceDelegation', { task, targetAgent: preferredAgent, enforcementLevel: 'strict', context: { retryCount } }); // Validate delegation success const validation = await client.call('validateDelegation', { originalRequest: { task, targetAgent: preferredAgent }, response: delegation, expectedAgent: preferredAgent }); if (validation.delegationOccurred) { console.log('โœ… Delegation successful'); return delegation; } else { throw new Error('Delegation validation failed'); } } catch (error) { console.warn(`โš ๏ธ Attempt ${retryCount + 1} failed: ${error.message}`); retryCount++; if (retryCount >= maxRetries) { // Generate recovery strategy const recovery = await client.call('generateRecoveryPrompt', { executionContext: { task, selectedAgent: preferredAgent, retryCount, maxRetries }, failedStep: 'delegation', errorDetails: { message: error.message, code: 'MAX_RETRIES_EXCEEDED' }, recoveryOptions: ['alternative', 'rollback'] }); console.log(`๐Ÿ”„ Recovery strategy: ${recovery.recoveryStrategy}`); if (recovery.recoveryStrategy === 'alternative' && recovery.alternativeAgent) { console.log(`๐Ÿ”€ Trying alternative agent: ${recovery.alternativeAgent}`); return await robustTaskExecution(task, recovery.alternativeAgent); } else { throw new Error(`Task failed after ${maxRetries} attempts: ${error.message}`); } } // Wait before retry await new Promise(resolve => setTimeout(resolve, 2000 * retryCount)); } } } ``` ### Example 2: Multi-Agent Workflow with Error Recovery ```javascript async function resilientWorkflow(complexTask) { const workflow = await client.call('generateMultiAgentWorkflow', { task: complexTask, complexity: 'high' }); const results = []; const failedSteps = []; for (let i = 0; i < workflow.workflow.steps.length; i++) { const step = workflow.workflow.steps[i]; try { console.log(`๐Ÿ”„ Executing step ${i + 1}/${workflow.workflow.steps.length}: ${step.description}`); const result = await robustTaskExecution(step.task, step.agent); results.push({ stepNumber: i + 1, step: step.description, agent: step.agent, status: 'completed', result: result }); console.log(`โœ… Step ${i + 1} completed successfully`); } catch (error) { console.error(`โŒ Step ${i + 1} failed: ${error.message}`); failedSteps.push({ stepNumber: i + 1, step: step.description, agent: step.agent, error: error.message }); // Check if this step is critical if (step.critical !== false) { console.log('๐Ÿšจ Critical step failed - generating recovery strategy'); const recovery = await client.call('generateRecoveryPrompt', { executionContext: { task: complexTask, completedSteps: results.map(r => r.step), failedStep: step.description, remainingSteps: workflow.workflow.steps.slice(i + 1).map(s => s.description) }, failedStep: step.description, errorDetails: { message: error.message, code: 'STEP_EXECUTION_FAILED' }, recoveryOptions: ['retry', 'skip', 'alternative'] }); if (recovery.recoveryStrategy === 'retry') { console.log('๐Ÿ”„ Retrying failed step...'); i--; // Retry current step continue; } else if (recovery.recoveryStrategy === 'skip') { console.log('โญ๏ธ Skipping failed step...'); results.push({ stepNumber: i + 1, step: step.description, agent: step.agent, status: 'skipped', reason: 'Recovery strategy: skip' }); } else { console.log('๐Ÿ›‘ Workflow stopped due to critical failure'); break; } } else { console.log('โš ๏ธ Non-critical step failed - continuing workflow'); results.push({ stepNumber: i + 1, step: step.description, agent: step.agent, status: 'failed', error: error.message }); } } } const successfulSteps = results.filter(r => r.status === 'completed').length; const totalSteps = workflow.workflow.steps.length; console.log(`\n๐Ÿ“Š Workflow Summary:`); console.log(`โœ… Successful steps: ${successfulSteps}/${totalSteps}`); console.log(`โŒ Failed steps: ${failedSteps.length}`); console.log(`โญ๏ธ Skipped steps: ${results.filter(r => r.status === 'skipped').length}`); return { success: successfulSteps > totalSteps * 0.8, // 80% success threshold totalSteps, successfulSteps, failedSteps, results, workflowCompleted: successfulSteps === totalSteps }; } ``` ## Performance Monitoring and Optimization ### Real-Time Delegation Monitoring ```javascript async function monitorDelegationPerformance() { console.log('๐Ÿ“Š Starting delegation performance monitoring...'); const monitoringInterval = setInterval(async () => { try { // Get current metrics const metrics = await client.call('delegationMetrics', {}); console.log('\n๐Ÿ“ˆ Delegation Metrics:'); console.log(` Success Rate: ${(metrics.summary.successRate * 100).toFixed(1)}%`); console.log(` Bypass Prevention: ${(metrics.summary.bypassPreventionRate * 100).toFixed(1)}%`); console.log(` Average Execution Time: ${metrics.summary.averageExecutionTime}ms`); console.log(` Active Agents: ${metrics.summary.activeAgents}`); console.log(` Total Delegations: ${metrics.summary.totalDelegations}`); // Check for performance issues if (metrics.summary.successRate < 0.9) { console.warn('โš ๏ธ WARNING: Delegation success rate below 90%'); // Analyze failing agents for (const [agentId, health] of Object.entries(metrics.health)) { if (health.successRate < 0.8) { console.warn(` ๐Ÿ”ด Agent ${agentId}: ${(health.successRate * 100).toFixed(1)}% success rate`); } } } if (metrics.summary.bypassPreventionRate < 0.95) { console.error('๐Ÿšจ CRITICAL: Claude Code bypass detected - delegation enforcement failing'); // Attempt to reset enforcement await client.call('delegationConfig', { enforcementLevel: 'strict' }); console.log('๐Ÿ”ง Enforcement level reset to strict'); } if (metrics.summary.averageExecutionTime > 10000) { // 10 seconds console.warn('โš ๏ธ WARNING: Average execution time exceeding 10 seconds'); } } catch (error) { console.error('โŒ Error monitoring delegation performance:', error.message); } }, 30000); // Monitor every 30 seconds // Stop monitoring after 10 minutes setTimeout(() => { clearInterval(monitoringInterval); console.log('๐Ÿ“Š Monitoring session ended'); }, 600000); return monitoringInterval; } // Start monitoring const monitoring = await monitorDelegationPerformance(); ``` ### Delegation Health Check ```javascript async function performDelegationHealthCheck() { console.log('๐Ÿฅ Performing comprehensive delegation health check...'); const healthReport = { timestamp: new Date(), agentAvailability: {}, delegationTest: {}, systemHealth: {}, recommendations: [] }; try { // Check agent availability const agents = await client.call('listAgents', {}); healthReport.agentAvailability = { totalAgents: agents.totalCount, categories: agents.categories, status: 'healthy' }; console.log(`๐Ÿ“‹ Found ${agents.totalCount} agents across ${Object.keys(agents.categories).length} categories`); // Test delegation with each agent type const testAgents = ['backend-architect', 'frontend-developer', 'devops-engineer']; for (const agentName of testAgents) { try { console.log(`๐Ÿงช Testing delegation to ${agentName}...`); const testStart = Date.now(); const testDelegation = await client.call('forceDelegation', { task: `Health check test task for ${agentName}`, targetAgent: agentName, enforcementLevel: 'strict' }); const testDuration = Date.now() - testStart; const validation = await client.call('validateDelegation', { originalRequest: { task: 'health check', targetAgent: agentName }, response: testDelegation, expectedAgent: agentName }); healthReport.delegationTest[agentName] = { status: validation.delegationOccurred ? 'healthy' : 'unhealthy', responseTime: testDuration, delegationOccurred: validation.delegationOccurred, claudeCodeBypassed: validation.claudeCodeBypassed, evidence: validation.evidence }; if (validation.delegationOccurred) { console.log(` โœ… ${agentName}: Healthy (${testDuration}ms)`); } else { console.log(` โŒ ${agentName}: Unhealthy - delegation failed`); healthReport.recommendations.push(`Investigate delegation issues with ${agentName}`); } } catch (error) { console.log(` ๐Ÿ”ด ${agentName}: Error - ${error.message}`); healthReport.delegationTest[agentName] = { status: 'error', error: error.message }; healthReport.recommendations.push(`Fix delegation errors for ${agentName}: ${error.message}`); } } // Get system metrics const metrics = await client.call('delegationMetrics', {}); healthReport.systemHealth = { successRate: metrics.summary.successRate, bypassPreventionRate: metrics.summary.bypassPreventionRate, averageExecutionTime: metrics.summary.averageExecutionTime, activeAgents: metrics.summary.activeAgents, totalDelegations: metrics.summary.totalDelegations }; // Generate recommendations based on metrics if (metrics.summary.successRate < 0.95) { healthReport.recommendations.push('Success rate below 95% - investigate failing delegations'); } if (metrics.summary.bypassPreventionRate < 0.98) { healthReport.recommendations.push('Bypass prevention below 98% - check enforcement configuration'); } if (metrics.summary.averageExecutionTime > 5000) { healthReport.recommendations.push('Average execution time over 5s - investigate performance issues'); } // Overall health score const healthyAgents = Object.values(healthReport.delegationTest).filter(t => t.status === 'healthy').length; const totalTestedAgents = Object.keys(healthReport.delegationTest).length; const agentHealthScore = healthyAgents / totalTestedAgents; const systemHealthScore = (metrics.summary.successRate + metrics.summary.bypassPreventionRate) / 2; const overallHealth = (agentHealthScore + systemHealthScore) / 2; healthReport.overallHealth = { score: overallHealth, grade: overallHealth > 0.95 ? 'A' : overallHealth > 0.9 ? 'B' : overallHealth > 0.8 ? 'C' : 'D', status: overallHealth > 0.9 ? 'healthy' : overallHealth > 0.7 ? 'warning' : 'critical' }; console.log(`\n๐Ÿฅ Health Check Summary:`); console.log(`Overall Health: ${healthReport.overallHealth.grade} (${(overallHealth * 100).toFixed(1)}%)`); console.log(`Status: ${healthReport.overallHealth.status.toUpperCase()}`); console.log(`Agent Health: ${healthyAgents}/${totalTestedAgents} agents healthy`); console.log(`System Health: ${(systemHealthScore * 100).toFixed(1)}%`); if (healthReport.recommendations.length > 0) { console.log(`\n๐Ÿ“‹ Recommendations (${healthReport.recommendations.length}):`); healthReport.recommendations.forEach((rec, i) => { console.log(` ${i + 1}. ${rec}`); }); } else { console.log('\nโœ… No issues found - system is healthy'); } } catch (error) { console.error('โŒ Health check failed:', error.message); healthReport.error = error.message; healthReport.overallHealth = { score: 0, grade: 'F', status: 'critical' }; } return healthReport; } // Run health check const healthCheck = await performDelegationHealthCheck(); ``` These comprehensive examples demonstrate the power and flexibility of the Claude Code Subagents Orchestrator for complex, real-world development scenarios. The examples show how to: 1. **Build complete applications** with multiple specialist agents working in coordination 2. **Handle complex migrations** with proper planning and risk mitigation 3. **Optimize system performance** across all layers of the stack 4. **Implement robust error handling** and recovery strategies 5. **Monitor system health** and performance in real-time Each example includes detailed error handling, validation, and monitoring to ensure reliable execution in production environments.