vibe_coding_tracker 0.5.14

Vibe Coding Tracker - AI coding assistant telemetry/usage parser, aggregate JSONL events into CodeAnalysis results
Documentation
use crate::cache::global_cache;
use crate::cli::TimeRange;
use crate::constants::{FastHashMap, capacity};
use crate::models::ProviderActiveDays;
use crate::utils::{collect_files_with_dates, is_gemini_chat_file, is_json_file};
use anyhow::Result;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashSet;
use std::path::Path;
use std::sync::Arc;

/// Single row of aggregated metrics grouped by model
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AggregatedAnalysisRow {
    pub model: String,
    pub edit_lines: usize,
    pub read_lines: usize,
    pub write_lines: usize,
    pub bash_count: usize,
    pub edit_count: usize,
    pub read_count: usize,
    pub todo_write_count: usize,
    pub write_count: usize,
}

/// Analysis results with provider active day counts for daily averages
pub struct AnalysisData {
    pub rows: Vec<AggregatedAnalysisRow>,
    pub provider_days: ProviderActiveDays,
}

/// Analyzes all session files across providers and aggregates file operation metrics
///
/// Scans Claude, Codex, Copilot, and Gemini session directories, aggregates tool call counts
/// and line counts by model, then returns sorted results with provider active day counts.
pub fn analyze_all_sessions(time_range: TimeRange) -> Result<AnalysisData> {
    let paths = crate::utils::resolve_paths()?;
    let mut aggregated: FastHashMap<String, AggregatedAnalysisRow> =
        FastHashMap::with_capacity(capacity::MODEL_COMBINATIONS);

    let mut claude_dates: HashSet<String> = HashSet::new();
    let mut codex_dates: HashSet<String> = HashSet::new();
    let mut copilot_dates: HashSet<String> = HashSet::new();
    let mut gemini_dates: HashSet<String> = HashSet::new();

    if paths.claude_session_dir.exists() {
        process_analysis_directory(
            &paths.claude_session_dir,
            &mut aggregated,
            &mut claude_dates,
            is_json_file,
            time_range,
        )?;
    }

    if paths.codex_session_dir.exists() {
        process_analysis_directory(
            &paths.codex_session_dir,
            &mut aggregated,
            &mut codex_dates,
            is_json_file,
            time_range,
        )?;
    }

    if paths.copilot_session_dir.exists() {
        process_analysis_directory(
            &paths.copilot_session_dir,
            &mut aggregated,
            &mut copilot_dates,
            is_json_file,
            time_range,
        )?;
    }

    if paths.gemini_session_dir.exists() {
        process_analysis_directory(
            &paths.gemini_session_dir,
            &mut aggregated,
            &mut gemini_dates,
            is_gemini_chat_file,
            time_range,
        )?;
    }

    let mut all_dates: HashSet<&String> = HashSet::new();
    all_dates.extend(claude_dates.iter());
    all_dates.extend(codex_dates.iter());
    all_dates.extend(copilot_dates.iter());
    all_dates.extend(gemini_dates.iter());

    let provider_days = ProviderActiveDays {
        claude: claude_dates.len(),
        codex: codex_dates.len(),
        copilot: copilot_dates.len(),
        gemini: gemini_dates.len(),
        total: all_dates.len(),
    };

    let mut results: Vec<AggregatedAnalysisRow> = aggregated.into_values().collect();
    results.sort_unstable_by(|a, b| a.model.cmp(&b.model));

    Ok(AnalysisData {
        rows: results,
        provider_days,
    })
}

/// Complete CodeAnalysis results organized by AI provider
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderGroupedAnalysis {
    #[serde(rename = "Claude-Code")]
    pub claude: Vec<Value>,
    #[serde(rename = "Codex")]
    pub codex: Vec<Value>,
    #[serde(rename = "Copilot-CLI")]
    pub copilot: Vec<Value>,
    #[serde(rename = "Gemini")]
    pub gemini: Vec<Value>,
}

/// Analyzes all session files and returns complete records grouped by provider
///
/// Unlike `analyze_all_sessions()` which aggregates metrics, this function preserves
/// full CodeAnalysis records for each session file.
pub fn analyze_all_sessions_by_provider(time_range: TimeRange) -> Result<ProviderGroupedAnalysis> {
    let paths = crate::utils::resolve_paths()?;

    let mut claude_results: Vec<Value> = Vec::new();
    let mut codex_results: Vec<Value> = Vec::new();
    let mut copilot_results: Vec<Value> = Vec::new();
    let mut gemini_results: Vec<Value> = Vec::new();

    // Process Claude sessions
    if paths.claude_session_dir.exists() {
        process_full_analysis_directory(
            &paths.claude_session_dir,
            &mut claude_results,
            is_json_file,
            time_range,
        )?;
    }

    // Process Codex sessions
    if paths.codex_session_dir.exists() {
        process_full_analysis_directory(
            &paths.codex_session_dir,
            &mut codex_results,
            is_json_file,
            time_range,
        )?;
    }

    // Process Copilot sessions
    if paths.copilot_session_dir.exists() {
        process_full_analysis_directory(
            &paths.copilot_session_dir,
            &mut copilot_results,
            is_json_file,
            time_range,
        )?;
    }

    // Process Gemini sessions
    if paths.gemini_session_dir.exists() {
        process_full_analysis_directory(
            &paths.gemini_session_dir,
            &mut gemini_results,
            is_gemini_chat_file,
            time_range,
        )?;
    }

    Ok(ProviderGroupedAnalysis {
        claude: claude_results,
        codex: codex_results,
        copilot: copilot_results,
        gemini: gemini_results,
    })
}

fn process_full_analysis_directory<P, F>(
    dir: P,
    results: &mut Vec<Value>,
    filter_fn: F,
    time_range: TimeRange,
) -> Result<()>
where
    P: AsRef<Path>,
    F: Copy + Fn(&Path) -> bool + Sync + Send,
{
    let dir = dir.as_ref();
    let files = collect_files_with_dates(dir, filter_fn, time_range)?;

    // Process files in parallel with caching for better performance
    // Use Arc directly to avoid deep cloning large JSON values
    let analyzed: Vec<Arc<Value>> = files
        .par_iter()
        .filter_map(
            |file_info| match global_cache().get_or_parse(&file_info.path) {
                Ok(analysis_arc) => Some(analysis_arc),
                Err(e) => {
                    eprintln!(
                        "Warning: Failed to analyze {}: {}",
                        file_info.path.display(),
                        e
                    );
                    None
                }
            },
        )
        .collect();

    // Only clone when serializing (unavoidable, but done once at the end)
    results.extend(analyzed.iter().map(|arc| (**arc).clone()));
    Ok(())
}

fn process_analysis_directory<P, F>(
    dir: P,
    aggregated: &mut FastHashMap<String, AggregatedAnalysisRow>,
    unique_dates: &mut HashSet<String>,
    filter_fn: F,
    time_range: TimeRange,
) -> Result<()>
where
    P: AsRef<Path>,
    F: Copy + Fn(&Path) -> bool + Sync + Send,
{
    let dir = dir.as_ref();
    let files = collect_files_with_dates(dir, filter_fn, time_range)?;

    // Process files in parallel with caching and collect per-file aggregations
    // Use Arc to avoid deep cloning - we only need to read fields
    let file_aggregations: Vec<(String, Arc<Value>)> = files
        .par_iter()
        .filter_map(
            |file_info| match global_cache().get_or_parse(&file_info.path) {
                Ok(analysis_arc) => Some((file_info.modified_date.clone(), analysis_arc)),
                Err(e) => {
                    eprintln!(
                        "Warning: Failed to analyze {}: {}",
                        file_info.path.display(),
                        e
                    );
                    None
                }
            },
        )
        .collect();

    // Merge parallel results sequentially (this part is fast)
    for (date, analysis_arc) in file_aggregations {
        unique_dates.insert(date);
        aggregate_analysis_result(aggregated, &analysis_arc);
    }

    Ok(())
}

fn aggregate_analysis_result(
    aggregated: &mut FastHashMap<String, AggregatedAnalysisRow>,
    analysis: &Value,
) {
    let Some(records) = analysis.get("records").and_then(|r| r.as_array()) else {
        return;
    };

    for record in records {
        let Some(record_obj) = record.as_object() else {
            continue;
        };

        let Some(conv_usage) = record_obj
            .get("conversationUsage")
            .and_then(|c| c.as_object())
        else {
            continue;
        };

        for (model, _usage) in conv_usage {
            if model.contains("<synthetic>") {
                continue;
            }

            let entry =
                aggregated
                    .entry(model.to_string())
                    .or_insert_with(|| AggregatedAnalysisRow {
                        model: model.to_string(),
                        edit_lines: 0,
                        read_lines: 0,
                        write_lines: 0,
                        bash_count: 0,
                        edit_count: 0,
                        read_count: 0,
                        todo_write_count: 0,
                        write_count: 0,
                    });

            // Extract line counts
            entry.edit_lines += record_obj
                .get("totalEditLines")
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as usize;
            entry.read_lines += record_obj
                .get("totalReadLines")
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as usize;
            entry.write_lines += record_obj
                .get("totalWriteLines")
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as usize;

            // Extract tool call counts
            if let Some(tool_calls) = record_obj.get("toolCallCounts").and_then(|t| t.as_object()) {
                entry.bash_count +=
                    tool_calls.get("Bash").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
                entry.edit_count +=
                    tool_calls.get("Edit").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
                entry.read_count +=
                    tool_calls.get("Read").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
                entry.todo_write_count += tool_calls
                    .get("TodoWrite")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0) as usize;
                entry.write_count += tool_calls
                    .get("Write")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0) as usize;
            }
        }
    }
}