import { printSuccess, printError, printWarning, callRuvSwarmMCP, checkRuvSwarmAvailable, } from '../utils.js'; import { promises as fs } from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; import { dirname } from 'path'; import { initializeMetrics, getPerformanceReport, getBottleneckAnalysis, exportMetrics } from './performance-metrics.js'; import { getRealTokenUsage, calculateCost, generateOptimizationSuggestions, generateTokenUsageReport, getAgentIcon, trackTokens } from './token-tracker.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); async function setupTelemetry() { console.log(`\nšŸ”§ TELEMETRY SETUP FOR TOKEN TRACKING\n`); console.log(`${'═'.repeat(60)}\n`); // Check current status const currentValue = process.env.CLAUDE_CODE_ENABLE_TELEMETRY; const isEnabled = currentValue === '1'; console.log(`šŸ“Š Current Status: ${isEnabled ? 'āœ… ENABLED' : 'āŒ DISABLED'}`); console.log(` Environment Variable: CLAUDE_CODE_ENABLE_TELEMETRY=${currentValue || 'not set'}\n`); if (!isEnabled) { // Set the environment variable for current session process.env.CLAUDE_CODE_ENABLE_TELEMETRY = '1'; console.log(`āœ… Telemetry ENABLED for this session!\n`); // Create or update .env file const envPath = path.join(process.cwd(), '.env'); let envContent = ''; try { envContent = await fs.readFile(envPath, 'utf-8'); } catch (err) { // .env doesn't exist yet } // Check if telemetry is already in .env if (!envContent.includes('CLAUDE_CODE_ENABLE_TELEMETRY')) { envContent += `\n# Enable token tracking for Claude API calls\nCLAUDE_CODE_ENABLE_TELEMETRY=1\n`; try { await fs.writeFile(envPath, envContent); console.log(`šŸ“ Updated .env file with telemetry setting`); } catch (err) { console.log(`āš ļø Could not update .env file: ${err.message}`); } } // Also add to shell profile for persistence console.log(`\nšŸ“Œ To make this permanent, add to your shell profile:`); console.log(` ${'-'.repeat(50)}`); console.log(` echo 'export CLAUDE_CODE_ENABLE_TELEMETRY=1' >> ~/.bashrc`); console.log(` ${'-'.repeat(50)}\n`); } // Initialize token tracking directory const metricsDir = path.join(process.cwd(), '.claude-flow', 'metrics'); try { await fs.mkdir(metricsDir, { recursive: true }); console.log(`šŸ“ Token tracking directory: ${metricsDir}`); } catch (err) { // Directory already exists } // Check for existing token data const tokenFile = path.join(metricsDir, 'token-usage.json'); try { const data = await fs.readFile(tokenFile, 'utf-8'); const tokenData = JSON.parse(data); console.log(`\nšŸ“Š Existing token data found:`); console.log(` • Total tokens tracked: ${tokenData.totals?.total || 0}`); console.log(` • Sessions recorded: ${Object.keys(tokenData.sessions || {}).length}`); } catch (err) { console.log(`\nšŸ“Š No existing token data (will be created on first use)`); } console.log(`\nšŸš€ NEXT STEPS:`); console.log(` 1. Run Claude commands with --claude flag`); console.log(` 2. Example: ./claude-flow swarm "analyze code" --claude`); console.log(` 3. Check usage: ./claude-flow analysis token-usage --breakdown`); console.log(`\n${'═'.repeat(60)}`); printSuccess(`Telemetry setup complete!`); } export async function analysisAction(subArgs, flags) { const subcommand = subArgs[0]; const options = flags; if (options.help || options.h || !subcommand) { showAnalysisHelp(); return; } // Handle telemetry setup if (subcommand === 'setup-telemetry' || options['enable-telemetry']) { await setupTelemetry(); if (subcommand === 'setup-telemetry') return; } try { switch (subcommand) { case 'bottleneck-detect': await bottleneckDetectCommand(subArgs, flags); break; case 'performance-report': await performanceReportCommand(subArgs, flags); break; case 'token-usage': await tokenUsageCommand(subArgs, flags); break; case 'claude-monitor': await claudeMonitorCommand(subArgs, flags); break; case 'claude-cost': await claudeCostCommand(subArgs, flags); break; default: printError(`Unknown analysis command: ${subcommand}`); showAnalysisHelp(); } } catch (err) { printError(`Analysis command failed: ${err.message}`); } } async function bottleneckDetectCommand(subArgs, flags) { const options = flags; const scope = options.scope || 'system'; const target = options.target || 'all'; console.log(`šŸ” Detecting performance bottlenecks...`); console.log(`šŸ“Š Scope: ${scope}`); console.log(`šŸŽÆ Target: ${target}`); try { // Initialize metrics system without starting monitoring await initializeMetrics(false); // Get real bottleneck analysis const analysis = await getBottleneckAnalysis(scope, target); printSuccess(`āœ… Bottleneck analysis completed`); console.log(`\nšŸ“Š BOTTLENECK ANALYSIS RESULTS:`); analysis.bottlenecks.forEach((bottleneck) => { const icon = bottleneck.severity === 'critical' ? 'šŸ”“' : bottleneck.severity === 'warning' ? '🟔' : '🟢'; console.log( ` ${icon} ${bottleneck.severity.toUpperCase()}: ${bottleneck.component} (${bottleneck.metric})`, ); // Show details if available if (bottleneck.details) { bottleneck.details.forEach(detail => { console.log(` - ${detail.type || detail.id}: ${detail.duration}s`); }); } }); if (analysis.recommendations.length > 0) { console.log(`\nšŸ’” RECOMMENDATIONS:`); analysis.recommendations.forEach((rec) => { console.log(` • ${rec}`); }); } console.log(`\nšŸ“Š PERFORMANCE METRICS:`); console.log(` • Analysis duration: ${analysis.analysisDuration.toFixed(2)}ms`); console.log(` • Confidence score: ${(analysis.confidenceScore * 100).toFixed(0)}%`); console.log(` • Issues detected: ${analysis.issuesDetected}`); // Save detailed report const reportPath = path.join(process.cwd(), 'analysis-reports', `bottleneck-${Date.now()}.json`); await fs.mkdir(path.dirname(reportPath), { recursive: true }); await fs.writeFile(reportPath, JSON.stringify(analysis, null, 2)); console.log(`\nšŸ“„ Detailed report saved to: ${reportPath}`); } catch (err) { printError(`Bottleneck analysis failed: ${err.message}`); console.log('\nFalling back to simulated analysis...'); // Fallback to simulated data console.log(`\nšŸ“Š BOTTLENECK ANALYSIS RESULTS (SIMULATED):`); console.log(` šŸ”“ CRITICAL: Memory usage in agent spawn process (85% utilization)`); console.log(` 🟔 WARNING: Task queue processing (12s avg)`); console.log(` 🟢 GOOD: Neural training pipeline (optimal)`); console.log(` 🟢 GOOD: Swarm coordination latency (within limits)`); } } async function performanceReportCommand(subArgs, flags) { const options = flags; const timeframe = options.timeframe || '24h'; const format = options.format || 'summary'; console.log(`šŸ“ˆ Generating performance report...`); console.log(`ā° Timeframe: ${timeframe}`); console.log(`šŸ“‹ Format: ${format}`); try { // Initialize metrics system without starting monitoring await initializeMetrics(false); // Get real performance data const report = await getPerformanceReport(timeframe); printSuccess(`āœ… Performance report generated`); console.log(`\nšŸ“Š PERFORMANCE SUMMARY (${timeframe}):`); console.log(` šŸš€ Total tasks executed: ${report.summary.totalTasks}`); console.log(` āœ… Success rate: ${report.summary.successRate.toFixed(1)}%`); console.log(` ā±ļø Average execution time: ${report.summary.avgDuration.toFixed(1)}s`); console.log(` šŸ¤– Agents spawned: ${report.summary.agentsSpawned}`); console.log(` šŸ’¾ Memory efficiency: ${report.summary.memoryEfficiency.toFixed(0)}%`); console.log(` 🧠 Neural learning events: ${report.summary.neuralEvents}`); // Show trends if available if (report.trends) { console.log(`\nšŸ“ˆ TRENDS:`); if (report.trends.successRateChange !== 0) { const trend = report.trends.successRateChange > 0 ? 'improved' : 'decreased'; console.log(` • Task success rate ${trend} ${Math.abs(report.trends.successRateChange).toFixed(1)}% vs previous period`); } if (report.trends.durationChange !== 0) { const trend = report.trends.durationChange < 0 ? 'reduced' : 'increased'; console.log(` • Average execution time ${trend} by ${Math.abs(report.trends.durationChange / 1000).toFixed(1)}s`); } if (report.trends.taskVolumeChange !== 0) { const trend = report.trends.taskVolumeChange > 0 ? 'increased' : 'decreased'; const percent = Math.abs((report.trends.taskVolumeChange / report.summary.totalTasks) * 100).toFixed(0); console.log(` • Task volume ${trend} ${percent}%`); } } if (format === 'detailed' && report.agentMetrics) { console.log(`\nšŸ“Š DETAILED METRICS:`); console.log(` Agent Performance:`); Object.entries(report.agentMetrics).forEach(([type, metrics]) => { console.log(` - ${type} agents: ${metrics.successRate.toFixed(0)}% success, ${(metrics.avgDuration / 1000).toFixed(1)}s avg`); }); } // Export full report const reportPath = await exportMetrics(format === 'json' ? 'json' : 'html'); console.log(`\nšŸ“„ Full report: ${reportPath}`); } catch (err) { printError(`Failed to generate performance report: ${err.message}`); printWarning('Showing simulated data as fallback...'); // Fallback to simulated data console.log(`\nšŸ“Š PERFORMANCE SUMMARY (${timeframe}) - SIMULATED:`); console.log(` šŸš€ Total tasks executed: 127`); console.log(` āœ… Success rate: 94.5%`); console.log(` ā±ļø Average execution time: 8.3s`); console.log(` šŸ¤– Agents spawned: 23`); console.log(` šŸ’¾ Memory efficiency: 78%`); console.log(` 🧠 Neural learning events: 45`); } } async function tokenUsageCommand(subArgs, flags) { const options = flags; const agent = options.agent || 'all'; const breakdown = options.breakdown || false; const costAnalysis = options['cost-analysis'] || false; console.log(`šŸ”¢ Analyzing token usage...`); console.log(`šŸ¤– Agent filter: ${agent}`); console.log(`šŸ“Š Include breakdown: ${breakdown ? 'Yes' : 'No'}`); console.log(`šŸ’° Include cost analysis: ${costAnalysis ? 'Yes' : 'No'}`); try { // Get real token usage from Claude Code metrics const tokenData = await getRealTokenUsage(agent); printSuccess(`āœ… Token usage analysis completed`); // Check if we have any data if (tokenData.total === 0) { // Show instructions when no data available await showSimulatedTokenUsage(breakdown, costAnalysis); // Still generate empty report for consistency const reportPath = await generateTokenUsageReport(tokenData, agent); console.log(`\nšŸ“„ Detailed usage log: ${reportPath}`); } else { // Display real token usage console.log(`\nšŸ”¢ TOKEN USAGE SUMMARY:`); console.log(` šŸ“ Total tokens consumed: ${tokenData.total.toLocaleString()}`); console.log(` šŸ“„ Input tokens: ${tokenData.input.toLocaleString()} (${((tokenData.input / tokenData.total) * 100).toFixed(1)}%)`); console.log(` šŸ“¤ Output tokens: ${tokenData.output.toLocaleString()} (${((tokenData.output / tokenData.total) * 100).toFixed(1)}%)`); if (costAnalysis) { const cost = calculateCost(tokenData); console.log(` šŸ’° Estimated cost: $${cost.total.toFixed(2)}`); console.log(` Input cost: $${cost.input.toFixed(2)}`); console.log(` Output cost: $${cost.output.toFixed(2)}`); } if (breakdown && tokenData.byAgent) { console.log(`\nšŸ“Š BREAKDOWN BY AGENT TYPE:`); Object.entries(tokenData.byAgent).forEach(([agentType, usage]) => { const percentage = ((usage / tokenData.total) * 100).toFixed(1); const icon = getAgentIcon(agentType); console.log(` ${icon} ${agentType}: ${usage.toLocaleString()} tokens (${percentage}%)`); }); console.log(`\nšŸ’” OPTIMIZATION OPPORTUNITIES:`); const opportunities = generateOptimizationSuggestions(tokenData); opportunities.forEach(suggestion => { console.log(` • ${suggestion}`); }); } // Generate real CSV report const reportPath = await generateTokenUsageReport(tokenData, agent); console.log(`\nšŸ“„ Detailed usage log: ${reportPath}`); } } catch (err) { printError(`Failed to get real token usage: ${err.message}`); printWarning('Falling back to help instructions...'); // Fallback to instructions await showSimulatedTokenUsage(breakdown, costAnalysis); } } function showAnalysisHelp() { console.log(` šŸ“Š Analysis Commands - Performance & Usage Analytics USAGE: claude-flow analysis [options] COMMANDS: setup-telemetry Configure token tracking for Claude API calls bottleneck-detect Detect performance bottlenecks in the system performance-report Generate comprehensive performance reports token-usage Analyze token consumption and costs claude-monitor Monitor Claude session for real-time token usage claude-cost Get current Claude session cost and usage GLOBAL OPTIONS: --enable-telemetry Enable token tracking for this session --help, -h Show this help message TELEMETRY SETUP: claude-flow analysis setup-telemetry This command will: • Set CLAUDE_CODE_ENABLE_TELEMETRY=1 in your environment • Create .env file with telemetry settings • Initialize token tracking directory • Show current telemetry status BOTTLENECK DETECT OPTIONS: --scope Analysis scope (default: system) Options: system, swarm, agent, task, memory --target Specific target to analyze (default: all) Examples: agent-id, swarm-id, task-type PERFORMANCE REPORT OPTIONS: --timeframe