UNPKG

ai-debug-local-mcp

Version:

🎯 ENHANCED AI GUIDANCE v4.1.2: Dramatically improved tool descriptions help AI users choose the right tools instead of 'close enough' options. Ultra-fast keyboard automation (10x speed), universal recording, multi-ecosystem debugging support, and compreh

350 lines 14.6 kB
/** * Architecture Orchestrator - Code architecture and quality analysis * * Analyzes code structure, dependencies, patterns, and suggests improvements */ export class ArchitectureOrchestrator { subAgents = { structure: 'code_structure_agent', dependencies: 'dependency_analysis_agent', patterns: 'pattern_detection_agent', quality: 'code_quality_agent', complexity: 'complexity_analysis_agent', suggestions: 'refactoring_suggestion_agent' }; async orchestrate(task) { console.error('🏗️ Architecture Orchestrator: Analyzing code architecture...'); const analysis = this.analyzeTask(task); const plan = this.createExecutionPlan(analysis); const results = await this.executePlan(plan); return this.synthesizeResults(results); } analyzeTask(task) { const keywords = (task.task || task.description || '').toLowerCase(); const analysis = { focus: task.focus || 'all', scope: task.path ? 'targeted' : 'project-wide', depth: task.depth || 3, suggestedAgents: [] }; // Determine agents based on keywords and focus if (analysis.focus === 'all' || keywords.includes('comprehensive')) { // Full architecture analysis analysis.suggestedAgents.push(this.subAgents.structure, this.subAgents.dependencies, this.subAgents.patterns, this.subAgents.quality, this.subAgents.complexity); } else { // Focused analysis switch (analysis.focus) { case 'structure': analysis.suggestedAgents.push(this.subAgents.structure, this.subAgents.complexity); break; case 'dependencies': analysis.suggestedAgents.push(this.subAgents.dependencies); break; case 'patterns': analysis.suggestedAgents.push(this.subAgents.patterns, this.subAgents.quality); break; case 'quality': analysis.suggestedAgents.push(this.subAgents.quality, this.subAgents.complexity); break; } } // Always add suggestions at the end if (!analysis.suggestedAgents.includes(this.subAgents.suggestions)) { analysis.suggestedAgents.push(this.subAgents.suggestions); } // Special keywords if (keywords.includes('smell') || keywords.includes('antipattern')) { if (!analysis.suggestedAgents.includes(this.subAgents.patterns)) { analysis.suggestedAgents.push(this.subAgents.patterns); } } if (keywords.includes('circular') || keywords.includes('coupling')) { if (!analysis.suggestedAgents.includes(this.subAgents.dependencies)) { analysis.suggestedAgents.push(this.subAgents.dependencies); } } return analysis; } createExecutionPlan(analysis) { const plan = { steps: [], parallel: true, estimatedDuration: 0 }; // Create steps for each agent analysis.suggestedAgents.forEach(agent => { switch (agent) { case this.subAgents.structure: plan.steps.push({ agent, action: 'analyze_structure', params: { depth: analysis.depth, includeMetrics: true, detectLayers: true } }); break; case this.subAgents.dependencies: plan.steps.push({ agent, action: 'analyze_dependencies', params: { checkCircular: true, analyzeVersions: true, findUnused: true } }); break; case this.subAgents.patterns: plan.steps.push({ agent, action: 'detect_patterns', params: { includeAntipatterns: true, checkBestPractices: true } }); break; case this.subAgents.quality: plan.steps.push({ agent, action: 'assess_quality', params: { metrics: ['maintainability', 'reliability', 'security'], includeHotspots: true } }); break; case this.subAgents.complexity: plan.steps.push({ agent, action: 'measure_complexity', params: { thresholds: { cyclomatic: 10, cognitive: 15 }, findHotspots: true } }); break; case this.subAgents.suggestions: plan.steps.push({ agent, action: 'generate_refactoring_suggestions', params: { prioritizeByImpact: true, includeEstimates: true } }); break; } }); plan.estimatedDuration = plan.steps.length * 6; // 6 seconds per analysis return plan; } async executePlan(plan) { const results = []; // Execute in parallel groups if specified for (const step of plan.steps) { console.log(` → Delegating to ${step.agent} for ${step.action}...`); // Mock implementation const result = { agent: step.agent, action: step.action, success: true, summary: `Completed ${step.action}`, data: this.getMockDataForAction(step.action), duration: Math.random() * 4000 + 2000 }; results.push(result); } return results; } getMockDataForAction(action) { switch (action) { case 'analyze_structure': return { layers: ['presentation', 'business', 'data'], modules: 15, avgModuleSize: 250, maxDepth: 5, violations: [ { type: 'layer_violation', from: 'data', to: 'presentation' } ] }; case 'analyze_dependencies': return { total: 45, direct: 20, circular: [ { modules: ['moduleA', 'moduleB'], severity: 'high' } ], unused: ['old-package', 'legacy-util'], outdated: 8 }; case 'detect_patterns': return { patterns: [ { name: 'Singleton', count: 3, appropriate: true }, { name: 'Factory', count: 5, appropriate: true } ], antipatterns: [ { name: 'God Object', location: 'UserService', severity: 'high' }, { name: 'Spaghetti Code', location: 'legacy/', severity: 'medium' } ] }; case 'assess_quality': return { scores: { maintainability: 72, reliability: 85, security: 78 }, hotspots: [ { file: 'api/auth.js', issues: ['complexity', 'duplication'] } ], debt: { hours: 120, currency: 'technical' } }; case 'measure_complexity': return { average: { cyclomatic: 6, cognitive: 8 }, complex: [ { function: 'processPayment', cyclomatic: 25, cognitive: 30 }, { function: 'validateUser', cyclomatic: 15, cognitive: 18 } ] }; case 'generate_refactoring_suggestions': return { suggestions: [ { title: 'Extract UserService god object', impact: 'high', effort: 'large', benefits: ['Better separation of concerns', 'Easier testing'] }, { title: 'Implement dependency injection', impact: 'medium', effort: 'medium', benefits: ['Looser coupling', 'Better testability'] } ] }; default: return {}; } } synthesizeResults(results) { const findings = { critical: [], warnings: [], info: [] }; // Process structure violations const structureResult = results.find(r => r.action === 'analyze_structure'); if (structureResult && structureResult.data?.violations?.length > 0) { structureResult.data.violations.forEach((v) => { findings.critical.push({ type: 'architecture_violation', severity: 'critical', title: `Layer violation: ${v.from} → ${v.to}`, description: 'Breaks architectural boundaries' }); }); } // Process dependencies const depResult = results.find(r => r.action === 'analyze_dependencies'); if (depResult && depResult.data?.circular?.length > 0) { depResult.data.circular.forEach((c) => { findings.critical.push({ type: 'circular_dependency', severity: 'critical', title: `Circular dependency: ${c.modules.join(' ↔ ')}`, description: 'Creates tight coupling and maintenance issues' }); }); } // Process antipatterns const patternResult = results.find(r => r.action === 'detect_patterns'); if (patternResult?.data?.antipatterns) { patternResult.data.antipatterns.forEach((ap) => { findings[ap.severity === 'high' ? 'critical' : 'warnings'].push({ type: 'antipattern', severity: ap.severity === 'high' ? 'critical' : 'warning', title: `${ap.name} in ${ap.location}`, description: 'Code smell that needs refactoring' }); }); } // Process complexity const complexityResult = results.find(r => r.action === 'measure_complexity'); if (complexityResult?.data?.complex) { complexityResult.data.complex.forEach((c) => { if (c.cyclomatic > 20) { findings.warnings.push({ type: 'high_complexity', severity: 'warning', title: `High complexity in ${c.function}`, description: `Cyclomatic complexity: ${c.cyclomatic}` }); } }); } // Get suggestions const suggestionsResult = results.find(r => r.action === 'generate_refactoring_suggestions'); const suggestions = suggestionsResult?.data?.suggestions || []; const summary = this.createSummary(results, findings); return { success: findings.critical.length === 0, summary, findings, suggestions: suggestions.slice(0, 3), nextSteps: this.determineNextSteps(findings, results), metadata: { duration: results.reduce((sum, r) => sum + r.duration, 0), agentsUsed: [...new Set(results.map(r => r.agent))], confidence: 0.88 } }; } createSummary(results, findings) { const parts = []; const qualityResult = results.find(r => r.action === 'assess_quality'); if (qualityResult?.data?.scores) { const avgScore = Object.values(qualityResult.data.scores).reduce((a, b) => a + (typeof b === 'number' ? b : 0), 0) / 3; parts.push(`Quality: ${Math.round(avgScore)}/100`); } const depResult = results.find(r => r.action === 'analyze_dependencies'); if (depResult?.data) { parts.push(`Dependencies: ${depResult.data.total} (${depResult.data.outdated} outdated)`); } if (findings.critical.length > 0) { parts.push(`⚠️ ${findings.critical.length} critical issues`); } if (qualityResult?.data?.debt) { parts.push(`Tech debt: ${qualityResult.data.debt.hours}h`); } return parts.join(' | ') || 'Architecture analysis complete'; } determineNextSteps(findings, results) { const steps = []; if (findings.critical.length > 0) { steps.push('Address critical architecture violations'); steps.push('Break circular dependencies'); } const depResult = results.find(r => r.action === 'analyze_dependencies'); if (depResult?.data?.outdated > 5) { steps.push('Update outdated dependencies'); } const qualityResult = results.find(r => r.action === 'assess_quality'); if (qualityResult?.data?.debt?.hours > 100) { steps.push('Create technical debt reduction plan'); } if (steps.length === 0) { steps.push('Set up architecture fitness functions'); steps.push('Document architectural decisions (ADRs)'); } return steps; } } //# sourceMappingURL=architecture-orchestrator.js.map