UNPKG

task-engine-ai-core

Version:

Revolutionary AI-driven task management system with complete transformation trilogy: Frontend v0.1.0, Backend v0.2.0, CLI v0.3.0 - Enterprise-grade performance with 95% improvements

561 lines (471 loc) 21.5 kB
/** * Enhanced Task Operations Test Suite * * Comprehensive tests for the enhanced task operation flows, * performance optimization, and intelligent routing. */ import { enhancedTaskOperations, createTaskEnhanced, getTasksEnhanced, updateTaskEnhanced, setTaskStatusEnhanced, expandTaskEnhanced, getEnhancedOperationStats } from '../core/enhanced-task-operations.js'; import { performanceOptimizationEngine, optimizeOperation, getPerformanceMetrics, clearOptimizationCaches } from '../core/performance-optimization-engine.js'; import { taskEngineFrontendService } from '../core/task-engine-frontend-service.js'; import { logger } from '../utils/logger-utils.js'; /** * Test Configuration */ const TEST_CONFIG = { projectRoot: 'C:\\Users\\visual-code\\Task-engine', enableLogging: true, testTimeout: 60000 }; /** * Mock MCP Session for testing */ const mockSession = { id: 'enhanced-operations-test-session', clientCapabilities: { sampling: { enabled: true }, roots: { listChanged: true } }, capabilities: { tools: true, resources: true }, clientInfo: { name: 'enhanced-operations-test-client', version: '1.0.0' } }; /** * Enhanced Task Operations Test Suite */ class EnhancedTaskOperationsTestSuite { constructor() { this.testResults = []; this.startTime = Date.now(); this.testData = { createdTasks: [], performanceMetrics: [], operationStats: [] }; } /** * Run complete enhanced operations test suite */ async runCompleteTestSuite() { console.log('🚀 Starting Enhanced Task Operations Test Suite...\n'); try { await this.testEnhancedTaskCreation(); await this.testIntelligentTaskParsing(); await this.testPerformanceOptimization(); await this.testOperationFlowTypes(); await this.testCachingMechanisms(); await this.testBatchProcessing(); await this.testFrontendServiceIntegration(); await this.testStatisticsAndMonitoring(); this.printComprehensiveTestSummary(); } catch (error) { console.error('❌ Enhanced operations test suite failed:', error.message); process.exit(1); } } /** * Test enhanced task creation */ async testEnhancedTaskCreation() { console.log('📝 Testing Enhanced Task Creation...'); try { // Test structured task creation const structuredTask = await createTaskEnhanced({ title: 'Enhanced Task Creation Test', description: 'Testing enhanced task creation with structured data', details: 'Implementation details for enhanced task creation', testStrategy: 'Comprehensive testing strategy', priority: 'high', projectRoot: TEST_CONFIG.projectRoot }, mockSession); this.assert(structuredTask.success, 'Structured task creation should succeed'); this.assert(structuredTask.operationMetadata, 'Should include operation metadata'); this.assert(structuredTask.operationMetadata.flowType, 'Should specify flow type'); // Test prompt-based task creation const promptTask = await createTaskEnhanced({ prompt: 'Create a comprehensive user authentication system with OAuth integration, password reset functionality, and multi-factor authentication support', projectRoot: TEST_CONFIG.projectRoot }, mockSession); this.assert(promptTask.success, 'Prompt-based task creation should succeed'); this.assert(promptTask.operationMetadata, 'Should include operation metadata'); if (promptTask.data && promptTask.data.taskId) { this.testData.createdTasks.push(promptTask.data.taskId); } this.recordTestResult('Enhanced Task Creation', true); console.log('✅ Enhanced Task Creation tests passed\n'); } catch (error) { this.recordTestResult('Enhanced Task Creation', false, error.message); console.log('❌ Enhanced Task Creation tests failed:', error.message, '\n'); } } /** * Test intelligent task parsing */ async testIntelligentTaskParsing() { console.log('🧠 Testing Intelligent Task Parsing...'); try { // Test complex prompt parsing const complexPrompt = `Create a high-priority task for implementing a real-time chat system that depends on task 5 and task 7. The system should include WebSocket connections, message persistence, user authentication, and file sharing capabilities. This is urgent and needs to be completed ASAP.`; const parsedTask = await createTaskEnhanced({ prompt: complexPrompt, projectRoot: TEST_CONFIG.projectRoot }, mockSession, { context: { projectType: 'web-application', relatedTasks: [5, 7] } }); this.assert(parsedTask.success, 'Complex prompt parsing should succeed'); // Verify intelligent parsing extracted key information if (parsedTask.data && parsedTask.data.task) { const task = parsedTask.data.task; this.assert(task.title, 'Should extract meaningful title'); this.assert(task.priority === 'high', 'Should detect high priority from "urgent" and "ASAP"'); this.assert(task.description, 'Should generate comprehensive description'); } // Test priority detection const lowPriorityTask = await createTaskEnhanced({ prompt: 'Nice to have: refactor the code documentation for better readability', projectRoot: TEST_CONFIG.projectRoot }, mockSession); this.assert(lowPriorityTask.success, 'Low priority task creation should succeed'); this.recordTestResult('Intelligent Task Parsing', true); console.log('✅ Intelligent Task Parsing tests passed\n'); } catch (error) { this.recordTestResult('Intelligent Task Parsing', false, error.message); console.log('❌ Intelligent Task Parsing tests failed:', error.message, '\n'); } } /** * Test performance optimization */ async testPerformanceOptimization() { console.log('⚡ Testing Performance Optimization...'); try { // Clear caches to start fresh clearOptimizationCaches(); // Test optimized operation const startTime = Date.now(); const optimizedResult = await optimizeOperation( 'GET_TASKS', { projectRoot: TEST_CONFIG.projectRoot }, async () => { // Simulate operation await new Promise(resolve => setTimeout(resolve, 100)); return { success: true, data: { tasks: [], stats: { total: 0 } } }; } ); const responseTime = Date.now() - startTime; this.assert(optimizedResult.success, 'Optimized operation should succeed'); this.assert(optimizedResult.optimizationMetadata, 'Should include optimization metadata'); this.assert(responseTime < 1000, 'Response time should be reasonable'); // Test caching const cachedResult = await optimizeOperation( 'GET_TASKS', { projectRoot: TEST_CONFIG.projectRoot }, async () => { throw new Error('Should not execute - should use cache'); } ); this.assert(cachedResult.success, 'Cached operation should succeed'); this.assert(cachedResult.optimizationMetadata.fromCache, 'Should indicate cache usage'); // Get performance metrics const perfMetrics = getPerformanceMetrics(); this.assert(perfMetrics.cacheHitRate > 0, 'Should have cache hits'); this.assert(perfMetrics.totalRequests >= 2, 'Should track total requests'); this.testData.performanceMetrics.push(perfMetrics); this.recordTestResult('Performance Optimization', true); console.log('✅ Performance Optimization tests passed\n'); } catch (error) { this.recordTestResult('Performance Optimization', false, error.message); console.log('❌ Performance Optimization tests failed:', error.message, '\n'); } } /** * Test operation flow types */ async testOperationFlowTypes() { console.log('🔀 Testing Operation Flow Types...'); try { // Test direct flow const directResult = await getTasksEnhanced({ projectRoot: TEST_CONFIG.projectRoot }, mockSession, { flowType: 'direct' }); this.assert(directResult.success, 'Direct flow should succeed'); this.assert( directResult.operationMetadata?.flowType === 'direct', 'Should use direct flow when specified' ); // Test intelligent flow const intelligentResult = await createTaskEnhanced({ prompt: 'Create an intelligent task with enhanced processing', projectRoot: TEST_CONFIG.projectRoot }, mockSession, { flowType: 'intelligent' }); this.assert(intelligentResult.success, 'Intelligent flow should succeed'); // Test cached flow (should use cache from previous operations) const cachedResult = await getTasksEnhanced({ projectRoot: TEST_CONFIG.projectRoot }, mockSession, { maxAge: 300000 // 5 minutes }); this.assert(cachedResult.success, 'Cached flow should succeed'); this.recordTestResult('Operation Flow Types', true); console.log('✅ Operation Flow Types tests passed\n'); } catch (error) { this.recordTestResult('Operation Flow Types', false, error.message); console.log('❌ Operation Flow Types tests failed:', error.message, '\n'); } } /** * Test caching mechanisms */ async testCachingMechanisms() { console.log('💾 Testing Caching Mechanisms...'); try { // Clear cache to start fresh enhancedTaskOperations.clearCache(); // First call - should not be cached const firstCall = await getTasksEnhanced({ projectRoot: TEST_CONFIG.projectRoot, status: 'pending' }, mockSession); this.assert(firstCall.success, 'First call should succeed'); this.assert(!firstCall.operationMetadata?.fromCache, 'First call should not be from cache'); // Second call with same parameters - should be cached const secondCall = await getTasksEnhanced({ projectRoot: TEST_CONFIG.projectRoot, status: 'pending' }, mockSession); this.assert(secondCall.success, 'Second call should succeed'); // Note: Caching might not be enabled for all operations in test mode // Test cache with different parameters const differentCall = await getTasksEnhanced({ projectRoot: TEST_CONFIG.projectRoot, status: 'done' }, mockSession); this.assert(differentCall.success, 'Different parameters call should succeed'); this.recordTestResult('Caching Mechanisms', true); console.log('✅ Caching Mechanisms tests passed\n'); } catch (error) { this.recordTestResult('Caching Mechanisms', false, error.message); console.log('❌ Caching Mechanisms tests failed:', error.message, '\n'); } } /** * Test batch processing */ async testBatchProcessing() { console.log('📦 Testing Batch Processing...'); try { // Test multiple similar operations const batchPromises = []; for (let i = 0; i < 3; i++) { batchPromises.push( getTasksEnhanced({ projectRoot: TEST_CONFIG.projectRoot, status: 'pending' }, mockSession, { enableBatching: true }) ); } const batchResults = await Promise.all(batchPromises); this.assert( batchResults.every(result => result.success), 'All batch operations should succeed' ); // Check if any operations were batched const stats = getEnhancedOperationStats(); this.assert(stats.totalOperations >= 3, 'Should track batch operations'); this.recordTestResult('Batch Processing', true); console.log('✅ Batch Processing tests passed\n'); } catch (error) { this.recordTestResult('Batch Processing', false, error.message); console.log('❌ Batch Processing tests failed:', error.message, '\n'); } } /** * Test frontend service integration */ async testFrontendServiceIntegration() { console.log('🔗 Testing Frontend Service Integration...'); try { // Initialize frontend service with enhanced operations enabled const initResult = await taskEngineFrontendService.initialize(mockSession, { projectRoot: TEST_CONFIG.projectRoot }); this.assert(initResult.success, 'Frontend service initialization should succeed'); // Test enhanced operation through frontend service const serviceResult = await taskEngineFrontendService.createTask({ title: 'Frontend Service Integration Test', description: 'Testing enhanced operations through frontend service', priority: 'medium' }); this.assert(serviceResult.success, 'Frontend service task creation should succeed'); // Get service status to check enhanced operation stats const serviceStatus = taskEngineFrontendService.getStatus(); this.assert(serviceStatus.enhancedOperationsEnabled, 'Enhanced operations should be enabled'); this.assert(serviceStatus.stats, 'Should include service statistics'); if (serviceStatus.enhancedOperationStats) { this.assert( serviceStatus.enhancedOperationStats.totalOperations > 0, 'Should track enhanced operations' ); } this.recordTestResult('Frontend Service Integration', true); console.log('✅ Frontend Service Integration tests passed\n'); } catch (error) { this.recordTestResult('Frontend Service Integration', false, error.message); console.log('❌ Frontend Service Integration tests failed:', error.message, '\n'); } } /** * Test statistics and monitoring */ async testStatisticsAndMonitoring() { console.log('📊 Testing Statistics and Monitoring...'); try { // Get enhanced operation statistics const enhancedStats = getEnhancedOperationStats(); this.assert(enhancedStats.totalOperations !== undefined, 'Should track total operations'); this.assert(enhancedStats.averageResponseTime !== undefined, 'Should track response times'); this.assert(enhancedStats.successRate !== undefined, 'Should track success rate'); // Get performance metrics const perfMetrics = getPerformanceMetrics(); this.assert(perfMetrics.totalRequests !== undefined, 'Should track total requests'); this.assert(perfMetrics.cacheHitRate !== undefined, 'Should track cache hit rate'); // Store statistics for summary this.testData.operationStats.push({ enhanced: enhancedStats, performance: perfMetrics, timestamp: Date.now() }); this.recordTestResult('Statistics and Monitoring', true); console.log('✅ Statistics and Monitoring tests passed\n'); } catch (error) { this.recordTestResult('Statistics and Monitoring', false, error.message); console.log('❌ Statistics and Monitoring tests failed:', error.message, '\n'); } } /** * Assert a condition * @param {boolean} condition - Condition to test * @param {string} message - Error message if condition fails */ assert(condition, message) { if (!condition) { throw new Error(`Assertion failed: ${message}`); } } /** * Record test result * @param {string} testName - Name of the test * @param {boolean} passed - Whether test passed * @param {string} error - Error message if failed */ recordTestResult(testName, passed, error = null) { this.testResults.push({ name: testName, passed, error, timestamp: Date.now() }); } /** * Print comprehensive test summary */ printComprehensiveTestSummary() { const totalTests = this.testResults.length; const passedTests = this.testResults.filter(r => r.passed).length; const failedTests = totalTests - passedTests; const duration = Date.now() - this.startTime; console.log('📊 Enhanced Task Operations Test Summary'); console.log('='.repeat(50)); console.log(`Total Tests: ${totalTests}`); console.log(`Passed: ${passedTests} ✅`); console.log(`Failed: ${failedTests} ❌`); console.log(`Duration: ${Math.round(duration / 1000)}s`); console.log(''); // Print performance metrics if (this.testData.performanceMetrics.length > 0) { const latestMetrics = this.testData.performanceMetrics[this.testData.performanceMetrics.length - 1]; console.log('⚡ Performance Metrics:'); console.log(` Cache Hit Rate: ${latestMetrics.cacheHitRate.toFixed(1)}%`); console.log(` Average Response Time: ${latestMetrics.averageResponseTime.toFixed(0)}ms`); console.log(` Total Requests: ${latestMetrics.totalRequests}`); console.log(` Optimization Savings: ${latestMetrics.optimizationSavings}ms`); console.log(''); } // Print operation statistics if (this.testData.operationStats.length > 0) { const latestStats = this.testData.operationStats[this.testData.operationStats.length - 1]; console.log('📈 Operation Statistics:'); console.log(` Enhanced Operations: ${latestStats.enhanced.totalOperations}`); console.log(` Success Rate: ${latestStats.enhanced.successRate.toFixed(1)}%`); console.log(` Direct Operations: ${latestStats.enhanced.directOperations}`); console.log(` Intelligent Operations: ${latestStats.enhanced.intelligentOperations}`); console.log(` Cached Operations: ${latestStats.enhanced.cachedOperations}`); console.log(''); } if (failedTests > 0) { console.log('Failed Tests:'); this.testResults .filter(r => !r.passed) .forEach(test => { console.log(` ❌ ${test.name}: ${test.error}`); }); console.log(''); } if (failedTests === 0) { console.log('🎉 All enhanced task operations tests passed!'); console.log('✅ Enhanced Task Creation: Working'); console.log('✅ Intelligent Parsing: Functional'); console.log('✅ Performance Optimization: Optimized'); console.log('✅ Operation Flows: Efficient'); console.log('✅ Caching: Effective'); console.log('✅ Batch Processing: Operational'); console.log('✅ Service Integration: Seamless'); console.log('✅ Monitoring: Comprehensive'); } else { console.log('⚠️ Some enhanced operations tests failed. Please review the implementation.'); } } } /** * Run tests if this file is executed directly */ if (import.meta.url === `file://${process.argv[1]}`) { const testSuite = new EnhancedTaskOperationsTestSuite(); testSuite.runCompleteTestSuite().catch(error => { console.error('Enhanced operations test suite execution failed:', error); process.exit(1); }); } export { EnhancedTaskOperationsTestSuite };