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

618 lines (527 loc) 20.8 kB
/** * Frontend Service Manager * * Orchestrates the refactored frontend architecture, managing the transition * from legacy components to the new active agent system. */ import { TaskEngineFrontendService } from './task-engine-frontend-service.js'; import { legacyCompatibilityLayer, COMPATIBILITY_MODES } from './legacy-compatibility-layer.js'; import { activeAgentDetector } from './active-agent-detector.js'; import { logger } from '../utils/logger-utils.js'; /** * Service Manager States */ export const MANAGER_STATES = { INITIALIZING: 'initializing', READY: 'ready', MIGRATING: 'migrating', ERROR: 'error', SHUTDOWN: 'shutdown' }; /** * Migration Phases */ export const MIGRATION_PHASES = { ASSESSMENT: 'assessment', // Assess current environment and capabilities PREPARATION: 'preparation', // Prepare new architecture components TRANSITION: 'transition', // Gradual transition to new architecture COMPLETION: 'completion', // Complete migration to new architecture VALIDATION: 'validation' // Validate migration success }; /** * Frontend Service Manager Class * * Manages the overall frontend architecture, coordinating between new and legacy * components during the migration process. */ export class FrontendServiceManager { constructor(options = {}) { this.options = { enableLogging: options.enableLogging ?? true, compatibilityMode: options.compatibilityMode ?? COMPATIBILITY_MODES.HYBRID, migrationPhase: options.migrationPhase ?? MIGRATION_PHASES.ASSESSMENT, autoMigrate: options.autoMigrate ?? true, projectRoot: options.projectRoot, sessionTimeout: options.sessionTimeout ?? 3600000, ...options }; this.state = MANAGER_STATES.INITIALIZING; this.migrationPhase = this.options.migrationPhase; this.frontendService = null; this.session = null; this.projectContext = null; this.managementStats = { startTime: Date.now(), operationsHandled: 0, newArchitectureOperations: 0, legacyFallbackOperations: 0, migrationEvents: [], currentPhase: this.migrationPhase }; this.eventHandlers = new Map(); this.migrationCallbacks = new Map(); } /** * Initialize the frontend service manager * @param {Object} session - MCP session object * @param {Object} projectContext - Project context * @returns {Promise<Object>} Initialization result */ async initialize(session = null, projectContext = null) { try { if (this.options.enableLogging) { logger.info('Initializing Frontend Service Manager', { compatibilityMode: this.options.compatibilityMode, migrationPhase: this.migrationPhase }); } this.state = MANAGER_STATES.INITIALIZING; this.session = session; this.projectContext = projectContext; // Initialize the new frontend service this.frontendService = new TaskEngineFrontendService({ enableLogging: this.options.enableLogging, projectRoot: this.options.projectRoot, autoInitialize: false // We'll initialize it manually }); const serviceInitResult = await this.frontendService.initialize(session, projectContext); if (!serviceInitResult.success) { throw new Error(`Frontend service initialization failed: ${serviceInitResult.error}`); } // Initialize legacy compatibility layer await legacyCompatibilityLayer.initializeLegacyProviders(); // Set compatibility mode legacyCompatibilityLayer.setCompatibilityMode(this.options.compatibilityMode); // Perform migration assessment if auto-migrate is enabled if (this.options.autoMigrate) { await this.performMigrationAssessment(); } this.state = MANAGER_STATES.READY; const initResult = { success: true, state: this.state, migrationPhase: this.migrationPhase, compatibilityMode: this.options.compatibilityMode, serviceInitResult, migrationAssessment: this.migrationAssessment }; if (this.options.enableLogging) { logger.info('Frontend Service Manager initialized successfully', { state: this.state, migrationPhase: this.migrationPhase, agentDetected: serviceInitResult.agentDetection?.result }); } this.emitEvent('initialized', initResult); return initResult; } catch (error) { this.state = MANAGER_STATES.ERROR; if (this.options.enableLogging) { logger.error('Frontend Service Manager initialization failed:', error.message); } const errorResult = { success: false, error: error.message, state: this.state }; this.emitEvent('initialization_failed', errorResult); return errorResult; } } /** * Perform migration assessment * @returns {Promise<Object>} Assessment result */ async performMigrationAssessment() { if (this.options.enableLogging) { logger.info('Performing migration assessment...'); } try { // Assess active agent capabilities const agentDetection = await activeAgentDetector.detectActiveAgent( this.session, { assessmentMode: true } ); // Assess legacy component availability const legacyAssessment = { aiProviders: legacyCompatibilityLayer.isLegacyComponentAvailable('ai_providers'), bridgeServer: legacyCompatibilityLayer.isLegacyComponentAvailable('bridge_server') }; // Determine recommended migration phase const recommendedPhase = this.determineRecommendedMigrationPhase( agentDetection, legacyAssessment ); this.migrationAssessment = { timestamp: Date.now(), agentDetection, legacyAssessment, recommendedPhase, currentPhase: this.migrationPhase, readinessScore: this.calculateReadinessScore(agentDetection, legacyAssessment) }; // Auto-advance migration phase if appropriate if (this.options.autoMigrate && recommendedPhase !== this.migrationPhase) { await this.advanceMigrationPhase(recommendedPhase); } if (this.options.enableLogging) { logger.info('Migration assessment completed', { readinessScore: this.migrationAssessment.readinessScore, recommendedPhase, currentPhase: this.migrationPhase }); } this.emitEvent('assessment_completed', this.migrationAssessment); return this.migrationAssessment; } catch (error) { if (this.options.enableLogging) { logger.error('Migration assessment failed:', error.message); } throw error; } } /** * Determine recommended migration phase based on assessment * @param {Object} agentDetection - Agent detection results * @param {Object} legacyAssessment - Legacy component assessment * @returns {string} Recommended migration phase */ determineRecommendedMigrationPhase(agentDetection, legacyAssessment) { // High confidence active agent detected if (agentDetection.success && agentDetection.confidence > 0.9) { return MIGRATION_PHASES.COMPLETION; } // Medium confidence active agent detected if (agentDetection.success && agentDetection.confidence > 0.7) { return MIGRATION_PHASES.TRANSITION; } // Active agent detected but low confidence if (agentDetection.success && agentDetection.confidence > 0.5) { return MIGRATION_PHASES.PREPARATION; } // No active agent or very low confidence return MIGRATION_PHASES.ASSESSMENT; } /** * Calculate migration readiness score * @param {Object} agentDetection - Agent detection results * @param {Object} legacyAssessment - Legacy assessment * @returns {number} Readiness score (0-100) */ calculateReadinessScore(agentDetection, legacyAssessment) { let score = 0; // Active agent detection contributes 60% of score if (agentDetection.success) { score += agentDetection.confidence * 60; } // Legacy fallback availability contributes 20% of score if (legacyAssessment.aiProviders) { score += 20; } // System stability contributes 20% of score const systemStability = this.assessSystemStability(); score += systemStability * 20; return Math.round(score); } /** * Assess system stability * @returns {number} Stability score (0-1) */ assessSystemStability() { // Basic stability assessment based on service state and error rates if (this.state === MANAGER_STATES.READY) { return 1.0; } else if (this.state === MANAGER_STATES.MIGRATING) { return 0.8; } else if (this.state === MANAGER_STATES.ERROR) { return 0.3; } return 0.5; } /** * Advance to a new migration phase * @param {string} newPhase - New migration phase * @returns {Promise<Object>} Migration result */ async advanceMigrationPhase(newPhase) { if (!Object.values(MIGRATION_PHASES).includes(newPhase)) { throw new Error(`Invalid migration phase: ${newPhase}`); } const previousPhase = this.migrationPhase; this.state = MANAGER_STATES.MIGRATING; try { if (this.options.enableLogging) { logger.info(`Advancing migration phase: ${previousPhase} → ${newPhase}`); } // Execute phase-specific migration logic await this.executeMigrationPhase(newPhase); this.migrationPhase = newPhase; this.managementStats.currentPhase = newPhase; this.managementStats.migrationEvents.push({ timestamp: Date.now(), from: previousPhase, to: newPhase, success: true }); // Update compatibility mode based on phase const newCompatibilityMode = this.getCompatibilityModeForPhase(newPhase); legacyCompatibilityLayer.setCompatibilityMode(newCompatibilityMode); this.options.compatibilityMode = newCompatibilityMode; this.state = MANAGER_STATES.READY; const migrationResult = { success: true, previousPhase, newPhase, compatibilityMode: newCompatibilityMode, timestamp: Date.now() }; if (this.options.enableLogging) { logger.info(`Migration phase advanced successfully to: ${newPhase}`); } this.emitEvent('migration_phase_advanced', migrationResult); return migrationResult; } catch (error) { this.state = MANAGER_STATES.ERROR; this.managementStats.migrationEvents.push({ timestamp: Date.now(), from: previousPhase, to: newPhase, success: false, error: error.message }); if (this.options.enableLogging) { logger.error(`Migration phase advancement failed:`, error.message); } throw error; } } /** * Execute migration logic for specific phase * @param {string} phase - Migration phase to execute */ async executeMigrationPhase(phase) { switch (phase) { case MIGRATION_PHASES.ASSESSMENT: // Already performed in initialization break; case MIGRATION_PHASES.PREPARATION: // Prepare new architecture components await this.prepareNewArchitecture(); break; case MIGRATION_PHASES.TRANSITION: // Start gradual transition await this.startGradualTransition(); break; case MIGRATION_PHASES.COMPLETION: // Complete migration to new architecture await this.completeMigration(); break; case MIGRATION_PHASES.VALIDATION: // Validate migration success await this.validateMigration(); break; default: throw new Error(`Unknown migration phase: ${phase}`); } } /** * Get compatibility mode for migration phase * @param {string} phase - Migration phase * @returns {string} Compatibility mode */ getCompatibilityModeForPhase(phase) { switch (phase) { case MIGRATION_PHASES.ASSESSMENT: return COMPATIBILITY_MODES.HYBRID; case MIGRATION_PHASES.PREPARATION: return COMPATIBILITY_MODES.HYBRID; case MIGRATION_PHASES.TRANSITION: return COMPATIBILITY_MODES.MIGRATION; case MIGRATION_PHASES.COMPLETION: return COMPATIBILITY_MODES.FULL_NEW; case MIGRATION_PHASES.VALIDATION: return COMPATIBILITY_MODES.FULL_NEW; default: return COMPATIBILITY_MODES.HYBRID; } } /** * Prepare new architecture components */ async prepareNewArchitecture() { if (this.options.enableLogging) { logger.debug('Preparing new architecture components...'); } // Ensure frontend service is fully initialized if (this.frontendService.state !== 'ready') { await this.frontendService.initialize(this.session, this.projectContext); } // Test MCP communication const mcpTest = await this.frontendService.testMCPConnection(); if (!mcpTest) { throw new Error('MCP connection test failed during preparation'); } } /** * Start gradual transition to new architecture */ async startGradualTransition() { if (this.options.enableLogging) { logger.debug('Starting gradual transition to new architecture...'); } // Increase confidence threshold for using new architecture legacyCompatibilityLayer.options.migrationThreshold = 0.6; } /** * Complete migration to new architecture */ async completeMigration() { if (this.options.enableLogging) { logger.debug('Completing migration to new architecture...'); } // Set very low threshold to prefer new architecture legacyCompatibilityLayer.options.migrationThreshold = 0.3; } /** * Validate migration success */ async validateMigration() { if (this.options.enableLogging) { logger.debug('Validating migration success...'); } // Test key operations with new architecture const testOperations = [ { type: 'GET_TASKS', data: { projectRoot: this.options.projectRoot } }, { type: 'CREATE_TASK', data: { projectRoot: this.options.projectRoot, title: 'Migration Validation Test', description: 'Test task to validate migration success' }} ]; for (const operation of testOperations) { try { await this.frontendService.executeOperation( operation.type, operation.data, { validationTest: true } ); } catch (error) { throw new Error(`Migration validation failed for ${operation.type}: ${error.message}`); } } } /** * Handle operation through the service manager * @param {string} operationType - Operation type * @param {Object} operationData - Operation data * @param {Object} options - Operation options * @returns {Promise<Object>} Operation result */ async handleOperation(operationType, operationData, options = {}) { this.managementStats.operationsHandled++; try { // Route through compatibility layer const result = await legacyCompatibilityLayer.routeOperation( operationType, operationData, this.session, { ...options, serviceManager: true, migrationPhase: this.migrationPhase } ); // Update statistics if (result.compatibilityInfo?.architecture === 'new') { this.managementStats.newArchitectureOperations++; } else { this.managementStats.legacyFallbackOperations++; } return result; } catch (error) { if (this.options.enableLogging) { logger.error('Service manager operation failed:', error.message); } throw error; } } /** * Register event handler * @param {string} event - Event name * @param {Function} handler - Event handler function */ on(event, handler) { if (!this.eventHandlers.has(event)) { this.eventHandlers.set(event, []); } this.eventHandlers.get(event).push(handler); } /** * Emit event to registered handlers * @param {string} event - Event name * @param {Object} data - Event data */ emitEvent(event, data) { const handlers = this.eventHandlers.get(event) || []; handlers.forEach(handler => { try { handler(data); } catch (error) { if (this.options.enableLogging) { logger.error(`Event handler error for ${event}:`, error.message); } } }); } /** * Get comprehensive service manager status * @returns {Object} Service manager status */ getStatus() { return { state: this.state, migrationPhase: this.migrationPhase, compatibilityMode: this.options.compatibilityMode, stats: { ...this.managementStats }, frontendServiceStatus: this.frontendService?.getStatus(), migrationStats: legacyCompatibilityLayer.getMigrationStats(), migrationAssessment: this.migrationAssessment, uptime: Date.now() - this.managementStats.startTime }; } /** * Shutdown the service manager gracefully */ async shutdown() { if (this.options.enableLogging) { logger.info('Shutting down Frontend Service Manager...'); } this.state = MANAGER_STATES.SHUTDOWN; if (this.frontendService) { await this.frontendService.shutdown(); } this.emitEvent('shutdown', { timestamp: Date.now() }); if (this.options.enableLogging) { logger.info('Frontend Service Manager shutdown complete'); } } } /** * Default service manager instance */ export const frontendServiceManager = new FrontendServiceManager(); /** * Convenience functions for common operations */ export async function initializeManager(session, projectContext, options = {}) { return frontendServiceManager.initialize(session, projectContext); } export async function handleOperation(operationType, operationData, options = {}) { return frontendServiceManager.handleOperation(operationType, operationData, options); } export async function getManagerStatus() { return frontendServiceManager.getStatus(); } export async function advanceMigration(newPhase) { return frontendServiceManager.advanceMigrationPhase(newPhase); }