UNPKG

shipdeck

Version:

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

572 lines (506 loc) • 19.1 kB
#!/usr/bin/env node /** * Example Usage of DAG-Based Workflow Engine * Demonstrates various workflow patterns and use cases */ const { ShipdeckWorkflowEngine, WorkflowTemplates } = require('./index'); async function runExamples() { console.log('šŸš€ DAG Workflow Engine Examples\n'); // Initialize the workflow engine const engine = new ShipdeckWorkflowEngine({ stateDir: '.example-workflows', maxConcurrentWorkflows: 3, progressTracking: true }); // Setup progress monitoring engine.progressManager.on('progress:update', (data) => { console.log(`šŸ“Š Progress Update: ${data.workflowId} - ${data.overallProgress}% complete`); }); engine.progressManager.on('workflow:completed', (data) => { console.log(`āœ… Workflow Complete: ${data.workflowId} in ${Math.round(data.duration/1000)}s`); }); try { // Example 1: Quick MVP Generation await example1_QuickMVP(engine); // Example 2: Custom Workflow Creation await example2_CustomWorkflow(engine); // Example 3: Template Customization await example3_TemplateCustomization(engine); // Example 4: API-First Backend await example4_APIBackend(engine); // Example 5: Parallel Development await example5_ParallelDevelopment(engine); // Example 6: Error Recovery await example6_ErrorRecovery(engine); // Example 7: Workflow Monitoring await example7_WorkflowMonitoring(engine); // Show final metrics const metrics = await engine.getMetrics(); console.log('\nšŸ“ˆ Final Metrics:', JSON.stringify(metrics, null, 2)); } catch (error) { console.error('āŒ Example failed:', error.message); } finally { await engine.shutdown(); } } /** * Example 1: Quick MVP Generation * Generate a complete SaaS MVP in under 48 hours */ async function example1_QuickMVP(engine) { console.log('\nšŸŽÆ Example 1: Quick MVP Generation'); console.log('================================'); console.log('šŸ“‹ Generating full-stack SaaS MVP...'); // This would normally take 2-4 hours with real agents // For demo, we'll use a minimal version const mvpConfig = { name: 'InnovateSaaS', stack: 'Next.js 14, TypeScript, Supabase, Stripe', features: ['auth', 'dashboard', 'payments', 'admin'], maxConcurrency: 3 // Limit for demo }; try { // Create a simplified version for demo const workflowInfo = engine.createFromTemplate('fullstack-saas-mvp', { context: mvpConfig, // Use only first few nodes for demo nodes: [ { id: 'project-planning' }, { id: 'auth-system' }, { id: 'ui-components' } ] }); console.log(`āœ… MVP Workflow Created: ${workflowInfo.workflowId}`); console.log(`šŸ“Š Nodes: ${workflowInfo.nodeCount}`); console.log(`ā±ļø Estimated Duration: ${Math.round(workflowInfo.estimatedDuration/1000/60)} minutes`); // For real execution, uncomment: // const result = await engine.executeWorkflow(workflowInfo.workflowId); // console.log('šŸŽ‰ MVP Generated Successfully!'); } catch (error) { console.error('āŒ MVP Generation failed:', error.message); } } /** * Example 2: Custom Workflow Creation * Build a workflow from scratch for specific requirements */ async function example2_CustomWorkflow(engine) { console.log('\nšŸ”§ Example 2: Custom Workflow Creation'); console.log('===================================='); const customWorkflow = { name: 'Custom E-commerce API', description: 'Specialized e-commerce backend with inventory management', maxConcurrency: 4, timeout: 7200000, // 2 hours context: { projectName: 'ShopAPI', database: 'PostgreSQL', payment: 'Stripe' }, nodes: [ { id: 'architecture-design', name: 'System Architecture', agent: 'backend-architect', prompt: `Design a scalable e-commerce API architecture for {{projectName}}: 1. Database schema for products, orders, users 2. API endpoint structure 3. Payment integration strategy 4. Inventory management system 5. Security considerations`, outputs: ['architecture_doc'], timeout: 600000 }, { id: 'database-schema', name: 'Database Implementation', agent: 'backend-architect', dependencies: ['architecture-design'], prompt: `Create {{database}} database schema based on architecture: 1. User and authentication tables 2. Product catalog with variants 3. Order and payment tracking 4. Inventory management tables 5. Audit trails and logging`, inputs: ['architecture_doc'], outputs: ['db_schema'], timeout: 900000 }, { id: 'api-endpoints', name: 'REST API Development', agent: 'backend-architect', dependencies: ['database-schema'], prompt: `Implement RESTful API endpoints: 1. Authentication and user management 2. Product catalog operations 3. Shopping cart functionality 4. Order processing 5. {{payment}} payment integration 6. Admin inventory management`, inputs: ['db_schema'], outputs: ['api_code'], timeout: 1800000 }, { id: 'testing-suite', name: 'Comprehensive Testing', agent: 'test-writer-fixer', dependencies: ['api-endpoints'], prompt: `Create complete test suite for e-commerce API: 1. Unit tests for all business logic 2. Integration tests for API endpoints 3. Payment flow testing 4. Load testing for high traffic 5. Security testing for vulnerabilities`, inputs: ['api_code'], outputs: ['test_suite'], timeout: 1200000 } ] }; try { const workflowInfo = engine.createCustomWorkflow(customWorkflow); console.log(`āœ… Custom Workflow Created: ${workflowInfo.workflowId}`); console.log(`šŸ“Š Nodes: ${workflowInfo.nodeCount}`); // Show workflow structure const status = await engine.getWorkflowStatus(workflowInfo.workflowId); console.log('šŸ“‹ Workflow Structure:'); if (status && status.nodes) { Object.values(status.nodes).forEach((node, i) => { console.log(` ${i + 1}. ${node.name} (${node.agent})`); }); } } catch (error) { console.error('āŒ Custom workflow creation failed:', error.message); } } /** * Example 3: Template Customization * Show how to customize existing templates for specific needs */ async function example3_TemplateCustomization(engine) { console.log('\nšŸŽØ Example 3: Template Customization'); console.log('==================================='); // Show available templates const templates = engine.getAvailableTemplates(); console.log('šŸ“š Available Templates:'); templates.forEach(template => { console.log(` • ${template.name}: ${template.nodeCount} nodes`); }); // Customize the API-first backend template const customization = { context: { projectName: 'WeatherAPI', techStack: 'Node.js, Express, MongoDB, Redis', features: ['weather-data', 'forecasting', 'alerts', 'analytics'], apiVersion: 'v2' }, maxConcurrency: 2, timeout: 5400000, // 1.5 hours nodes: [ // Customize specific nodes { id: 'api-architecture', prompt: `Design weather data API architecture: 1. Real-time weather data ingestion 2. Forecasting algorithm integration 3. User alert system 4. Historical data analytics 5. Rate limiting for public API 6. Caching strategy with Redis` } ] }; try { const workflowInfo = engine.createFromTemplate('api-first-backend', customization); console.log(`āœ… Customized Template Created: ${workflowInfo.workflowId}`); console.log(`šŸŽÆ Project: ${customization.context.projectName}`); console.log(`āš™ļø Tech Stack: ${customization.context.techStack}`); // Get template metrics const templateInfo = engine.getTemplateInfo('api-first-backend'); console.log('šŸ“Š Template Metrics:'); console.log(` • Parallelization Ratio: ${templateInfo.metrics.parallelizationRatio.toFixed(2)}`); console.log(` • Max Dependency Depth: ${templateInfo.metrics.maxDependencyDepth}`); } catch (error) { console.error('āŒ Template customization failed:', error.message); } } /** * Example 4: API-First Backend Development * Demonstrate API-focused workflow */ async function example4_APIBackend(engine) { console.log('\nšŸ”Œ Example 4: API-First Backend'); console.log('=============================='); const apiConfig = { context: { projectName: 'TaskManagerAPI', database: 'PostgreSQL', framework: 'Express.js', auth: 'JWT', features: ['tasks', 'projects', 'teams', 'notifications'] } }; try { const workflowInfo = engine.createFromTemplate('api-first-backend', apiConfig); console.log(`šŸš€ API Backend Workflow: ${workflowInfo.workflowId}`); // Show estimated timeline const hours = Math.round(workflowInfo.estimatedDuration / 1000 / 60 / 60); console.log(`ā±ļø Estimated Completion: ${hours} hours`); console.log('šŸ—ļø Workflow will create:'); console.log(' • Complete PostgreSQL schema'); console.log(' • JWT authentication system'); console.log(' • RESTful API endpoints'); console.log(' • Comprehensive test suite'); console.log(' • Docker deployment setup'); } catch (error) { console.error('āŒ API backend setup failed:', error.message); } } /** * Example 5: Parallel Development Workflow * Show how multiple teams can work in parallel */ async function example5_ParallelDevelopment(engine) { console.log('\n⚔ Example 5: Parallel Development'); console.log('================================='); const parallelWorkflow = { name: 'Multi-Team Parallel Development', description: 'Frontend and Backend teams working in parallel', maxConcurrency: 6, nodes: [ // Shared planning phase { id: 'project-kickoff', name: 'Project Planning & Architecture', agent: 'backend-architect', prompt: 'Define project architecture, API contracts, and team coordination', outputs: ['api_spec', 'ui_mockups'] }, // Backend track (parallel) { id: 'backend-setup', name: 'Backend Infrastructure', agent: 'backend-architect', dependencies: ['project-kickoff'], prompt: 'Setup database, authentication, and core API structure', inputs: ['api_spec'], outputs: ['backend_foundation'] }, { id: 'api-implementation', name: 'API Endpoints', agent: 'backend-architect', dependencies: ['backend-setup'], prompt: 'Implement all API endpoints according to specification', inputs: ['backend_foundation'], outputs: ['api_endpoints'] }, // Frontend track (parallel) { id: 'frontend-setup', name: 'Frontend Foundation', agent: 'frontend-developer', dependencies: ['project-kickoff'], prompt: 'Setup React app, routing, and component structure', inputs: ['ui_mockups'], outputs: ['frontend_foundation'] }, { id: 'ui-components', name: 'UI Components', agent: 'frontend-developer', dependencies: ['frontend-setup'], prompt: 'Build reusable UI components and pages', inputs: ['frontend_foundation'], outputs: ['ui_components'] }, // Testing track (parallel) { id: 'backend-tests', name: 'Backend Testing', agent: 'test-writer-fixer', dependencies: ['api-implementation'], prompt: 'Create comprehensive API tests', inputs: ['api_endpoints'] }, { id: 'frontend-tests', name: 'Frontend Testing', agent: 'test-writer-fixer', dependencies: ['ui-components'], prompt: 'Create component and integration tests', inputs: ['ui_components'] }, // Integration phase { id: 'integration', name: 'System Integration', agent: 'backend-architect', dependencies: ['backend-tests', 'frontend-tests'], prompt: 'Integrate frontend with backend, deploy to staging' } ] }; try { const workflowInfo = engine.createCustomWorkflow(parallelWorkflow); console.log(`⚔ Parallel Workflow Created: ${workflowInfo.workflowId}`); console.log('\nšŸ—ļø Parallel Execution Plan:'); console.log(' Phase 1: Project Planning (1 node)'); console.log(' Phase 2: Parallel Development (4 nodes)'); console.log(' • Backend: Infrastructure → API'); console.log(' • Frontend: Foundation → Components'); console.log(' Phase 3: Parallel Testing (2 nodes)'); console.log(' Phase 4: Integration (1 node)'); console.log('\nšŸ“Š Parallelization Benefits:'); console.log(' • Sequential Time: ~8 hours'); console.log(' • Parallel Time: ~3 hours'); console.log(' • Time Savings: 62%'); } catch (error) { console.error('āŒ Parallel workflow setup failed:', error.message); } } /** * Example 6: Error Recovery and Retry * Demonstrate workflow resilience */ async function example6_ErrorRecovery(engine) { console.log('\nšŸ”„ Example 6: Error Recovery'); console.log('==========================='); const resilientWorkflow = { name: 'Resilient Deployment Workflow', description: 'Production deployment with automatic error recovery', nodes: [ { id: 'pre-deploy-tests', name: 'Pre-deployment Testing', agent: 'test-writer-fixer', prompt: 'Run comprehensive test suite before deployment', retry: { maxAttempts: 3, backoffMs: 5000 } }, { id: 'staging-deploy', name: 'Deploy to Staging', agent: 'devops-automator', dependencies: ['pre-deploy-tests'], prompt: 'Deploy application to staging environment with health checks', retry: { maxAttempts: 2, backoffMs: 10000 } }, { id: 'staging-validation', name: 'Staging Validation', agent: 'test-writer-fixer', dependencies: ['staging-deploy'], prompt: 'Validate staging deployment with smoke tests', retry: { maxAttempts: 3, backoffMs: 2000 } }, { id: 'production-deploy', name: 'Production Deployment', agent: 'devops-automator', dependencies: ['staging-validation'], prompt: 'Deploy to production with blue-green deployment strategy', retry: { maxAttempts: 1, backoffMs: 0 } // No retry for prod deploy } ] }; try { const workflowInfo = engine.createCustomWorkflow(resilientWorkflow); console.log(`šŸ”„ Resilient Workflow Created: ${workflowInfo.workflowId}`); console.log('\nšŸ›”ļø Error Recovery Features:'); console.log(' • Automatic retry with backoff'); console.log(' • Configurable retry policies per node'); console.log(' • State persistence for recovery'); console.log(' • Detailed error tracking'); console.log('\n🚨 Recovery Scenarios:'); console.log(' • Network timeouts: Auto-retry with backoff'); console.log(' • Transient failures: Multiple retry attempts'); console.log(' • Critical failures: Immediate stop and alert'); console.log(' • Workflow crash: Resume from last checkpoint'); } catch (error) { console.error('āŒ Resilient workflow setup failed:', error.message); } } /** * Example 7: Workflow Monitoring and Analytics * Show real-time monitoring capabilities */ async function example7_WorkflowMonitoring(engine) { console.log('\nšŸ“Š Example 7: Workflow Monitoring'); console.log('================================='); // Create a workflow for monitoring demo const monitoredWorkflow = { name: 'Monitored Development Workflow', nodes: [ { id: 'analysis', agent: 'backend-architect', prompt: 'Analyze requirements' }, { id: 'design', agent: 'frontend-developer', prompt: 'Create design system', dependencies: ['analysis'] }, { id: 'implementation', agent: 'backend-architect', prompt: 'Implement features', dependencies: ['design'] } ] }; try { const workflowInfo = engine.createCustomWorkflow(monitoredWorkflow); console.log(`šŸ“Š Monitored Workflow: ${workflowInfo.workflowId}`); // Show monitoring capabilities console.log('\nšŸ” Available Monitoring Features:'); console.log(' • Real-time progress updates'); console.log(' • Node execution metrics'); console.log(' • Cost and token tracking'); console.log(' • Performance analytics'); console.log(' • Error rate monitoring'); console.log(' • Parallelization efficiency'); // Demo progress tracking console.log('\nšŸ“ˆ Sample Progress Metrics:'); const demoMetrics = { overallProgress: 75, nodesCompleted: 2, totalNodes: 3, runningNodes: 1, estimatedCompletion: new Date(Date.now() + 15 * 60 * 1000), throughput: 0.8, // nodes per minute cost: 0.15, parallelizationEfficiency: 85 }; console.log(` • Progress: ${demoMetrics.overallProgress}%`); console.log(` • Completed: ${demoMetrics.nodesCompleted}/${demoMetrics.totalNodes} nodes`); console.log(` • Running: ${demoMetrics.runningNodes} nodes`); console.log(` • ETA: ${demoMetrics.estimatedCompletion.toLocaleTimeString()}`); console.log(` • Throughput: ${demoMetrics.throughput} nodes/min`); console.log(` • Cost: $${demoMetrics.cost}`); console.log(` • Efficiency: ${demoMetrics.parallelizationEfficiency}%`); // Show available alerts console.log('\n🚨 Available Alerts:'); console.log(' • Node failure notifications'); console.log(' • Performance degradation warnings'); console.log(' • Cost threshold alerts'); console.log(' • Completion notifications'); console.log(' • SLA breach warnings'); } catch (error) { console.error('āŒ Monitoring setup failed:', error.message); } } // Helper function to simulate workflow execution progress function simulateProgress(workflowId, engine, duration = 5000) { return new Promise((resolve) => { let progress = 0; const interval = setInterval(() => { progress += Math.random() * 20; if (progress >= 100) { progress = 100; clearInterval(interval); console.log(`āœ… ${workflowId} completed!`); resolve(); } else { console.log(`šŸ“ˆ ${workflowId}: ${Math.round(progress)}% complete`); } }, duration / 10); }); } // Run examples if this file is executed directly if (require.main === module) { runExamples().catch(error => { console.error('āŒ Examples failed:', error); process.exit(1); }); } module.exports = { runExamples };