mira-consciousness
Version:
Memory & Intelligence Retention Archive - Preserving The Spark
215 lines • 9.52 kB
JavaScript
/**
* Performance Analyzer - Main Orchestrator
* Coordinates all performance analysis modules
*/
import { FileSystemAnalyzer } from './FileSystemAnalyzer.js';
import { MemoryLeakDetector } from './MemoryLeakDetector.js';
import { BundleAnalyzer } from './BundleAnalyzer.js';
import { ComplexityAnalyzer } from './ComplexityAnalyzer.js';
import { CachingAnalyzer } from './CachingAnalyzer.js';
import { MemorySystemAnalyzer } from './MemorySystemAnalyzer.js';
export class PerformanceAnalyzer {
projectRoot;
constructor(projectRoot) {
this.projectRoot = projectRoot;
}
async withTimeout(promise, timeoutMs, name) {
console.log(`[PerformanceAnalyzer] Starting ${name} analysis...`);
const startTime = Date.now();
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {
const elapsed = Date.now() - startTime;
console.error(`[PerformanceAnalyzer] ${name} analysis timeout after ${elapsed}ms`);
reject(new Error(`${name} analysis timeout after ${timeoutMs}ms`));
}, timeoutMs);
});
try {
const result = await Promise.race([promise, timeoutPromise]);
const elapsed = Date.now() - startTime;
console.log(`[PerformanceAnalyzer] ${name} analysis completed in ${elapsed}ms`);
return result;
}
catch (error) {
console.warn(`[PerformanceAnalyzer] ${name} analysis failed:`, error instanceof Error ? error.message : error);
throw error;
}
}
async analyze() {
const issues = [];
console.log('Analyzing performance...');
// Run analyzers with individual timeouts (increased for larger codebases)
const analysisPromises = [
this.withTimeout(this.runFileSystemAnalysis(), 30000, 'FileSystem'),
this.withTimeout(this.runMemoryLeakDetection(), 30000, 'MemoryLeak'),
this.withTimeout(this.runBundleAnalysis(issues), 20000, 'Bundle'),
this.withTimeout(this.runComplexityAnalysis(issues), 30000, 'Complexity'),
this.withTimeout(this.runCachingAnalysis(issues), 20000, 'Caching'),
this.withTimeout(this.runMemorySystemAnalysis(issues), 20000, 'MemorySystem')
];
const results = await Promise.allSettled(analysisPromises);
// Extract successful results
const [fileSystemResult, memoryLeakResult, bundleResult, complexityResult, cachingResult, memorySystemResult] = results;
const fileSystemIssues = fileSystemResult.status === 'fulfilled' ? fileSystemResult.value : [];
const memoryLeakIssues = memoryLeakResult.status === 'fulfilled' ? memoryLeakResult.value : [];
const bundleAnalysis = bundleResult.status === 'fulfilled' ? bundleResult.value : undefined;
const complexityAnalysis = complexityResult.status === 'fulfilled' ? complexityResult.value : undefined;
const cachingAnalysis = cachingResult.status === 'fulfilled' ? cachingResult.value : undefined;
const memorySystemPerformance = memorySystemResult.status === 'fulfilled' ? memorySystemResult.value : undefined;
// Combine all issues
issues.push(...fileSystemIssues, ...memoryLeakIssues);
// Identify bottlenecks
const bottlenecks = this.identifyBottlenecks(issues, bundleAnalysis, complexityAnalysis, cachingAnalysis, memorySystemPerformance);
// Calculate overall score
const overallScore = this.calculateScore(issues, bundleAnalysis, complexityAnalysis, memorySystemPerformance, cachingAnalysis);
return {
score: overallScore,
issues: this.sortIssuesByImpact(issues),
bundleAnalysis,
complexityAnalysis,
memorySystemPerformance,
cachingAnalysis,
overallScore,
bottlenecks
};
}
async runFileSystemAnalysis() {
const analyzer = new FileSystemAnalyzer(this.projectRoot);
return analyzer.analyze();
}
async runMemoryLeakDetection() {
const detector = new MemoryLeakDetector(this.projectRoot);
return detector.analyze();
}
async runBundleAnalysis(issues) {
const analyzer = new BundleAnalyzer(this.projectRoot);
return analyzer.analyze(issues);
}
async runComplexityAnalysis(issues) {
const analyzer = new ComplexityAnalyzer(this.projectRoot);
return analyzer.analyze(issues);
}
async runCachingAnalysis(issues) {
const analyzer = new CachingAnalyzer(this.projectRoot);
return analyzer.analyze(issues);
}
async runMemorySystemAnalysis(issues) {
const analyzer = new MemorySystemAnalyzer(this.projectRoot);
return analyzer.analyze(issues);
}
identifyBottlenecks(issues, bundleAnalysis, complexityAnalysis, cachingAnalysis, memorySystemPerformance) {
const bottlenecks = [];
// High-impact issues are bottlenecks
const highImpactIssues = issues.filter(i => i.impact === 'high');
if (highImpactIssues.length > 0) {
bottlenecks.push(`${highImpactIssues.length} high-impact performance issues detected`);
}
// Bundle size bottlenecks
if (bundleAnalysis && bundleAnalysis.totalSize > 5 * 1024 * 1024) {
bottlenecks.push(`Large bundle size (${(bundleAnalysis.totalSize / 1024 / 1024).toFixed(1)}MB) affecting load time`);
}
// Complexity bottlenecks
if (complexityAnalysis && complexityAnalysis.averageComplexity > 15) {
bottlenecks.push(`High average code complexity (${complexityAnalysis.averageComplexity.toFixed(1)}) affecting maintainability`);
}
// Caching bottlenecks
if (cachingAnalysis) {
if (cachingAnalysis.riskLevel === 'poor') {
bottlenecks.push('Poor caching strategy detected - significant performance impact');
}
if (cachingAnalysis.missedOpportunities.length > 10) {
bottlenecks.push(`${cachingAnalysis.missedOpportunities.length} missed caching opportunities`);
}
}
// Memory system bottlenecks
if (memorySystemPerformance?.lightningVidmem.efficiency === 'poor') {
bottlenecks.push('Memory system performance is poor - affecting data operations');
}
// Memory leak bottlenecks
const memoryLeakIssues = issues.filter(i => i.type.includes('leak') || i.type.includes('uncleaned'));
if (memoryLeakIssues.length > 5) {
bottlenecks.push(`${memoryLeakIssues.length} potential memory leaks detected`);
}
return bottlenecks;
}
calculateScore(issues, bundleAnalysis, complexityAnalysis, memorySystemPerformance, cachingAnalysis) {
let score = 100;
// Deduct for issues
for (const issue of issues) {
switch (issue.impact) {
case 'high':
score -= 15;
break;
case 'medium':
score -= 8;
break;
case 'low':
score -= 3;
break;
}
}
// Bundle performance impact
if (bundleAnalysis) {
if (bundleAnalysis.totalSize > 10 * 1024 * 1024) {
score -= 20;
}
else if (bundleAnalysis.totalSize > 5 * 1024 * 1024) {
score -= 10;
}
else if (bundleAnalysis.totalSize < 1 * 1024 * 1024) {
score += 5;
}
// Bonus for optimized bundles
if (bundleAnalysis.duplicatedModules.length === 0) {
score += 3;
}
}
// Complexity impact
if (complexityAnalysis) {
if (complexityAnalysis.averageComplexity > 20) {
score -= 15;
}
else if (complexityAnalysis.averageComplexity > 15) {
score -= 10;
}
else if (complexityAnalysis.averageComplexity < 5) {
score += 5;
}
}
// Memory system impact
if (memorySystemPerformance) {
switch (memorySystemPerformance.lightningVidmem.efficiency) {
case 'excellent':
score += 10;
break;
case 'good':
score += 5;
break;
case 'fair':
score -= 5;
break;
case 'poor':
score -= 15;
break;
}
}
// Caching impact
if (cachingAnalysis) {
// Use the pre-calculated caching score
const cachingImpact = (cachingAnalysis.overallCachingScore - 50) / 5;
score += cachingImpact;
}
// Ensure score is within bounds
return Math.max(0, Math.min(100, Math.round(score)));
}
sortIssuesByImpact(issues) {
const impactOrder = { high: 3, medium: 2, low: 1 };
return issues.sort((a, b) => {
const impactDiff = impactOrder[b.impact] - impactOrder[a.impact];
if (impactDiff !== 0)
return impactDiff;
// Secondary sort by type
return a.type.localeCompare(b.type);
});
}
}
//# sourceMappingURL=PerformanceAnalyzer.js.map