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
1,440 lines (1,259 loc) • 52.6 kB
JavaScript
/**
* Enhanced Task Operations
*
* Redesigned task operations that leverage the active agent pattern through MCP middleware,
* providing optimized flows for all task management activities.
*/
import { mcpCommunicationLayer, MCP_TOOLS } from './mcp-communication-layer.js';
import { activeAgentDetector, ROUTING_STRATEGIES } from './active-agent-detector.js';
import { activeAgentIntelligenceEngine } from './active-agent-intelligence-engine.js';
import { logger } from '../utils/logger-utils.js';
/**
* Operation Flow Types
*/
export const OPERATION_FLOWS = {
DIRECT: 'direct', // Direct MCP call
INTELLIGENT: 'intelligent', // AI-enhanced operation
BATCH: 'batch', // Batch processing
STREAMING: 'streaming', // Real-time streaming
CACHED: 'cached' // Cached operation
};
/**
* Task Operation Priorities
*/
export const OPERATION_PRIORITIES = {
CRITICAL: 'critical', // Immediate execution
HIGH: 'high', // High priority
NORMAL: 'normal', // Normal priority
LOW: 'low', // Low priority
BACKGROUND: 'background' // Background processing
};
/**
* Enhanced Task Operations Class
*
* Provides optimized task operation flows that leverage active agent intelligence
* and MCP middleware for maximum efficiency and reliability.
*/
export class EnhancedTaskOperations {
constructor(options = {}) {
this.options = {
enableLogging: options.enableLogging ?? true,
enableCaching: options.enableCaching ?? true,
enableBatching: options.enableBatching ?? true,
enableStreaming: options.enableStreaming ?? false,
batchSize: options.batchSize ?? 10,
cacheTimeout: options.cacheTimeout ?? 300000, // 5 minutes
operationTimeout: options.operationTimeout ?? 30000,
...options
};
this.operationCache = new Map();
this.batchQueue = new Map();
this.operationStats = {
totalOperations: 0,
directOperations: 0,
intelligentOperations: 0,
batchOperations: 0,
cachedOperations: 0,
averageResponseTime: 0,
successRate: 0
};
this.activeOperations = new Map();
this.operationHistory = [];
}
/**
* Create a task with enhanced flow
* @param {Object} taskData - Task creation data
* @param {Object} session - MCP session
* @param {Object} options - Operation options
* @returns {Promise<Object>} Creation result
*/
async createTask(taskData, session, options = {}) {
const operationId = this.generateOperationId();
const startTime = Date.now();
try {
if (this.options.enableLogging) {
logger.info('Enhanced task creation started', {
operationId,
hasTitle: !!taskData.title,
hasPrompt: !!taskData.prompt
});
}
this.trackOperationStart(operationId, 'CREATE_TASK', taskData);
// Determine optimal flow based on task data and session
const flowType = await this.determineOptimalFlow(
'CREATE_TASK',
taskData,
session,
options
);
let result;
switch (flowType) {
case OPERATION_FLOWS.INTELLIGENT:
result = await this.createTaskIntelligent(taskData, session, options);
break;
case OPERATION_FLOWS.DIRECT:
result = await this.createTaskDirect(taskData, session, options);
break;
case OPERATION_FLOWS.CACHED:
result = await this.createTaskCached(taskData, session, options);
break;
default:
result = await this.createTaskDirect(taskData, session, options);
}
// Enhance result with operation metadata
const enhancedResult = this.enhanceOperationResult(result, {
operationId,
flowType,
responseTime: Date.now() - startTime,
operationType: 'CREATE_TASK'
});
this.trackOperationComplete(operationId, enhancedResult);
this.updateOperationStats('CREATE_TASK', flowType, Date.now() - startTime, true);
if (this.options.enableLogging) {
logger.info('Enhanced task creation completed', {
operationId,
flowType,
success: enhancedResult.success,
responseTime: Date.now() - startTime
});
}
return enhancedResult;
} catch (error) {
this.trackOperationError(operationId, error);
this.updateOperationStats('CREATE_TASK', 'error', Date.now() - startTime, false);
if (this.options.enableLogging) {
logger.error('Enhanced task creation failed', {
operationId,
error: error.message
});
}
return {
success: false,
error: error.message,
operationId,
timestamp: Date.now()
};
}
}
/**
* Create task using intelligent flow (active agent)
* @param {Object} taskData - Task data
* @param {Object} session - MCP session
* @param {Object} options - Options
* @returns {Promise<Object>} Result
*/
async createTaskIntelligent(taskData, session, options) {
// Detect active agent capabilities
const agentDetection = await activeAgentDetector.detectActiveAgent(session, {
operationType: 'CREATE_TASK',
taskData
});
if (agentDetection.strategy === ROUTING_STRATEGIES.ACTIVE_AGENT) {
// Use active agent for intelligent task creation
const intelligentTaskData = await this.enhanceTaskDataWithActiveAgent(
taskData,
session,
options
);
return mcpCommunicationLayer.callTool(
MCP_TOOLS.ADD_TASK,
{
projectRoot: taskData.projectRoot,
title: intelligentTaskData.title,
description: intelligentTaskData.description,
details: intelligentTaskData.details,
testStrategy: intelligentTaskData.testStrategy,
priority: intelligentTaskData.priority || 'medium',
dependencies: intelligentTaskData.dependencies || []
},
session,
{ flowType: OPERATION_FLOWS.INTELLIGENT }
);
} else {
// Fall back to direct creation
return this.createTaskDirect(taskData, session, options);
}
}
/**
* Create task using direct flow
* @param {Object} taskData - Task data
* @param {Object} session - MCP session
* @param {Object} options - Options
* @returns {Promise<Object>} Result
*/
async createTaskDirect(taskData, session, options) {
return mcpCommunicationLayer.callTool(
MCP_TOOLS.ADD_TASK,
{
projectRoot: taskData.projectRoot,
title: taskData.title,
description: taskData.description,
details: taskData.details,
testStrategy: taskData.testStrategy,
priority: taskData.priority || 'medium',
dependencies: taskData.dependencies || []
},
session,
{ flowType: OPERATION_FLOWS.DIRECT }
);
}
/**
* Create task using cached flow
* @param {Object} taskData - Task data
* @param {Object} session - MCP session
* @param {Object} options - Options
* @returns {Promise<Object>} Result
*/
async createTaskCached(taskData, session, options) {
const cacheKey = this.generateCacheKey('CREATE_TASK', taskData);
const cached = this.getFromCache(cacheKey);
if (cached) {
return {
...cached,
fromCache: true,
timestamp: Date.now()
};
}
const result = await this.createTaskDirect(taskData, session, options);
if (result.success && this.options.enableCaching) {
this.setCache(cacheKey, result);
}
return result;
}
/**
* Enhance task data using active agent intelligence
* @param {Object} taskData - Original task data
* @param {Object} session - MCP session
* @param {Object} options - Options
* @returns {Promise<Object>} Enhanced task data
*/
async enhanceTaskDataWithActiveAgent(taskData, session, options) {
// If structured data is already provided, use it
if (taskData.title && taskData.description) {
return {
title: taskData.title,
description: taskData.description,
details: taskData.details || this.generateDefaultDetails(taskData),
testStrategy: taskData.testStrategy || this.generateDefaultTestStrategy(taskData),
priority: taskData.priority,
dependencies: taskData.dependencies
};
}
// Extract from prompt using active agent intelligence engine
if (taskData.prompt) {
try {
const intelligenceResult = await activeAgentIntelligenceEngine.generateTaskFromPrompt(
taskData.prompt,
options.context || {},
session
);
if (intelligenceResult.success) {
return intelligenceResult.task;
} else {
// Fallback to enhanced parsing
return this.parseTaskFromPromptEnhanced(taskData.prompt, options);
}
} catch (error) {
if (this.options.enableLogging) {
logger.warn('Active agent intelligence failed, using fallback parsing:', error.message);
}
return this.parseTaskFromPromptEnhanced(taskData.prompt, options);
}
}
throw new Error('Insufficient data to create enhanced task');
}
/**
* Parse task details from prompt with enhanced intelligence
* @param {string} prompt - Task prompt
* @param {Object} options - Parsing options
* @returns {Object} Parsed task data
*/
parseTaskFromPromptEnhanced(prompt, options = {}) {
// Enhanced parsing with context awareness
const context = options.context || {};
// Extract title with improved intelligence
let title = this.extractTitleFromPrompt(prompt, context);
// Generate comprehensive description
let description = this.generateDescriptionFromPrompt(prompt, context);
// Generate detailed implementation details
const details = this.generateImplementationDetails(prompt, context);
// Generate comprehensive test strategy
const testStrategy = this.generateTestStrategy(prompt, context);
// Determine priority based on prompt analysis
const priority = this.determinePriorityFromPrompt(prompt, context);
// Extract potential dependencies
const dependencies = this.extractDependenciesFromPrompt(prompt, context);
return {
title,
description,
details,
testStrategy,
priority,
dependencies
};
}
/**
* Extract title from prompt with enhanced intelligence
* @param {string} prompt - Task prompt
* @param {Object} context - Additional context
* @returns {string} Extracted title
*/
extractTitleFromPrompt(prompt, context) {
// Remove common prefixes and clean up
let title = prompt.split(/[.\n]/)[0].trim();
// Remove action words at the beginning
title = title.replace(/^(create|implement|build|develop|add|design|write|setup|configure)\s+/i, '');
title = title.replace(/^(a|an|the)\s+/i, '');
// Capitalize first letter and handle acronyms
title = title.charAt(0).toUpperCase() + title.slice(1);
// Handle common patterns
if (title.toLowerCase().includes('system')) {
title = title.replace(/system/i, 'System');
}
if (title.toLowerCase().includes('api')) {
title = title.replace(/api/i, 'API');
}
if (title.toLowerCase().includes('ui')) {
title = title.replace(/ui/i, 'UI');
}
// Limit length and add context if available
if (title.length > 80) {
title = title.substring(0, 77) + '...';
}
// Add context prefix if relevant
if (context.projectType) {
const projectPrefix = this.getProjectTypePrefix(context.projectType);
if (projectPrefix && !title.toLowerCase().includes(projectPrefix.toLowerCase())) {
title = `${projectPrefix} ${title}`;
}
}
return title;
}
/**
* Generate description from prompt
* @param {string} prompt - Task prompt
* @param {Object} context - Additional context
* @returns {string} Generated description
*/
generateDescriptionFromPrompt(prompt, context) {
let description = prompt;
// Limit length but preserve important information
if (description.length > 300) {
// Try to find a good breaking point
const sentences = description.split(/[.!?]/);
let truncated = '';
for (const sentence of sentences) {
if ((truncated + sentence).length > 250) {
break;
}
truncated += sentence + '. ';
}
description = truncated.trim() + '...';
}
// Add context information if available
if (context.projectType) {
description = `${description}\n\nProject Type: ${context.projectType}`;
}
if (context.relatedTasks && context.relatedTasks.length > 0) {
description += `\n\nRelated Tasks: ${context.relatedTasks.join(', ')}`;
}
return description;
}
/**
* Generate implementation details
* @param {string} prompt - Task prompt
* @param {Object} context - Additional context
* @returns {string} Implementation details
*/
generateImplementationDetails(prompt, context) {
const details = `Implementation Details for: ${prompt}
Key Requirements:
- Follow project coding standards and best practices
- Ensure compatibility with existing system architecture
- Implement proper error handling and validation
- Include comprehensive logging and monitoring
- Consider performance and scalability implications
Technical Considerations:
- Review existing codebase for similar implementations
- Identify potential integration points and dependencies
- Plan for testing at unit, integration, and system levels
- Document any new APIs or interfaces created
- Consider security implications and implement appropriate measures
Implementation Steps:
1. Analyze requirements and design approach
2. Create implementation plan and timeline
3. Develop core functionality with tests
4. Integrate with existing systems
5. Perform thorough testing and validation
6. Document implementation and usage
7. Deploy and monitor in production environment`;
// Add context-specific details
if (context.projectType === 'web-application') {
return details + `
Web Application Specific:
- Ensure responsive design and cross-browser compatibility
- Implement proper state management
- Consider SEO and accessibility requirements
- Optimize for performance and loading times`;
}
if (context.projectType === 'api') {
return details + `
API Specific:
- Design RESTful endpoints following conventions
- Implement proper authentication and authorization
- Include comprehensive API documentation
- Plan for versioning and backward compatibility`;
}
return details;
}
/**
* Generate test strategy
* @param {string} prompt - Task prompt
* @param {Object} context - Additional context
* @returns {string} Test strategy
*/
generateTestStrategy(prompt, context) {
const title = this.extractTitleFromPrompt(prompt, context);
return `Test Strategy for: ${title}
Testing Approach:
1. Unit Testing
- Test individual components and functions
- Verify correct behavior with valid inputs
- Test error handling with invalid inputs
- Achieve minimum 80% code coverage
2. Integration Testing
- Test component interactions
- Verify data flow between modules
- Test external service integrations
- Validate API contracts and interfaces
3. System Testing
- End-to-end workflow validation
- Performance and load testing
- Security and vulnerability testing
- User acceptance testing scenarios
4. Regression Testing
- Ensure existing functionality remains intact
- Automated test suite execution
- Cross-browser and cross-platform testing
- Backward compatibility verification
Test Environment:
- Set up isolated test environment
- Use test data and mock services
- Implement continuous integration testing
- Monitor test results and coverage metrics
Acceptance Criteria:
- All tests pass with 95%+ success rate
- Performance meets specified requirements
- Security vulnerabilities addressed
- User acceptance criteria satisfied`;
}
/**
* Determine priority from prompt analysis
* @param {string} prompt - Task prompt
* @param {Object} context - Additional context
* @returns {string} Determined priority
*/
determinePriorityFromPrompt(prompt, context) {
const lowerPrompt = prompt.toLowerCase();
// High priority indicators
const highPriorityKeywords = [
'urgent', 'critical', 'asap', 'immediately', 'emergency',
'security', 'vulnerability', 'bug fix', 'production issue'
];
// Low priority indicators
const lowPriorityKeywords = [
'nice to have', 'future', 'enhancement', 'optimization',
'refactor', 'cleanup', 'documentation'
];
if (highPriorityKeywords.some(keyword => lowerPrompt.includes(keyword))) {
return 'high';
}
if (lowPriorityKeywords.some(keyword => lowerPrompt.includes(keyword))) {
return 'low';
}
// Context-based priority
if (context.deadline && this.isDeadlineUrgent(context.deadline)) {
return 'high';
}
return 'medium'; // Default priority
}
/**
* Extract dependencies from prompt
* @param {string} prompt - Task prompt
* @param {Object} context - Additional context
* @returns {Array} Extracted dependencies
*/
extractDependenciesFromPrompt(prompt, context) {
const dependencies = [];
// Look for explicit dependency mentions
const dependencyPatterns = [
/depends on task (\d+)/gi,
/requires task (\d+)/gi,
/after task (\d+)/gi,
/following task (\d+)/gi
];
for (const pattern of dependencyPatterns) {
const matches = prompt.matchAll(pattern);
for (const match of matches) {
const taskId = parseInt(match[1]);
if (!isNaN(taskId) && !dependencies.includes(taskId)) {
dependencies.push(taskId);
}
}
}
// Add context-based dependencies
if (context.relatedTasks) {
context.relatedTasks.forEach(taskId => {
if (!dependencies.includes(taskId)) {
dependencies.push(taskId);
}
});
}
return dependencies;
}
/**
* Get tasks with enhanced flow
* @param {Object} filters - Task filters
* @param {Object} session - MCP session
* @param {Object} options - Operation options
* @returns {Promise<Object>} Tasks result
*/
async getTasks(filters, session, options = {}) {
const operationId = this.generateOperationId();
const startTime = Date.now();
try {
this.trackOperationStart(operationId, 'GET_TASKS', filters);
// Check cache first if enabled
if (this.options.enableCaching) {
const cacheKey = this.generateCacheKey('GET_TASKS', filters);
const cached = this.getFromCache(cacheKey);
if (cached) {
this.updateOperationStats('GET_TASKS', OPERATION_FLOWS.CACHED, Date.now() - startTime, true);
return this.enhanceOperationResult(cached, {
operationId,
flowType: OPERATION_FLOWS.CACHED,
responseTime: Date.now() - startTime,
fromCache: true
});
}
}
// Determine optimal flow
const flowType = await this.determineOptimalFlow('GET_TASKS', filters, session, options);
let result;
if (flowType === OPERATION_FLOWS.BATCH && this.options.enableBatching) {
result = await this.getTasksBatch(filters, session, options);
} else {
result = await mcpCommunicationLayer.callTool(
MCP_TOOLS.GET_TASKS,
{
projectRoot: filters.projectRoot,
status: filters.status,
withSubtasks: filters.withSubtasks,
file: filters.file
},
session,
{ flowType }
);
}
// Cache successful results
if (result.success && this.options.enableCaching) {
const cacheKey = this.generateCacheKey('GET_TASKS', filters);
this.setCache(cacheKey, result);
}
const enhancedResult = this.enhanceOperationResult(result, {
operationId,
flowType,
responseTime: Date.now() - startTime,
operationType: 'GET_TASKS'
});
this.trackOperationComplete(operationId, enhancedResult);
this.updateOperationStats('GET_TASKS', flowType, Date.now() - startTime, true);
return enhancedResult;
} catch (error) {
this.trackOperationError(operationId, error);
this.updateOperationStats('GET_TASKS', 'error', Date.now() - startTime, false);
return {
success: false,
error: error.message,
operationId,
timestamp: Date.now()
};
}
}
/**
* Update task with enhanced flow
* @param {string} taskId - Task ID
* @param {Object} updateData - Update data
* @param {Object} session - MCP session
* @param {Object} options - Operation options
* @returns {Promise<Object>} Update result
*/
async updateTask(taskId, updateData, session, options = {}) {
const operationId = this.generateOperationId();
const startTime = Date.now();
try {
this.trackOperationStart(operationId, 'UPDATE_TASK', { taskId, ...updateData });
// Determine optimal flow
const flowType = await this.determineOptimalFlow('UPDATE_TASK', updateData, session, options);
let result;
if (flowType === OPERATION_FLOWS.INTELLIGENT) {
result = await this.updateTaskIntelligent(taskId, updateData, session, options);
} else {
result = await mcpCommunicationLayer.callTool(
MCP_TOOLS.UPDATE_TASK,
{
projectRoot: updateData.projectRoot,
id: taskId,
prompt: updateData.prompt,
research: updateData.research || false
},
session,
{ flowType }
);
}
const enhancedResult = this.enhanceOperationResult(result, {
operationId,
flowType,
responseTime: Date.now() - startTime,
operationType: 'UPDATE_TASK'
});
this.trackOperationComplete(operationId, enhancedResult);
this.updateOperationStats('UPDATE_TASK', flowType, Date.now() - startTime, true);
return enhancedResult;
} catch (error) {
this.trackOperationError(operationId, error);
this.updateOperationStats('UPDATE_TASK', 'error', Date.now() - startTime, false);
return {
success: false,
error: error.message,
operationId,
timestamp: Date.now()
};
}
}
/**
* Set task status with enhanced flow
* @param {string} taskId - Task ID
* @param {string} status - New status
* @param {Object} session - MCP session
* @param {Object} options - Operation options
* @returns {Promise<Object>} Status update result
*/
async setTaskStatus(taskId, status, session, options = {}) {
const operationId = this.generateOperationId();
const startTime = Date.now();
try {
this.trackOperationStart(operationId, 'SET_STATUS', { taskId, status });
// Status updates are typically direct operations
const result = await mcpCommunicationLayer.callTool(
MCP_TOOLS.SET_STATUS,
{
projectRoot: options.projectRoot,
id: taskId,
status
},
session,
{ flowType: OPERATION_FLOWS.DIRECT }
);
const enhancedResult = this.enhanceOperationResult(result, {
operationId,
flowType: OPERATION_FLOWS.DIRECT,
responseTime: Date.now() - startTime,
operationType: 'SET_STATUS'
});
this.trackOperationComplete(operationId, enhancedResult);
this.updateOperationStats('SET_STATUS', OPERATION_FLOWS.DIRECT, Date.now() - startTime, true);
return enhancedResult;
} catch (error) {
this.trackOperationError(operationId, error);
this.updateOperationStats('SET_STATUS', 'error', Date.now() - startTime, false);
return {
success: false,
error: error.message,
operationId,
timestamp: Date.now()
};
}
}
/**
* Expand task with enhanced flow
* @param {string} taskId - Task ID
* @param {Object} expansionData - Expansion data
* @param {Object} session - MCP session
* @param {Object} options - Operation options
* @returns {Promise<Object>} Expansion result
*/
async expandTask(taskId, expansionData, session, options = {}) {
const operationId = this.generateOperationId();
const startTime = Date.now();
try {
this.trackOperationStart(operationId, 'EXPAND_TASK', { taskId, ...expansionData });
// Task expansion benefits from intelligent flow
const flowType = OPERATION_FLOWS.INTELLIGENT;
const result = await this.expandTaskIntelligent(taskId, expansionData, session, options);
const enhancedResult = this.enhanceOperationResult(result, {
operationId,
flowType,
responseTime: Date.now() - startTime,
operationType: 'EXPAND_TASK'
});
this.trackOperationComplete(operationId, enhancedResult);
this.updateOperationStats('EXPAND_TASK', flowType, Date.now() - startTime, true);
return enhancedResult;
} catch (error) {
this.trackOperationError(operationId, error);
this.updateOperationStats('EXPAND_TASK', 'error', Date.now() - startTime, false);
return {
success: false,
error: error.message,
operationId,
timestamp: Date.now()
};
}
}
/**
* Determine optimal flow for operation
* @param {string} operationType - Type of operation
* @param {Object} operationData - Operation data
* @param {Object} session - MCP session
* @param {Object} options - Options
* @returns {Promise<string>} Optimal flow type
*/
async determineOptimalFlow(operationType, operationData, session, options) {
// Check for explicit flow preference
if (options.flowType) {
return options.flowType;
}
// Check cache eligibility
if (this.options.enableCaching && this.isCacheableOperation(operationType, operationData)) {
const cacheKey = this.generateCacheKey(operationType, operationData);
if (this.getFromCache(cacheKey)) {
return OPERATION_FLOWS.CACHED;
}
}
// Check batch eligibility
if (this.options.enableBatching && this.isBatchableOperation(operationType, operationData)) {
return OPERATION_FLOWS.BATCH;
}
// Check intelligent flow eligibility
if (await this.isIntelligentFlowBeneficial(operationType, operationData, session)) {
return OPERATION_FLOWS.INTELLIGENT;
}
// Default to direct flow
return OPERATION_FLOWS.DIRECT;
}
/**
* Check if operation is cacheable
* @param {string} operationType - Operation type
* @param {Object} operationData - Operation data
* @returns {boolean} True if cacheable
*/
isCacheableOperation(operationType, operationData) {
// Read operations are generally cacheable
const cacheableOperations = ['GET_TASKS', 'GET_TASK'];
return cacheableOperations.includes(operationType);
}
/**
* Check if operation is batchable
* @param {string} operationType - Operation type
* @param {Object} operationData - Operation data
* @returns {boolean} True if batchable
*/
isBatchableOperation(operationType, operationData) {
// Multiple similar operations can be batched
const batchableOperations = ['GET_TASKS', 'SET_STATUS'];
return batchableOperations.includes(operationType);
}
/**
* Check if intelligent flow would be beneficial
* @param {string} operationType - Operation type
* @param {Object} operationData - Operation data
* @param {Object} session - MCP session
* @returns {Promise<boolean>} True if beneficial
*/
async isIntelligentFlowBeneficial(operationType, operationData, session) {
// Operations that benefit from AI intelligence
const intelligentOperations = ['CREATE_TASK', 'UPDATE_TASK', 'EXPAND_TASK'];
if (!intelligentOperations.includes(operationType)) {
return false;
}
// Check if active agent is available
try {
const detection = await activeAgentDetector.detectActiveAgent(session, {
operationType,
operationData
});
return detection.success && detection.confidence > 0.7;
} catch (error) {
return false;
}
}
/**
* Update task using intelligent flow
* @param {string} taskId - Task ID
* @param {Object} updateData - Update data
* @param {Object} session - MCP session
* @param {Object} options - Options
* @returns {Promise<Object>} Update result
*/
async updateTaskIntelligent(taskId, updateData, session, options) {
try {
// Use active agent intelligence for task updates
const intelligenceResult = await activeAgentIntelligenceEngine.updateTaskWithIntelligence(
taskId,
updateData.prompt,
updateData.existingTask || {},
options.context || {},
session
);
if (intelligenceResult.success) {
// Apply the intelligent update through MCP
return mcpCommunicationLayer.callTool(
MCP_TOOLS.UPDATE_TASK,
{
projectRoot: updateData.projectRoot,
id: taskId,
prompt: this.formatIntelligentUpdate(intelligenceResult.updated_task, updateData.prompt),
research: updateData.research || false
},
session,
{ flowType: OPERATION_FLOWS.INTELLIGENT }
);
} else {
// Fallback to enhanced prompt
const enhancedPrompt = await this.enhanceUpdatePrompt(updateData.prompt, taskId, session);
return mcpCommunicationLayer.callTool(
MCP_TOOLS.UPDATE_TASK,
{
projectRoot: updateData.projectRoot,
id: taskId,
prompt: enhancedPrompt,
research: updateData.research || false
},
session,
{ flowType: OPERATION_FLOWS.INTELLIGENT }
);
}
} catch (error) {
if (this.options.enableLogging) {
logger.warn('Intelligent task update failed, using fallback:', error.message);
}
// Fallback to basic update
const enhancedPrompt = await this.enhanceUpdatePrompt(updateData.prompt, taskId, session);
return mcpCommunicationLayer.callTool(
MCP_TOOLS.UPDATE_TASK,
{
projectRoot: updateData.projectRoot,
id: taskId,
prompt: enhancedPrompt,
research: updateData.research || false
},
session,
{ flowType: OPERATION_FLOWS.INTELLIGENT }
);
}
}
/**
* Expand task using intelligent flow
* @param {string} taskId - Task ID
* @param {Object} expansionData - Expansion data
* @param {Object} session - MCP session
* @param {Object} options - Options
* @returns {Promise<Object>} Expansion result
*/
async expandTaskIntelligent(taskId, expansionData, session, options) {
try {
// Use active agent intelligence for task expansion
const intelligenceResult = await activeAgentIntelligenceEngine.expandTaskIntoSubtasks(
{ id: taskId, ...expansionData },
{ numSubtasks: expansionData.numSubtasks, ...options.context },
session
);
if (intelligenceResult.success) {
// Apply the intelligent expansion through MCP
return mcpCommunicationLayer.callTool(
MCP_TOOLS.EXPAND_TASK,
{
projectRoot: expansionData.projectRoot,
id: taskId,
num: intelligenceResult.subtasks.length,
prompt: this.formatIntelligentExpansion(intelligenceResult),
research: expansionData.research || false
},
session,
{ flowType: OPERATION_FLOWS.INTELLIGENT }
);
} else {
// Fallback to basic expansion
const intelligentExpansion = await this.generateIntelligentExpansion(
taskId,
expansionData,
session
);
return mcpCommunicationLayer.callTool(
MCP_TOOLS.EXPAND_TASK,
{
projectRoot: expansionData.projectRoot,
id: taskId,
num: intelligentExpansion.numSubtasks,
prompt: intelligentExpansion.prompt,
research: expansionData.research || false
},
session,
{ flowType: OPERATION_FLOWS.INTELLIGENT }
);
}
} catch (error) {
if (this.options.enableLogging) {
logger.warn('Intelligent task expansion failed, using fallback:', error.message);
}
// Fallback to basic expansion
const intelligentExpansion = await this.generateIntelligentExpansion(
taskId,
expansionData,
session
);
return mcpCommunicationLayer.callTool(
MCP_TOOLS.EXPAND_TASK,
{
projectRoot: expansionData.projectRoot,
id: taskId,
num: intelligentExpansion.numSubtasks,
prompt: intelligentExpansion.prompt,
research: expansionData.research || false
},
session,
{ flowType: OPERATION_FLOWS.INTELLIGENT }
);
}
}
/**
* Get tasks using batch flow
* @param {Object} filters - Task filters
* @param {Object} session - MCP session
* @param {Object} options - Options
* @returns {Promise<Object>} Batch result
*/
async getTasksBatch(filters, session, options) {
// For now, implement as direct call
// In future, could batch multiple similar requests
return mcpCommunicationLayer.callTool(
MCP_TOOLS.GET_TASKS,
{
projectRoot: filters.projectRoot,
status: filters.status,
withSubtasks: filters.withSubtasks,
file: filters.file
},
session,
{ flowType: OPERATION_FLOWS.BATCH }
);
}
/**
* Enhance update prompt with intelligence
* @param {string} prompt - Original prompt
* @param {string} taskId - Task ID
* @param {Object} session - MCP session
* @returns {Promise<string>} Enhanced prompt
*/
async enhanceUpdatePrompt(prompt, taskId, session) {
// Add context and intelligence to update prompt
const timestamp = new Date().toISOString();
return `${prompt}
Update Context:
- Task ID: ${taskId}
- Timestamp: ${timestamp}
- Update requested through enhanced task operations
- Consider existing task context and dependencies`;
}
/**
* Generate intelligent expansion parameters
* @param {string} taskId - Task ID
* @param {Object} expansionData - Expansion data
* @param {Object} session - MCP session
* @returns {Promise<Object>} Intelligent expansion parameters
*/
async generateIntelligentExpansion(taskId, expansionData, session) {
const numSubtasks = expansionData.numSubtasks || this.calculateOptimalSubtaskCount(expansionData);
const prompt = expansionData.prompt ||
`Break down task ${taskId} into ${numSubtasks} logical implementation phases, considering:
- Dependencies between subtasks
- Logical progression of work
- Testing and validation requirements
- Integration points with existing system`;
return {
numSubtasks,
prompt
};
}
/**
* Calculate optimal subtask count
* @param {Object} expansionData - Expansion data
* @returns {number} Optimal count
*/
calculateOptimalSubtaskCount(expansionData) {
// Default to 3-5 subtasks for most tasks
if (expansionData.complexity === 'high') {
return 7;
} else if (expansionData.complexity === 'low') {
return 3;
}
return 5; // Default for medium complexity
}
/**
* Helper methods for operation management
*/
/**
* Generate operation ID
* @returns {string} Unique operation ID
*/
generateOperationId() {
return `op_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
/**
* Generate cache key
* @param {string} operationType - Operation type
* @param {Object} operationData - Operation data
* @returns {string} Cache key
*/
generateCacheKey(operationType, operationData) {
const dataString = JSON.stringify(operationData, Object.keys(operationData).sort());
return `${operationType}_${this.hashString(dataString)}`;
}
/**
* Hash string for cache keys
* @param {string} str - String to hash
* @returns {string} Hash
*/
hashString(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return hash.toString(36);
}
/**
* Get from cache
* @param {string} key - Cache key
* @returns {Object|null} Cached value or null
*/
getFromCache(key) {
const cached = this.operationCache.get(key);
if (cached && (Date.now() - cached.timestamp) < this.options.cacheTimeout) {
return cached.data;
}
if (cached) {
this.operationCache.delete(key);
}
return null;
}
/**
* Set cache
* @param {string} key - Cache key
* @param {Object} data - Data to cache
*/
setCache(key, data) {
this.operationCache.set(key, {
data,
timestamp: Date.now()
});
}
/**
* Track operation start
* @param {string} operationId - Operation ID
* @param {string} operationType - Operation type
* @param {Object} operationData - Operation data
*/
trackOperationStart(operationId, operationType, operationData) {
this.activeOperations.set(operationId, {
type: operationType,
data: operationData,
startTime: Date.now(),
status: 'running'
});
this.operationStats.totalOperations++;
}
/**
* Track operation completion
* @param {string} operationId - Operation ID
* @param {Object} result - Operation result
*/
trackOperationComplete(operationId, result) {
const operation = this.activeOperations.get(operationId);
if (operation) {
operation.status = 'completed';
operation.endTime = Date.now();
operation.result = result;
this.operationHistory.push(operation);
this.activeOperations.delete(operationId);
// Keep history limited
if (this.operationHistory.length > 1000) {
this.operationHistory = this.operationHistory.slice(-500);
}
}
}
/**
* Track operation error
* @param {string} operationId - Operation ID
* @param {Error} error - Error that occurred
*/
trackOperationError(operationId, error) {
const operation = this.activeOperations.get(operationId);
if (operation) {
operation.status = 'error';
operation.endTime = Date.now();
operation.error = error.message;
this.operationHistory.push(operation);
this.activeOperations.delete(operationId);
}
}
/**
* Update operation statistics
* @param {string} operationType - Operation type
* @param {string} flowType - Flow type used
* @param {number} responseTime - Response time in ms
* @param {boolean} success - Whether operation succeeded
*/
updateOperationStats(operationType, flowType, responseTime, success) {
// Update flow-specific stats
switch (flowType) {
case OPERATION_FLOWS.DIRECT:
this.operationStats.directOperations++;
break;
case OPERATION_FLOWS.INTELLIGENT:
this.operationStats.intelligentOperations++;
break;
case OPERATION_FLOWS.BATCH:
this.operationStats.batchOperations++;
break;
case OPERATION_FLOWS.CACHED:
this.operationStats.cachedOperations++;
break;
}
// Update average response time
const totalOps = this.operationStats.totalOperations;
const currentAvg = this.operationStats.averageResponseTime;
this.operationStats.averageResponseTime =
((currentAvg * (totalOps - 1)) + responseTime) / totalOps;
// Update success rate
const successfulOps = success ?
(this.operationStats.successRate * (totalOps - 1) / 100) + 1 :
(this.operationStats.successRate * (totalOps - 1) / 100);
this.operationStats.successRate = (successfulOps / totalOps) * 100;
}
/**
* Enhance operation result with metadata
* @param {Object} result - Original result
* @param {Object} metadata - Additional metadata
* @returns {Object} Enhanced result
*/
enhanceOperationResult(result, metadata) {
return {
...result,
operationMetadata: {
operationId: metadata.operationId,
flowType: metadata.flowType,
responseTime: metadata.responseTime,
operationType: metadata.operationType,
timestamp: Date.now(),
fromCache: metadata.fromCache || false
}
};
}
/**
* Get operation statistics
* @returns {Object} Operation statistics
*/
getOperationStats() {
return {
...this.operationStats,
activeOperations: this.activeOperations.size,
cacheSize: this.operationCache.size,
historySize: this.operationHistory.length
};
}
/**
* Clear operation cache
*/
clearCache() {
this.operationCache.clear();
if (this.options.enableLogging) {
logger.debug('Enhanced task operations cache cleared');
}
}
/**
* Get project type prefix for titles
* @param {string} projectType - Project type
* @returns {string} Prefix
*/
getProjectTypePrefix(projectType) {
const prefixes = {
'web-application': 'Web',
'api': 'API',
'mobile-app': 'Mobile',
'desktop-app': 'Desktop',
'library': 'Library',
'cli-tool': 'CLI'
};
return prefixes[projectType] || '';
}
/**
* Check if deadline is urgent
* @param {string|Date} deadline - Deadline
* @returns {boolean} True if urgent
*/
isDeadlineUrgent(deadline) {
const deadlineDate = new Date(deadline);
const now = new Date();
const timeDiff = deadlineDate.getTime() - now.getTime();
const daysDiff = timeDiff / (1000 * 3600 * 24);
return daysDiff <= 3; // Urgent if deadline is within 3 days
}
/**
* Generate default details for task
* @param {Object} taskData - Task data
* @returns {string} Default details
*/
generateDefaultDetails(taskData) {
return `Implementation details for: ${taskData.title}
This task should be implemented following best practices and considering the project's existing architecture and dependencies.
Key considerations:
- Follow project coding standards
- Implement proper error handling
- Include comprehensive testing
- Document any new APIs or interfaces`;
}
/**
* Generate default test strategy for task
* @param {Object} taskData - Task data
* @returns {string} Default test strategy
*/
generateDefaultTestStrategy(taskData) {
return `Test strategy for: ${taskData.title}
1. Unit testing of individual components
2. Integration testing with existing systems
3. End-to-end workflow validation
4. Performance and security testing
5. User acceptance testing`;
}
/**
* Format intelligent update for MCP communication
* @param {Object} intelligentUpdate - Update from intelligence engine
* @param {string} originalPrompt - Original update prompt
* @returns {string} Formatted update prompt
*/
formatIntelligentUpdate(intelligentUpdate, originalPrompt) {
const changes = intelligentUpdate.changes_summary?.changes || [];
let formattedPrompt = `Intelligent Update Applied:\n\n${originalPrompt}\n\n`;
if (changes.length > 0) {
formattedPrompt += `Changes Applied:\n${changes.map(change => `- ${change}`).join('\n')}\n\n`;
}
if (intelligentUpdate.title) {
formattedPrompt += `Updated Title: ${intelligentUpdate.title}\n`;
}
if (intelligentUpdate.description) {
formattedPrompt += `Updated Description: ${intelligentUpdate.description}\n`;
}
if (intelli