mirror-magi-meta-agent
Version:
AI-powered development planning and execution system with Supabase integration
282 lines (241 loc) • 10.1 kB
JavaScript
class TaskClassifier {
constructor(learningSystem = null) {
this.learningSystem = learningSystem;
this.patterns = this.loadKnownPatterns();
}
loadKnownPatterns() {
return {
taskTypes: {
'feature_development': {
keywords: ['create new feature', 'implement feature', 'add functionality', 'build system', 'develop capability'],
complexity: 3,
avgTime: 120
},
'component_creation': {
keywords: ['create component', 'build component', 'new react component', 'ui component', 'reusable component'],
complexity: 2,
avgTime: 45
},
'api_integration': {
keywords: ['integrate api', 'connect service', 'external service', 'third party', 'webhook', 'rest api'],
complexity: 3,
avgTime: 90
},
'database_schema': {
keywords: ['database', 'schema', 'migration', 'table', 'sql', 'nosql', 'foreign key', 'index', 'constraint'],
complexity: 3,
avgTime: 60
},
'bug_fix': {
keywords: ['fix bug', 'resolve issue', 'error', 'not working', 'broken', 'debug', 'troubleshoot'],
complexity: 2,
avgTime: 30
},
'testing': {
keywords: ['add test', 'test coverage', 'e2e test', 'unit test', 'playwright', 'jest', 'testing'],
complexity: 2,
avgTime: 60
},
'refactoring': {
keywords: ['refactor', 'improve code', 'optimize', 'clean up', 'restructure', 'modernize'],
complexity: 3,
avgTime: 90
},
'performance_optimization': {
keywords: ['performance', 'slow', 'optimize', 'speed up', 'bundle size', 'loading time'],
complexity: 4,
avgTime: 150
}
}
};
}
classifyTask(taskDescription) {
const analysis = {
primaryType: this.determinePrimaryType(taskDescription),
complexity: this.assessComplexity(taskDescription),
domains: this.identifyDomains(taskDescription),
dependencies: this.identifyDependencies(taskDescription),
riskLevel: this.assessRisk(taskDescription),
estimatedTime: this.estimateTime(taskDescription)
};
return this.enhanceWithLearnings(analysis, taskDescription);
}
determinePrimaryType(description) {
const descLower = description.toLowerCase();
let bestMatch = 'feature_development';
let maxScore = 0;
Object.entries(this.patterns.taskTypes).forEach(([type, pattern]) => {
const score = this.calculateMatchScore(descLower, pattern.keywords);
if (score > maxScore) {
maxScore = score;
bestMatch = type;
}
});
return bestMatch;
}
calculateMatchScore(description, keywords) {
let score = 0;
keywords.forEach(keyword => {
if (description.includes(keyword)) {
score += keyword.split(' ').length; // Longer phrases score higher
}
});
return score;
}
identifyDomains(description) {
const domains = [];
const domainKeywords = {
'frontend': ['react', 'vue', 'angular', 'component', 'ui', 'interface', 'user', 'display', 'form', 'button'],
'backend': ['api', 'server', 'database', 'auth', 'endpoint', 'service', 'express', 'fastapi'],
'database': ['schema', 'table', 'migration', 'sql', 'mongodb', 'query', 'index', 'rls'],
'testing': ['test', 'e2e', 'unit', 'playwright', 'jest', 'cypress', 'coverage', 'spec'],
'external_apis': ['integration', 'third-party', 'webhook', 'rest', 'graphql', 'api'],
'ai_features': ['ai', 'ml', 'machine learning', 'openai', 'suggestions', 'recommendations', 'smart', 'intelligent'],
'real_time': ['realtime', 'live', 'websocket', 'subscription', 'sync', 'streaming'],
'authentication': ['auth', 'login', 'signup', 'user', 'session', 'jwt', 'oauth', 'security'],
'user_management': ['user', 'profile', 'account', 'preferences', 'settings', 'permissions'],
'data_visualization': ['chart', 'graph', 'dashboard', 'analytics', 'metrics', 'reporting'],
'mobile': ['mobile', 'responsive', 'touch', 'ios', 'android', 'react-native'],
'performance': ['performance', 'optimization', 'caching', 'bundle', 'loading', 'speed'],
'security': ['security', 'encryption', 'validation', 'sanitization', 'csrf', 'xss']
};
const descLower = description.toLowerCase();
Object.entries(domainKeywords).forEach(([domain, keywords]) => {
if (this.hasKeywords(descLower, keywords)) {
domains.push(domain);
}
});
return domains;
}
hasKeywords(description, keywords) {
return keywords.some(keyword => description.includes(keyword));
}
assessComplexity(description) {
let complexityScore = 1; // Base complexity
const descLower = description.toLowerCase();
// Factors that increase complexity
const complexityFactors = {
'multiple_domains': { keywords: ['multiple', 'integrate', 'connect'], multiplier: 2 },
'external_integration': { keywords: ['external', 'third-party', 'api'], multiplier: 1.5 },
'real_time_features': { keywords: ['realtime', 'live', 'collaboration'], multiplier: 2 },
'authentication_changes': { keywords: ['auth', 'security', 'permission'], multiplier: 1.5 },
'database_migration': { keywords: ['migration', 'schema', 'database'], multiplier: 1.8 },
'ai_integration': { keywords: ['ai', 'openai', 'smart'], multiplier: 2.2 },
'performance_optimization': { keywords: ['performance', 'optimize', 'speed'], multiplier: 2.5 },
'large_refactoring': { keywords: ['refactor', 'restructure', 'redesign'], multiplier: 3 }
};
// Check for complexity indicators
Object.values(complexityFactors).forEach(factor => {
if (this.hasKeywords(descLower, factor.keywords)) {
complexityScore *= factor.multiplier;
}
});
// Additional complexity for vague requirements
if (this.hasKeywords(descLower, ['complex', 'advanced', 'sophisticated', 'comprehensive'])) {
complexityScore *= 1.5;
}
// Normalize to 1-5 scale
return Math.min(5, Math.max(1, Math.round(complexityScore)));
}
identifyDependencies(description) {
const dependencies = [];
const descLower = description.toLowerCase();
// Check for explicit dependencies
if (descLower.includes('after') || descLower.includes('depends on')) {
dependencies.push('explicit_dependency');
}
// Check for implicit dependencies
const dependencyPatterns = {
'database_first': ['api', 'service', 'endpoint'],
'api_first': ['component', 'ui', 'frontend'],
'auth_required': ['user', 'profile', 'permission']
};
Object.entries(dependencyPatterns).forEach(([dep, keywords]) => {
if (this.hasKeywords(descLower, keywords)) {
dependencies.push(dep);
}
});
return dependencies;
}
assessRisk(description) {
let riskLevel = 'low';
const descLower = description.toLowerCase();
const riskIndicators = {
high: ['production', 'critical', 'security', 'payment', 'authentication', 'migration'],
medium: ['refactor', 'performance', 'integration', 'realtime'],
low: ['component', 'test', 'documentation', 'styling']
};
// Check risk indicators
if (this.hasKeywords(descLower, riskIndicators.high)) {
riskLevel = 'high';
} else if (this.hasKeywords(descLower, riskIndicators.medium)) {
riskLevel = 'medium';
}
return riskLevel;
}
estimateTime(description) {
const type = this.determinePrimaryType(description);
const complexity = this.assessComplexity(description);
const baseTime = this.patterns.taskTypes[type]?.avgTime || 60;
// Adjust for complexity
const complexityMultiplier = {
1: 0.7,
2: 1.0,
3: 1.4,
4: 2.0,
5: 3.0
};
const estimatedMinutes = Math.round(baseTime * complexityMultiplier[complexity]);
// Add buffer for high-risk tasks
const risk = this.assessRisk(description);
const riskBuffer = {
'high': 1.3,
'medium': 1.15,
'low': 1.0
};
return Math.round(estimatedMinutes * riskBuffer[risk]);
}
enhanceWithLearnings(analysis, taskDescription) {
// If learning system is available, enhance with historical data
if (this.learningSystem) {
const historicalData = this.learningSystem.getHistoricalData(analysis.primaryType);
if (historicalData) {
// Adjust time estimate based on historical accuracy
if (historicalData.avgActualTime) {
const accuracy = historicalData.avgEstimatedTime / historicalData.avgActualTime;
analysis.estimatedTime = Math.round(analysis.estimatedTime / accuracy);
}
// Add confidence score
analysis.confidence = historicalData.successRate || 0.8;
}
}
// Add recommendations based on analysis
analysis.recommendations = this.generateRecommendations(analysis);
return analysis;
}
generateRecommendations(analysis) {
const recommendations = [];
// High complexity tasks
if (analysis.complexity >= 4) {
recommendations.push('Consider breaking this into smaller subtasks');
recommendations.push('Plan for additional testing and validation time');
}
// High risk tasks
if (analysis.riskLevel === 'high') {
recommendations.push('Create a rollback plan before starting');
recommendations.push('Test thoroughly in development environment first');
}
// Multi-domain tasks
if (analysis.domains.length > 3) {
recommendations.push('Coordinate changes across multiple system areas');
recommendations.push('Consider impact on related components');
}
// Real-time features
if (analysis.domains.includes('real_time')) {
recommendations.push('Plan for handling connection failures');
recommendations.push('Implement proper conflict resolution');
}
return recommendations;
}
}
module.exports = TaskClassifier;