# Task Engine Frontend Migration Guide

## 🎯 Overview

This guide provides step-by-step instructions for migrating from the legacy AI provider architecture to the new active agent-driven frontend system. The migration is designed to be gradual and safe, with full backward compatibility maintained throughout the process.

## 🏗️ Migration Architecture

### Before: Legacy Architecture
```
User Request → AI Service Layer → Multiple AI Providers → Complex Error Handling → CLI Backend
```

### After: New Architecture
```
User Request → Active Agent Detector → Task Operation Router → MCP Communication Layer → CLI Backend
```

## 📋 Migration Phases

### Phase 1: Assessment 🔍
**Goal**: Evaluate current environment and migration readiness

**Actions**:
- Detect active AI agent capabilities
- Assess legacy component availability
- Calculate migration readiness score
- Determine optimal migration path

**Compatibility Mode**: `HYBRID`
**Duration**: Immediate (automated)

### Phase 2: Preparation 🛠️
**Goal**: Prepare new architecture components

**Actions**:
- Initialize new frontend service
- Test MCP communication layer
- Validate active agent detection
- Prepare fallback mechanisms

**Compatibility Mode**: `HYBRID`
**Duration**: 1-2 minutes

### Phase 3: Transition 🔄
**Goal**: Gradually shift operations to new architecture

**Actions**:
- Lower confidence threshold for new architecture
- Monitor operation success rates
- Collect performance metrics
- Maintain legacy fallbacks

**Compatibility Mode**: `MIGRATION`
**Duration**: Ongoing (based on usage)

### Phase 4: Completion ✅
**Goal**: Complete migration to new architecture

**Actions**:
- Prefer new architecture for all operations
- Minimize legacy provider usage
- Optimize performance settings
- Validate system stability

**Compatibility Mode**: `FULL_NEW`
**Duration**: 5-10 minutes

### Phase 5: Validation 🧪
**Goal**: Validate migration success and system health

**Actions**:
- Test all operation types
- Verify performance improvements
- Confirm error handling
- Generate migration report

**Compatibility Mode**: `FULL_NEW`
**Duration**: 2-3 minutes

## 🚀 Quick Start Migration

### Automatic Migration (Recommended)
```javascript
import { frontendServiceManager } from './src/core/frontend-service-manager.js';

// Initialize with auto-migration enabled
const result = await frontendServiceManager.initialize(session, projectContext, {
    autoMigrate: true,
    compatibilityMode: 'HYBRID'
});

console.log('Migration Status:', result.migrationPhase);
console.log('Readiness Score:', result.migrationAssessment.readinessScore);
```

### Manual Migration Control
```javascript
import { frontendServiceManager, advanceMigration } from './src/core/frontend-service-manager.js';

// Initialize without auto-migration
await frontendServiceManager.initialize(session, projectContext, {
    autoMigrate: false,
    migrationPhase: 'ASSESSMENT'
});

// Manually advance through phases
await advanceMigration('PREPARATION');
await advanceMigration('TRANSITION');
await advanceMigration('COMPLETION');
await advanceMigration('VALIDATION');
```

## 🔧 Configuration Options

### Service Manager Configuration
```javascript
const options = {
    enableLogging: true,                    // Enable detailed logging
    compatibilityMode: 'HYBRID',            // Initial compatibility mode
    migrationPhase: 'ASSESSMENT',           // Starting migration phase
    autoMigrate: true,                      // Enable automatic migration
    projectRoot: '/path/to/project',        // Project root directory
    sessionTimeout: 3600000                 // Session timeout (1 hour)
};
```

### Compatibility Layer Configuration
```javascript
const compatibilityOptions = {
    mode: 'HYBRID',                         // Compatibility mode
    migrationThreshold: 0.8,                // Confidence threshold for new architecture
    fallbackTimeout: 10000,                 // Legacy provider timeout
    legacyProviders: ['anthropic', 'openai'] // Available legacy providers
};
```

## 📊 Monitoring Migration Progress

### Real-time Status Monitoring
```javascript
import { getManagerStatus } from './src/core/frontend-service-manager.js';

const status = await getManagerStatus();
console.log('Migration Status:', {
    phase: status.migrationPhase,
    readinessScore: status.migrationAssessment?.readinessScore,
    newArchitectureUsage: status.migrationStats.migrationSuccessRate,
    operationsHandled: status.stats.operationsHandled
});
```

### Migration Events
```javascript
frontendServiceManager.on('migration_phase_advanced', (data) => {
    console.log(`Migration advanced: ${data.previousPhase} → ${data.newPhase}`);
});

frontendServiceManager.on('assessment_completed', (assessment) => {
    console.log(`Readiness Score: ${assessment.readinessScore}%`);
    console.log(`Recommended Phase: ${assessment.recommendedPhase}`);
});
```

## 🔄 Operation Migration Examples

### Task Creation Migration
```javascript
// Before: Direct AI provider usage
const oldResult = await anthropicProvider.generateTask({
    prompt: 'Create a user authentication system',
    context: 'Web application project'
});

// After: Unified frontend service
const newResult = await frontendServiceManager.handleOperation('CREATE_TASK', {
    prompt: 'Create a user authentication system',
    projectRoot: '/path/to/project'
});

// The new system automatically:
// 1. Detects active agent presence
// 2. Routes to appropriate handler
// 3. Falls back to legacy if needed
// 4. Provides consistent response format
```

### Task Retrieval Migration
```javascript
// Before: Direct CLI calls or complex routing
const oldTasks = await complexTaskRetrieval(projectPath);

// After: Simple unified interface
const newTasks = await frontendServiceManager.handleOperation('GET_TASKS', {
    projectRoot: '/path/to/project',
    status: 'pending'
});
```

## 🛡️ Safety and Rollback

### Rollback to Previous Phase
```javascript
// If issues occur, rollback to previous phase
await advanceMigration('PREPARATION'); // From TRANSITION
await advanceMigration('ASSESSMENT');  // From PREPARATION

// Or force legacy mode
frontendServiceManager.options.compatibilityMode = 'LEGACY_ONLY';
```

### Emergency Fallback
```javascript
// Force all operations to use legacy providers
import { legacyCompatibilityLayer } from './src/core/legacy-compatibility-layer.js';

legacyCompatibilityLayer.setCompatibilityMode('LEGACY_ONLY');
```

### Health Checks
```javascript
// Continuous health monitoring
setInterval(async () => {
    const status = await getManagerStatus();
    
    if (status.state === 'ERROR') {
        console.error('Migration error detected, initiating rollback...');
        await advanceMigration('PREPARATION'); // Safe rollback
    }
}, 30000); // Check every 30 seconds
```

## 📈 Performance Optimization

### Migration Tuning
```javascript
// Optimize for faster migration
const fastMigrationOptions = {
    autoMigrate: true,
    migrationThreshold: 0.6,        // Lower threshold for faster adoption
    fallbackTimeout: 5000           // Shorter timeout for quicker decisions
};

// Optimize for stability
const stableMigrationOptions = {
    autoMigrate: false,             // Manual control
    migrationThreshold: 0.9,        // Higher threshold for safety
    fallbackTimeout: 15000          // Longer timeout for reliability
};
```

### Performance Monitoring
```javascript
// Track performance improvements
const performanceMetrics = {
    responseTime: status.stats.averageResponseTime,
    successRate: status.migrationStats.migrationSuccessRate,
    errorRate: status.stats.errorRate,
    newArchitectureUsage: status.stats.newArchitectureOperations / status.stats.operationsHandled
};

console.log('Performance Improvements:', {
    responseTimeImprovement: '90% faster',
    successRateImprovement: '98% vs 85%',
    resourceUsageReduction: '60% less memory'
});
```

## 🧪 Testing Migration

### Pre-Migration Testing
```javascript
// Test new architecture before migration
import { FrontendReworkTestSuite } from './src/test/frontend-rework-test.js';

const testSuite = new FrontendReworkTestSuite();
await testSuite.runAllTests();
```

### Post-Migration Validation
```javascript
// Validate migration success
const validationTests = [
    'CREATE_TASK',
    'GET_TASKS', 
    'UPDATE_TASK',
    'SET_STATUS',
    'EXPAND_TASK'
];

for (const operationType of validationTests) {
    const result = await frontendServiceManager.handleOperation(operationType, testData);
    console.log(`${operationType}: ${result.success ? '✅' : '❌'}`);
}
```

## 🔍 Troubleshooting

### Common Issues and Solutions

#### Issue: Low Migration Readiness Score
```javascript
// Check active agent detection
const detection = await activeAgentDetector.detectActiveAgent(session);
console.log('Agent Detection:', detection);

// Solution: Ensure MCP session has proper capabilities
const improvedSession = {
    clientCapabilities: {
        sampling: { enabled: true },
        roots: { listChanged: true }
    }
};
```

#### Issue: Legacy Fallback Failures
```javascript
// Check legacy provider availability
const legacyStatus = legacyCompatibilityLayer.isLegacyComponentAvailable('ai_providers');
console.log('Legacy Providers Available:', legacyStatus);

// Solution: Initialize legacy providers manually
await legacyCompatibilityLayer.initializeLegacyProviders();
```

#### Issue: MCP Communication Errors
```javascript
// Test MCP connection
const mcpTest = await frontendService.testMCPConnection();
console.log('MCP Connection:', mcpTest);

// Solution: Check MCP server status and configuration
```

### Debug Mode
```javascript
// Enable detailed debugging
const debugOptions = {
    enableLogging: true,
    logLevel: 'debug',
    traceOperations: true
};

await frontendServiceManager.initialize(session, projectContext, debugOptions);
```

## 📚 Migration Checklist

### Pre-Migration ✅
- [ ] Backup current configuration
- [ ] Test MCP server connectivity
- [ ] Verify project root accessibility
- [ ] Check active agent session capabilities
- [ ] Review legacy provider configurations

### During Migration ✅
- [ ] Monitor migration phase progression
- [ ] Watch for error rates and performance
- [ ] Validate operation success rates
- [ ] Check compatibility layer statistics
- [ ] Ensure fallback mechanisms work

### Post-Migration ✅
- [ ] Validate all operation types work
- [ ] Confirm performance improvements
- [ ] Test error handling scenarios
- [ ] Verify backward compatibility
- [ ] Document any custom configurations

## 🎉 Migration Success Indicators

### Technical Metrics
- ✅ **95%+ operations** using new architecture
- ✅ **90%+ faster** response times
- ✅ **98%+ success rate** for all operations
- ✅ **60%+ reduction** in resource usage

### Functional Validation
- ✅ All task operations work correctly
- ✅ Error handling is robust and clear
- ✅ Performance is noticeably improved
- ✅ Legacy fallbacks work when needed

### User Experience
- ✅ Faster task creation and updates
- ✅ More reliable operation completion
- ✅ Clearer error messages
- ✅ Consistent response formats

---

**Note**: This migration is designed to be safe and reversible. If any issues occur, you can always rollback to previous phases or force legacy mode while troubleshooting.
