UNPKG

shipdeck

Version:

Ship MVPs in 48 hours. Fix bugs in 30 seconds. The command deck for developers who ship.

463 lines (415 loc) 14.4 kB
/** * Workflow Integration Example * * Demonstrates how to use the workflow integration module to orchestrate * multiple agents in complex workflows with quality gates, checkpoints, * and parallel execution capabilities. */ const { WorkflowIntegration, createWorkflowIntegration, convertAgentTasksToWorkflow } = require('./workflow-integration'); /** * Example: Creating a comprehensive development workflow */ async function developmentWorkflowExample() { console.log('🚀 Development Workflow Example'); // Initialize workflow integration with all features enabled const integration = createWorkflowIntegration({ enableQualityGates: true, enableCheckpoints: true, enableParallelExecution: true, maxConcurrency: 3, autoRetry: true, autoRollback: true }); await integration.initialize(); // Define agent tasks for a complete feature development workflow const agentTasks = [ { id: 'analyze-requirements', agent: 'backend-architect', name: 'Analyze Requirements', description: 'Analyze feature requirements and design system architecture', prompt: 'Analyze the requirements for a user authentication system with OAuth2 support', context: { feature: 'authentication', requirements: ['OAuth2', 'JWT tokens', 'user profiles', 'password reset'] }, timeout: 180000, // 3 minutes checkpoint: true, qualityGates: true }, { id: 'design-api', agent: 'backend-architect', name: 'Design API', description: 'Design RESTful API endpoints for authentication', prompt: 'Design RESTful API endpoints for user authentication with proper security', dependencies: ['analyze-requirements'], context: { endpoints: ['POST /auth/login', 'POST /auth/register', 'GET /auth/profile'] }, timeout: 240000, // 4 minutes checkpoint: true }, { id: 'implement-backend', agent: 'backend-architect', name: 'Implement Backend', description: 'Implement authentication backend with Node.js and Express', prompt: 'Implement secure authentication backend with Express.js, bcrypt, and JWT', dependencies: ['design-api'], retries: 2, timeout: 600000, // 10 minutes checkpoint: true, qualityGates: true }, { id: 'design-ui', agent: 'frontend-developer', name: 'Design UI Components', description: 'Design login and registration UI components', prompt: 'Design responsive login and registration forms with React', dependencies: ['analyze-requirements'], // Can start after requirements parallel: true, // Can run in parallel with backend work context: { framework: 'React', styling: 'Tailwind CSS', components: ['LoginForm', 'RegisterForm', 'PasswordReset'] }, timeout: 300000, // 5 minutes checkpoint: true }, { id: 'implement-frontend', agent: 'frontend-developer', name: 'Implement Frontend', description: 'Implement authentication frontend with React', prompt: 'Implement authentication frontend with React, form validation, and API integration', dependencies: ['design-ui', 'design-api'], timeout: 480000, // 8 minutes checkpoint: true, qualityGates: true }, { id: 'write-tests', agent: 'test-writer-fixer', name: 'Write Comprehensive Tests', description: 'Write unit and integration tests for authentication', prompt: 'Write comprehensive test suite for authentication system', dependencies: ['implement-backend', 'implement-frontend'], context: { testTypes: ['unit', 'integration', 'e2e'], coverage: 85 }, timeout: 360000, // 6 minutes checkpoint: true, qualityGates: true }, { id: 'security-audit', agent: 'backend-architect', name: 'Security Audit', description: 'Perform security audit of authentication system', prompt: 'Perform comprehensive security audit of authentication implementation', dependencies: ['write-tests'], context: { auditAreas: ['input validation', 'SQL injection', 'XSS', 'CSRF', 'JWT security'] }, timeout: 240000, // 4 minutes qualityGates: true }, { id: 'performance-optimization', agent: 'devops-automator', name: 'Performance Optimization', description: 'Optimize authentication system performance', prompt: 'Optimize authentication system for performance and scalability', dependencies: ['security-audit'], context: { optimizations: ['caching', 'database indexing', 'rate limiting', 'connection pooling'] }, timeout: 300000, // 5 minutes checkpoint: true }, { id: 'deployment-prep', agent: 'devops-automator', name: 'Deployment Preparation', description: 'Prepare authentication system for deployment', prompt: 'Prepare deployment configuration and CI/CD pipeline', dependencies: ['performance-optimization'], context: { environment: 'production', platform: 'AWS', services: ['ECS', 'RDS', 'ElastiCache', 'ALB'] }, timeout: 420000, // 7 minutes checkpoint: true, qualityGates: true } ]; // Execute the workflow try { const result = await integration.executeWorkflowWithIntegration({ name: 'Authentication Feature Development', description: 'Complete development workflow for user authentication feature', agentTasks, parallelExecution: true, // Enable parallel execution where possible context: { project: 'MyApp', version: '1.0.0', environment: 'development' } }); console.log('✅ Workflow completed successfully!'); console.log('📊 Results:', JSON.stringify(result, null, 2)); // Get agent statistics const stats = integration.getAgentStatistics(); console.log('📈 Agent Statistics:', stats); return result; } catch (error) { console.error('❌ Workflow failed:', error.message); // Show rollback information if available const checkpoints = await integration.checkpointManager?.listCheckpoints() || []; if (checkpoints.length > 0) { console.log('🔄 Available checkpoints for rollback:', checkpoints.slice(0, 3).map(cp => ({ id: cp.id, description: cp.description })) ); } throw error; } } /** * Example: Parallel agent execution */ async function parallelExecutionExample() { console.log('⚡ Parallel Execution Example'); const integration = createWorkflowIntegration({ enableParallelExecution: true, maxConcurrency: 5 }); await integration.initialize(); // Tasks that can run independently in parallel const parallelTasks = [ { id: 'content-creation', agent: 'content-creator', name: 'Create Blog Content', prompt: 'Write a technical blog post about microservices architecture', context: { topic: 'microservices', length: '1500 words' }, parallel: true }, { id: 'social-media', agent: 'tiktok-strategist', name: 'Create Social Content', prompt: 'Create viral TikTok content strategy for tech product launch', context: { product: 'developer tools', audience: 'developers' }, parallel: true }, { id: 'performance-analysis', agent: 'performance-benchmarker', name: 'Performance Analysis', prompt: 'Analyze application performance and suggest optimizations', context: { app: 'web-dashboard', metrics: ['load-time', 'memory', 'cpu'] }, parallel: true }, { id: 'security-scan', agent: 'backend-architect', name: 'Security Scan', prompt: 'Perform security vulnerability assessment', context: { scope: 'authentication-service', frameworks: ['express', 'jwt'] }, parallel: true }, { id: 'ui-enhancement', agent: 'whimsy-injector', name: 'UI Enhancement', prompt: 'Add delightful micro-interactions to user dashboard', context: { component: 'dashboard', interactions: ['hover', 'loading', 'success'] }, parallel: true } ]; try { const result = await integration.executeWorkflowWithIntegration({ name: 'Parallel Content & Analysis Workflow', agentTasks: parallelTasks, parallelExecution: true, context: { mode: 'parallel-demo', maxConcurrency: 5 } }); console.log('✅ Parallel execution completed!'); console.log('📊 Execution Statistics:'); console.log(`- Total tasks: ${result.statistics?.totalTasks || parallelTasks.length}`); console.log(`- Success count: ${result.statistics?.successCount || 0}`); console.log(`- Duration: ${result.statistics?.duration || 0}ms`); console.log(`- Parallel groups: ${result.statistics?.parallelGroups || 'N/A'}`); return result; } catch (error) { console.error('❌ Parallel execution failed:', error.message); throw error; } } /** * Example: Quality gates and checkpoints */ async function qualityGatesExample() { console.log('🛡️ Quality Gates & Checkpoints Example'); const integration = createWorkflowIntegration({ enableQualityGates: true, enableCheckpoints: true, autoRollback: true }); await integration.initialize(); // Create initial checkpoint const checkpoint = await integration.createCheckpoint({ type: 'manual', description: 'Pre-development checkpoint', tags: ['stable', 'baseline'] }); console.log(`📝 Created checkpoint: ${checkpoint.checkpoint?.id}`); const criticalTasks = [ { id: 'database-migration', agent: 'backend-architect', name: 'Database Migration', prompt: 'Create and execute database migration for user profiles schema', context: { database: 'postgresql', tables: ['users', 'profiles', 'settings'], migration: 'add-profile-fields' }, qualityGates: true, // Enable quality gates checkpoint: true, // Create checkpoint after completion timeout: 300000 }, { id: 'api-integration', agent: 'backend-architect', name: 'API Integration', prompt: 'Integrate third-party payment API with proper error handling', dependencies: ['database-migration'], context: { provider: 'stripe', endpoints: ['charges', 'customers', 'subscriptions'] }, qualityGates: true, checkpoint: true, timeout: 240000 } ]; try { const result = await integration.executeWorkflowWithIntegration({ name: 'Critical System Updates', agentTasks: criticalTasks, context: { environment: 'staging', criticalPath: true } }); console.log('✅ Critical updates completed successfully!'); // Demonstrate quality gate artifact validation if (result.success) { const artifact = { type: 'database-schema', content: 'CREATE TABLE profiles...', files: ['migration.sql', 'rollback.sql'] }; const qualityResult = await integration.applyQualityGates(artifact, { type: 'database-migration', environment: 'staging' }); console.log('🛡️ Quality Gates Result:', qualityResult.success ? 'PASSED' : 'FAILED'); } return result; } catch (error) { console.error('❌ Critical workflow failed:', error.message); // Demonstrate rollback if (checkpoint.success) { console.log('🔄 Attempting rollback...'); const rollbackResult = await integration.rollbackToCheckpoint( checkpoint.checkpoint.id, { hard: false, // Soft rollback preserving history runHooks: true } ); if (rollbackResult.success) { console.log('✅ Rollback completed successfully'); } else { console.error('❌ Rollback failed:', rollbackResult.error); } } throw error; } } /** * Example: Agent task conversion */ function taskConversionExample() { console.log('🔄 Agent Task Conversion Example'); const agentTasks = [ { id: 'feature-analysis', agent: 'backend-architect', prompt: 'Analyze requirements for new feature', dependencies: [], retries: 2 }, { id: 'ui-design', agent: 'ui-designer', prompt: 'Design user interface', dependencies: ['feature-analysis'] } ]; // Convert to workflow nodes const workflowNodes = convertAgentTasksToWorkflow(agentTasks, { nodeIdPrefix: 'demo' }); console.log('📋 Converted workflow nodes:'); workflowNodes.forEach(node => { console.log(`- ${node.id}: ${node.name} (${node.agent})`); console.log(` Dependencies: ${node.dependencies.join(', ') || 'none'}`); console.log(` Timeout: ${node.timeout}ms`); }); return workflowNodes; } // Export examples for use in other modules module.exports = { developmentWorkflowExample, parallelExecutionExample, qualityGatesExample, taskConversionExample }; // If running directly, execute examples if (require.main === module) { async function runExamples() { try { console.log('🎯 Workflow Integration Examples\n'); // Run task conversion example (doesn't require dependencies) console.log('1. Task Conversion Example'); taskConversionExample(); console.log('\n' + '='.repeat(50) + '\n'); // Note about other examples requiring dependencies console.log('2. Other examples require full system dependencies:'); console.log(' - developmentWorkflowExample()'); console.log(' - parallelExecutionExample()'); console.log(' - qualityGatesExample()'); console.log('\n To run these, ensure all dependencies are installed:'); console.log(' npm install @anthropic-ai/sdk'); console.log('\n Then call the individual example functions.'); } catch (error) { console.error('❌ Example execution failed:', error.message); process.exit(1); } } runExamples(); }