diff --git a/src/cli/simple-commands/analysis.js b/src/cli/simple-commands/analysis.js index 23d8890b13..fe2b2b5aac 100644 --- a/src/cli/simple-commands/analysis.js +++ b/src/cli/simple-commands/analysis.js @@ -58,8 +58,8 @@ async function bottleneckDetectCommand(subArgs, flags) { console.log(`🎯 Target: ${target}`); try { - // Initialize metrics system if needed - await initializeMetrics(); + // Initialize metrics system without starting monitoring + await initializeMetrics(false); // Get real bottleneck analysis const analysis = await getBottleneckAnalysis(scope, target); @@ -129,8 +129,8 @@ async function performanceReportCommand(subArgs, flags) { console.log(`📋 Format: ${format}`); try { - // Initialize metrics system if needed - await initializeMetrics(); + // Initialize metrics system without starting monitoring + await initializeMetrics(false); // Get real performance data const report = await getPerformanceReport(timeframe); diff --git a/src/cli/simple-commands/performance-metrics.js b/src/cli/simple-commands/performance-metrics.js index 23b7563f6c..3754619fa8 100644 --- a/src/cli/simple-commands/performance-metrics.js +++ b/src/cli/simple-commands/performance-metrics.js @@ -31,16 +31,21 @@ let metricsCache = { } }; +// Store interval ID for cleanup +let systemMonitoringInterval = null; + // Initialize metrics system -export async function initializeMetrics() { +export async function initializeMetrics(startMonitoring = true) { try { await fs.mkdir(METRICS_DIR, { recursive: true }); // Load existing metrics if available await loadMetricsFromDisk(); - // Start system monitoring - startSystemMonitoring(); + // Start system monitoring only if requested + if (startMonitoring) { + startSystemMonitoring(); + } return true; } catch (err) { @@ -330,8 +335,13 @@ export async function getBottleneckAnalysis(scope = 'system', target = 'all') { // System monitoring function startSystemMonitoring() { + // Clear any existing interval + if (systemMonitoringInterval) { + clearInterval(systemMonitoringInterval); + } + // Collect system metrics every 30 seconds - setInterval(async () => { + systemMonitoringInterval = setInterval(async () => { const metrics = await getSystemMetrics(); // Store system metrics @@ -355,6 +365,17 @@ function startSystemMonitoring() { // Ignore save errors } }, 30000); + + // Allow process to exit even with active interval + systemMonitoringInterval.unref(); +} + +// Stop system monitoring +export function stopSystemMonitoring() { + if (systemMonitoringInterval) { + clearInterval(systemMonitoringInterval); + systemMonitoringInterval = null; + } } // Get current system metrics @@ -407,6 +428,11 @@ async function fileExists(filepath) { } } +// Cleanup function for graceful shutdown +export function cleanup() { + stopSystemMonitoring(); +} + // Export metrics for reporting export async function exportMetrics(format = 'json') { const timestamp = Date.now();