terraphim-session-analyzer 1.16.34

Analyze AI coding assistant session logs to identify agent usage patterns
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
mod analyzer;
mod models;
mod parser;
mod patterns;
mod reporter;
mod tool_analyzer;

use models::SessionAnalysis;

use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use colored::*;
use std::io::IsTerminal;
use std::path::PathBuf;
use tracing::{info, warn};

use analyzer::Analyzer;
use parser::SessionParser;
use patterns::{AhoCorasickMatcher, PatternMatcher, load_all_patterns};
use reporter::Reporter;

#[derive(Parser)]
#[command(name = "terraphim-session-analyzer")]
#[command(
    version,
    about = "Analyze AI coding assistant session logs to identify agent usage patterns"
)]
#[command(long_about = r#"
Terraphim Session Analyzer (tsa/cla) - Analyze AI coding assistant session logs

Supported AI assistants:
  - Claude Code    ($HOME/.claude/projects/)
  - OpenCode       ($HOME/.local/state/opencode/)
  - Cursor         ($HOME/.cursor/)
  - Aider          ($HOME/.aider.chat.history.md)
  - Codex          ($HOME/.codex/)

This tool parses session logs and identifies which AI agents were used,
tool usage patterns, and development insights.

Examples:
  tsa analyze                                          # Analyze all sessions
  tsa analyze --target "STATUS_IMPLEMENTATION.md"     # Find specific file
  tsa list                                            # List available sessions
  tsa tools --show-chains                             # Show tool usage patterns
  tsa analyze --format json --output report.json     # Export to JSON

Aliases: tsa (new), cla (legacy)
"#)]
struct Cli {
    /// Use verbose output
    #[arg(short, long, global = true)]
    verbose: bool,

    /// Session directory (defaults to auto-detect from supported AI assistants)
    #[arg(short = 'd', long, env = "TSA_SESSION_DIR", global = true)]
    session_dir: Option<PathBuf>,

    /// Disable colored output
    #[arg(long, global = true)]
    no_color: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Analyze sessions to identify agent usage
    Analyze {
        /// Session file or directory to analyze (auto-detects AI assistant directories)
        path: Option<String>,

        /// Target file to track (e.g., "STATUS_IMPLEMENTATION.md")
        #[arg(short, long)]
        target: Option<String>,

        /// Output format
        #[arg(short = 'f', long, default_value = "terminal")]
        format: OutputFormat,

        /// Output file path
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Show only sessions that modified files
        #[arg(long)]
        files_only: bool,
    },

    /// List available sessions
    List {
        /// Show detailed information about each session
        #[arg(long)]
        detailed: bool,

        /// Filter by project directory
        #[arg(short, long)]
        project: Option<String>,
    },

    /// Show summary statistics across all sessions
    Summary {
        /// Number of top agents to show
        #[arg(short, long, default_value = "10")]
        top: usize,
    },

    /// Generate timeline visualization (HTML)
    Timeline {
        /// Session file to visualize
        session: PathBuf,

        /// Output HTML file
        #[arg(short, long, default_value = "timeline.html")]
        output: PathBuf,
    },

    /// Watch for new sessions in real-time
    Watch {
        /// Directory to watch (auto-detects AI assistant directories)
        path: Option<String>,

        /// Refresh interval in seconds
        #[arg(short, long, default_value = "5")]
        interval: u64,
    },

    /// Analyze tool usage patterns across sessions
    Tools {
        /// Session file or directory to analyze
        path: Option<String>,

        /// Output format
        #[arg(short = 'f', long, default_value = "terminal")]
        format: OutputFormat,

        /// Output file path
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Filter by tool name
        #[arg(short, long)]
        tool: Option<String>,

        /// Filter by agent type
        #[arg(short, long)]
        agent: Option<String>,

        /// Show tool chains (sequences of tools used together)
        #[arg(long)]
        show_chains: bool,

        /// Show correlation matrix between agents and tools
        #[arg(long)]
        show_correlation: bool,

        /// Minimum usage count to display
        #[arg(long, default_value = "1")]
        min_usage: u32,

        /// Sort by: frequency, recent, alphabetical
        #[arg(long, default_value = "frequency")]
        sort_by: SortBy,

        /// Knowledge graph search query (e.g., "deploy OR publish OR release")
        #[arg(long)]
        #[cfg(feature = "terraphim")]
        kg_search: Option<String>,
    },
}

#[derive(Debug, Clone, ValueEnum)]
enum OutputFormat {
    Terminal,
    Json,
    Csv,
    Markdown,
    Html,
}

#[derive(Debug, Clone, ValueEnum)]
enum SortBy {
    Frequency,
    Recent,
    Alphabetical,
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    // Initialize tracing
    let filter = if cli.verbose { "debug" } else { "info" };

    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_target(false)
        .with_level(false)
        .init();

    // Disable colors if requested or if not in terminal
    if cli.no_color || !std::io::stdout().is_terminal() {
        colored::control::set_override(false);
    }

    match cli.command {
        Commands::Analyze {
            ref path,
            ref target,
            ref format,
            ref output,
            files_only,
        } => {
            let analyzer = create_analyzer(path.clone(), &cli)?;
            let mut analyses = analyzer.analyze(target.as_deref())?;

            if files_only {
                analyses.retain(|a| !a.file_to_agents.is_empty());
            }

            if analyses.is_empty() {
                println!("{}", "No matching sessions found".yellow());
                return Ok(());
            }

            let reporter = Reporter::new().with_colors(!cli.no_color);

            match &format {
                OutputFormat::Terminal => {
                    reporter.print_terminal(&analyses);
                }
                OutputFormat::Json => {
                    let json = reporter.to_json(&analyses)?;
                    write_output(&json, output.clone())?;
                }
                OutputFormat::Csv => {
                    let csv = reporter.to_csv(&analyses)?;
                    write_output(&csv, output.clone())?;
                }
                OutputFormat::Markdown => {
                    let markdown = reporter.to_markdown(&analyses)?;
                    write_output(&markdown, output.clone())?;
                }
                OutputFormat::Html => {
                    println!("{}", "HTML format not yet implemented".yellow());
                }
            }
        }

        Commands::List {
            detailed,
            ref project,
        } => {
            list_sessions(&cli, detailed, project.as_deref())?;
        }

        Commands::Summary { top } => {
            show_summary(&cli, top)?;
        }

        Commands::Timeline { session, output } => {
            generate_timeline(session, output)?;
        }

        Commands::Watch { ref path, interval } => {
            watch_sessions(path.as_deref(), &cli, interval)?;
        }

        Commands::Tools {
            ref path,
            ref format,
            ref output,
            ref tool,
            ref agent,
            show_chains,
            show_correlation,
            min_usage,
            ref sort_by,
            #[cfg(feature = "terraphim")]
            ref kg_search,
        } => {
            analyze_tools(
                path.as_deref(),
                &cli,
                format,
                output.clone(),
                tool.as_deref(),
                agent.as_deref(),
                show_chains,
                show_correlation,
                min_usage,
                sort_by,
                #[cfg(feature = "terraphim")]
                kg_search.as_deref(),
            )?;
        }
    }

    Ok(())
}

fn create_analyzer(path: Option<String>, cli: &Cli) -> Result<Analyzer> {
    if let Some(path_str) = path {
        let path = expand_home_dir(&path_str)?;
        Analyzer::new(path)
    } else if let Some(session_dir) = &cli.session_dir {
        Analyzer::new(session_dir)
    } else {
        Analyzer::from_default_location()
    }
}

fn expand_home_dir(path: &str) -> Result<PathBuf> {
    if path.starts_with("$HOME") || path.starts_with("~") {
        let home = home::home_dir().context("Could not find home directory")?;
        let relative = path
            .trim_start_matches("$HOME")
            .trim_start_matches("~")
            .trim_start_matches('/');
        Ok(home.join(relative))
    } else {
        Ok(PathBuf::from(path))
    }
}

fn write_output(content: &str, output: Option<PathBuf>) -> Result<()> {
    match output {
        Some(path) => {
            std::fs::write(&path, content)
                .with_context(|| format!("Failed to write to {}", path.display()))?;
            info!("Output written to: {}", path.display());
        }
        None => {
            print!("{}", content);
        }
    }
    Ok(())
}

fn list_sessions(cli: &Cli, detailed: bool, project_filter: Option<&str>) -> Result<()> {
    let analyzer = create_analyzer(None, cli)?;
    let analyses = analyzer.analyze(None)?;

    if analyses.is_empty() {
        println!("{}", "No sessions found".yellow());
        return Ok(());
    }

    println!("{}", "📋 Available Sessions:".bold().cyan());
    println!();

    for analysis in &analyses {
        // Apply project filter if specified
        if let Some(filter) = &project_filter {
            if !analysis.project_path.contains(filter) {
                continue;
            }
        }

        println!("{} {}", "Session:".bold(), analysis.session_id.yellow());
        println!(
            "  {} {}",
            "Project:".dimmed(),
            analysis.project_path.green()
        );
        println!("  {} {}ms", "Duration:".dimmed(), analysis.duration_ms);

        if detailed {
            println!("  {} {}", "Agents:".dimmed(), analysis.agents.len());
            println!("  {} {}", "Files:".dimmed(), analysis.file_to_agents.len());
            println!(
                "  {} {}",
                "Start:".dimmed(),
                analysis.start_time.strftime("%Y-%m-%d %H:%M:%S")
            );

            if !analysis.agents.is_empty() {
                let agent_types: Vec<_> = analysis
                    .agents
                    .iter()
                    .map(|a| &a.agent_type)
                    .collect::<std::collections::HashSet<_>>()
                    .into_iter()
                    .collect();
                let agent_types_str: Vec<String> =
                    agent_types.iter().map(|s| s.to_string()).collect();
                println!(
                    "  {} {}",
                    "Agent types:".dimmed(),
                    agent_types_str.join(", ").cyan()
                );
            }
        }

        println!();
    }

    let filtered_count = if project_filter.is_some() {
        analyses
            .iter()
            .filter(|a| {
                project_filter
                    .as_ref()
                    .map_or(true, |f| a.project_path.contains(f))
            })
            .count()
    } else {
        analyses.len()
    };

    println!(
        "{} {} sessions",
        "Total:".bold(),
        filtered_count.to_string().yellow()
    );

    Ok(())
}

fn show_summary(cli: &Cli, top_count: usize) -> Result<()> {
    let analyzer = create_analyzer(None, cli)?;
    let summary = analyzer.get_summary_stats()?;

    println!("{}", "📈 Summary Statistics:".bold().cyan());
    println!();

    println!(
        "{} {}",
        "Total sessions:".bold(),
        summary.total_sessions.to_string().yellow()
    );
    println!(
        "{} {}",
        "Total agent invocations:".bold(),
        summary.total_agents.to_string().yellow()
    );
    println!(
        "{} {}",
        "Total files modified:".bold(),
        summary.total_files.to_string().yellow()
    );
    println!(
        "{} {}",
        "Unique agent types:".bold(),
        summary.unique_agent_types.to_string().yellow()
    );

    println!("\n{}", "🏆 Most Active Agents:".bold());
    for (i, (agent, count)) in summary
        .most_active_agents
        .iter()
        .take(top_count)
        .enumerate()
    {
        let reporter = Reporter::new();
        println!(
            "  {}. {} {} ({}x)",
            (i + 1).to_string().dimmed(),
            reporter.format_agent_icon(agent),
            agent.cyan(),
            count.to_string().yellow()
        );
    }

    Ok(())
}

fn generate_timeline(session_path: PathBuf, output_path: PathBuf) -> Result<()> {
    info!(
        "Generating timeline for session: {}",
        session_path.display()
    );

    let analyzer = Analyzer::new(&session_path)?;
    let analyses = analyzer.analyze(None)?;

    if analyses.is_empty() {
        return Err(anyhow::anyhow!(
            "No valid sessions found in {}",
            session_path.display()
        ));
    }

    let analysis = &analyses[0];

    // Generate simple HTML timeline
    let html = generate_timeline_html(analysis)?;

    std::fs::write(&output_path, html)
        .with_context(|| format!("Failed to write timeline to {}", output_path.display()))?;

    println!(
        "{} Timeline generated: {}",
        "".green(),
        output_path.display().to_string().yellow()
    );

    Ok(())
}

fn generate_timeline_html(analysis: &SessionAnalysis) -> Result<String> {
    let mut html = String::new();

    html.push_str(
        r#"<!DOCTYPE html>
<html>
<head>
    <title>Claude Session Timeline</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .timeline { border-left: 3px solid #ccc; padding-left: 20px; margin: 20px 0; }
        .event { margin-bottom: 20px; position: relative; }
        .event::before {
            content: '';
            position: absolute;
            left: -26px;
            top: 5px;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #007acc;
        }
        .time { color: #666; font-size: 0.9em; }
        .agent { font-weight: bold; color: #007acc; }
        .description { margin-top: 5px; color: #333; }
    </style>
</head>
<body>
    <h1>Claude Session Timeline</h1>
    <p><strong>Session:</strong> "#,
    );

    html.push_str(&analysis.session_id);
    html.push_str("</p>\n    <p><strong>Project:</strong> ");
    html.push_str(&analysis.project_path);
    html.push_str("</p>\n\n    <div class=\"timeline\">\n");

    for agent in &analysis.agents {
        html.push_str("        <div class=\"event\">\n");
        html.push_str(&format!(
            "            <div class=\"time\">{}</div>\n",
            agent.timestamp.strftime("%H:%M:%S")
        ));
        html.push_str(&format!(
            "            <div class=\"agent\">{}</div>\n",
            agent.agent_type
        ));
        html.push_str(&format!(
            "            <div class=\"description\">{}</div>\n",
            agent.task_description
        ));
        html.push_str("        </div>\n");
    }

    html.push_str("    </div>\n</body>\n</html>");

    Ok(html)
}

fn watch_sessions(path: Option<&str>, cli: &Cli, interval: u64) -> Result<()> {
    let watch_path = if let Some(p) = path {
        expand_home_dir(p)?
    } else if let Some(session_dir) = &cli.session_dir {
        session_dir.clone()
    } else {
        let home = home::home_dir().context("Could not find home directory")?;
        home.join(".claude").join("projects")
    };

    println!(
        "{} Watching for new sessions in: {}",
        "👀".cyan(),
        watch_path.display().to_string().green()
    );
    println!("Press Ctrl+C to stop...\n");

    let mut last_count = 0;

    loop {
        match Analyzer::new(&watch_path) {
            Ok(analyzer) => {
                match analyzer.analyze(None) {
                    Ok(analyses) => {
                        let current_count = analyses.len();
                        if current_count > last_count {
                            let new_sessions = current_count - last_count;
                            println!(
                                "{} {} new session(s) detected",
                                "🆕".green(),
                                new_sessions.to_string().yellow()
                            );

                            // Show details of new sessions
                            for analysis in analyses.iter().skip(last_count) {
                                println!(
                                    "  {} {} - {} agents, {} files",
                                    "Session:".dimmed(),
                                    analysis.session_id.yellow(),
                                    analysis.agents.len(),
                                    analysis.file_to_agents.len()
                                );
                            }
                        }
                        last_count = current_count;
                    }
                    Err(e) => {
                        warn!("Failed to analyze sessions: {}", e);
                    }
                }
            }
            Err(e) => {
                warn!("Failed to create analyzer: {}", e);
            }
        }

        std::thread::sleep(std::time::Duration::from_secs(interval));
    }
}

/// Convert local ToolCategory to library ToolCategory
#[cfg(feature = "terraphim")]
fn convert_tool_category(cat: &models::ToolCategory) -> terraphim_session_analyzer::ToolCategory {
    use models::ToolCategory as Local;
    use terraphim_session_analyzer::ToolCategory as Lib;
    match cat {
        Local::PackageManager => Lib::PackageManager,
        Local::BuildTool => Lib::BuildTool,
        Local::Testing => Lib::Testing,
        Local::Linting => Lib::Linting,
        Local::Git => Lib::Git,
        Local::CloudDeploy => Lib::CloudDeploy,
        Local::Database => Lib::Database,
        Local::Other(s) => Lib::Other(s.clone()),
    }
}

/// Convert local ToolInvocation to library ToolInvocation for KG module
#[cfg(feature = "terraphim")]
fn convert_to_lib_invocation(
    inv: &models::ToolInvocation,
) -> terraphim_session_analyzer::ToolInvocation {
    terraphim_session_analyzer::ToolInvocation {
        timestamp: inv.timestamp,
        tool_name: inv.tool_name.clone(),
        tool_category: convert_tool_category(&inv.tool_category),
        command_line: inv.command_line.clone(),
        arguments: inv.arguments.clone(),
        flags: inv.flags.clone(),
        exit_code: inv.exit_code,
        agent_context: inv.agent_context.clone(),
        session_id: inv.session_id.clone(),
        message_id: inv.message_id.clone(),
    }
}

/// Calculate tool chains from invocations
fn calculate_tool_chains(invocations: &[models::ToolInvocation]) -> Vec<models::ToolChain> {
    use std::collections::HashMap;

    // Group invocations by session
    let mut session_tools: HashMap<String, Vec<&models::ToolInvocation>> = HashMap::new();
    for inv in invocations {
        session_tools
            .entry(inv.session_id.clone())
            .or_default()
            .push(inv);
    }

    // Find common sequences (2-tool chains)
    let mut chain_freq: HashMap<(String, String), ChainData> = HashMap::new();

    for tools in session_tools.values() {
        let mut sorted_tools = tools.clone();
        sorted_tools.sort_by_key(|t| t.timestamp);

        for window in sorted_tools.windows(2) {
            let key = (window[0].tool_name.clone(), window[1].tool_name.clone());

            let time_diff = window[1].timestamp - window[0].timestamp;
            let time_diff_ms = time_diff
                .total(jiff::Unit::Millisecond)
                .unwrap_or(0.0)
                .abs();

            // Only consider tools within 5 minutes of each other
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            if time_diff_ms <= 300_000.0 {
                let entry = chain_freq.entry(key).or_insert_with(|| ChainData {
                    frequency: 0,
                    total_time_ms: 0,
                    success_count: 0,
                    total_count: 0,
                    agents: std::collections::HashSet::new(),
                });

                entry.frequency += 1;
                entry.total_time_ms += time_diff_ms as u64;
                entry.total_count += 1;

                if window[1].exit_code == Some(0) {
                    entry.success_count += 1;
                }

                if let Some(ref agent) = window[1].agent_context {
                    entry.agents.insert(agent.clone());
                }
            }
        }
    }

    // Convert to ToolChain structs, filter by frequency >= 2
    let mut chains: Vec<models::ToolChain> = chain_freq
        .into_iter()
        .filter(|(_, data)| data.frequency >= 2)
        .map(|((tool1, tool2), data)| {
            #[allow(clippy::cast_precision_loss)]
            let avg_time = data.total_time_ms / u64::from(data.total_count.max(1));
            #[allow(clippy::cast_precision_loss)]
            let success_rate = if data.total_count > 0 {
                data.success_count as f32 / data.total_count as f32
            } else {
                0.0
            };

            models::ToolChain {
                tools: vec![tool1, tool2],
                frequency: data.frequency,
                average_time_between_ms: avg_time,
                typical_agent: data.agents.iter().next().cloned(),
                success_rate,
            }
        })
        .collect();

    // Sort by frequency
    chains.sort_by(|a, b| b.frequency.cmp(&a.frequency));
    chains.truncate(10); // Top 10 chains

    chains
}

struct ChainData {
    frequency: u32,
    total_time_ms: u64,
    success_count: u32,
    total_count: u32,
    agents: std::collections::HashSet<String>,
}

/// Calculate agent-tool correlations
/// TODO: Remove in Phase 2 Part 2 - now handled by Analyzer::calculate_agent_tool_correlations
#[allow(dead_code)]
fn calculate_agent_tool_correlations(
    invocations: &[models::ToolInvocation],
) -> Vec<models::AgentToolCorrelation> {
    use std::collections::HashMap;

    // Group by (agent, tool)
    let mut correlation_data: HashMap<(String, String), CorrelationData> = HashMap::new();

    for inv in invocations {
        if let Some(ref agent) = inv.agent_context {
            let key = (agent.clone(), inv.tool_name.clone());
            let entry = correlation_data
                .entry(key)
                .or_insert_with(|| CorrelationData {
                    usage_count: 0,
                    success_count: 0,
                    sessions: std::collections::HashSet::new(),
                });

            entry.usage_count += 1;
            entry.sessions.insert(inv.session_id.clone());

            if inv.exit_code == Some(0) {
                entry.success_count += 1;
            }
        }
    }

    // Convert to correlation structs
    let mut correlations: Vec<models::AgentToolCorrelation> = correlation_data
        .into_iter()
        .map(|((agent, tool), data)| {
            #[allow(clippy::cast_precision_loss)]
            let success_rate = if data.usage_count > 0 {
                data.success_count as f32 / data.usage_count as f32
            } else {
                0.0
            };

            #[allow(clippy::cast_precision_loss)]
            let avg_per_session = if !data.sessions.is_empty() {
                data.usage_count as f32 / data.sessions.len() as f32
            } else {
                0.0
            };

            models::AgentToolCorrelation {
                agent_type: agent,
                tool_name: tool,
                usage_count: data.usage_count,
                success_rate,
                average_invocations_per_session: avg_per_session,
            }
        })
        .collect();

    // Sort by usage count
    correlations.sort_by(|a, b| b.usage_count.cmp(&a.usage_count));
    correlations.truncate(20); // Top 20 correlations

    correlations
}

#[allow(dead_code)]
struct CorrelationData {
    usage_count: u32,
    success_count: u32,
    sessions: std::collections::HashSet<String>,
}

#[allow(clippy::too_many_arguments)]
fn analyze_tools(
    path: Option<&str>,
    cli: &Cli,
    format: &OutputFormat,
    output: Option<PathBuf>,
    tool_filter: Option<&str>,
    agent_filter: Option<&str>,
    show_chains: bool,
    show_correlation: bool,
    min_usage: u32,
    sort_by: &SortBy,
    #[cfg(feature = "terraphim")] kg_search_query: Option<&str>,
) -> Result<()> {
    let analyzer = create_analyzer(path.map(String::from), cli)?;
    let analyses = analyzer.analyze(None)?;

    if analyses.is_empty() {
        println!("{}", "No sessions found".yellow());
        return Ok(());
    }

    // Show progress for large session sets
    if analyses.len() > 10 {
        info!("Analyzing tool usage across {} sessions...", analyses.len());
    }

    // Initialize pattern matcher with built-in and user patterns
    let mut matcher = AhoCorasickMatcher::new();
    let patterns = load_all_patterns().context("Failed to load patterns")?;
    matcher
        .initialize(&patterns)
        .context("Failed to initialize pattern matcher")?;

    // Extract tool invocations from all sessions
    let mut all_invocations = Vec::new();

    for (i, analysis) in analyses.iter().enumerate() {
        if analyses.len() > 10 && i % 10 == 0 {
            info!("Processing session {}/{}", i + 1, analyses.len());
        }

        // Find the session file
        let session_path = find_session_path(&analysis.session_id, cli)?;

        // Parse the session
        if let Ok(parser) = SessionParser::from_file(&session_path) {
            // Extract tool invocations from Bash commands
            if let Ok(mut invocations) = extract_tool_invocations_from_session(&parser, &matcher) {
                // Link tool invocations to agents from the analysis
                for invocation in &mut invocations {
                    // Find the agent that was active at this timestamp
                    let active_agent = analysis
                        .agents
                        .iter()
                        .filter(|a| a.timestamp <= invocation.timestamp)
                        .max_by_key(|a| a.timestamp);

                    if let Some(agent) = active_agent {
                        invocation.agent_context = Some(agent.agent_type.clone());
                    }
                }

                all_invocations.extend(invocations);
            }
        }
    }

    if all_invocations.is_empty() {
        println!("{}", "No tool invocations found".yellow());
        return Ok(());
    }

    // Handle KG search if provided
    #[cfg(feature = "terraphim")]
    if let Some(query_str) = kg_search_query {
        use terraphim_session_analyzer::kg::{
            KnowledgeGraphBuilder, KnowledgeGraphSearch, QueryParser,
        };

        // Parse the query
        let query_ast = QueryParser::parse(query_str)
            .with_context(|| format!("Failed to parse query: {query_str}"))?;

        // Convert to library types for KG module
        let lib_invocations: Vec<terraphim_session_analyzer::ToolInvocation> = all_invocations
            .iter()
            .map(convert_to_lib_invocation)
            .collect();

        // Build knowledge graph from tool invocations
        let builder = KnowledgeGraphBuilder::from_tool_invocations(&lib_invocations);
        let kg_search = KnowledgeGraphSearch::new(builder);

        // Search through invocations and collect results
        let mut matching_invocations = Vec::new();

        for invocation in &all_invocations {
            match kg_search.search(&invocation.command_line, &query_ast) {
                Ok(results) if !results.is_empty() => {
                    // Calculate total relevance for this invocation
                    let total_relevance: f32 = results.iter().map(|r| r.relevance_score).sum();

                    // Collect all matched concepts
                    let mut matched_concepts: Vec<String> = results
                        .iter()
                        .flat_map(|r| r.concepts_matched.clone())
                        .collect();
                    matched_concepts.sort();
                    matched_concepts.dedup();

                    matching_invocations.push((invocation, total_relevance, matched_concepts));
                }
                _ => {}
            }
        }

        // Sort by relevance score
        matching_invocations
            .sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

        // Display results
        println!(
            "\n{} Knowledge Graph Search Results for: {}",
            "🔍".cyan(),
            query_str.yellow().bold()
        );
        println!("{}", "=".repeat(80).dimmed());
        println!(
            "\n{} {} matching commands found\n",
            "Found:".bold(),
            matching_invocations.len().to_string().yellow()
        );

        for (i, (invocation, relevance, matched_concepts)) in
            matching_invocations.iter().enumerate().take(50)
        {
            // Show top 50 results
            println!(
                "{}. {} {}",
                (i + 1).to_string().dimmed(),
                "Command:".bold(),
                invocation.command_line.green()
            );
            println!("   {} {}", "Tool:".dimmed(), invocation.tool_name.cyan());
            println!(
                "   {} {}",
                "Session:".dimmed(),
                invocation.session_id.dimmed()
            );
            if let Some(ref agent) = invocation.agent_context {
                let agent_str = agent.as_str();
                println!("   {} {}", "Agent:".dimmed(), agent_str.yellow());
            }
            println!("   {} {:.2}", "Relevance:".dimmed(), relevance);
            println!(
                "   {} {}",
                "Matched:".dimmed(),
                matched_concepts.join(", ").cyan()
            );
            println!();
        }

        if matching_invocations.len() > 50 {
            println!(
                "{} Showing top 50 of {} results",
                "Note:".yellow(),
                matching_invocations.len()
            );
        }

        return Ok(());
    }

    // Calculate comprehensive statistics using the new Analyzer methods
    let tool_stats = analyzer.calculate_tool_statistics(&all_invocations);
    let category_breakdown = analyzer.calculate_category_breakdown(&all_invocations);

    // Apply filters to the IndexMap
    let filtered_stats: Vec<(String, models::ToolStatistics)> = tool_stats
        .into_iter()
        .filter(|(name, stats)| {
            // Tool name filter
            if let Some(tool_filter_str) = tool_filter {
                if !name
                    .to_lowercase()
                    .contains(&tool_filter_str.to_lowercase())
                {
                    return false;
                }
            }

            // Agent filter
            if let Some(agent_filter_str) = agent_filter {
                if !stats
                    .agents_using
                    .iter()
                    .any(|a| a.to_lowercase().contains(&agent_filter_str.to_lowercase()))
                {
                    return false;
                }
            }

            // Minimum usage filter
            if stats.total_invocations < min_usage {
                return false;
            }

            true
        })
        .collect();

    if filtered_stats.is_empty() {
        println!("{}", "No tools match the specified criteria".yellow());
        return Ok(());
    }

    // Sort the results
    let sorted_stats: Vec<(String, models::ToolStatistics)> = {
        let mut stats = filtered_stats;
        match sort_by {
            SortBy::Frequency => {
                stats.sort_by(|a, b| b.1.total_invocations.cmp(&a.1.total_invocations))
            }
            SortBy::Alphabetical => stats.sort_by(|a, b| a.0.cmp(&b.0)),
            SortBy::Recent => stats.sort_by(|a, b| b.1.last_seen.cmp(&a.1.last_seen)),
        }
        stats
    };

    // Convert sorted_stats back to IndexMap
    let mut tool_statistics = indexmap::IndexMap::new();
    for (name, stat) in sorted_stats {
        tool_statistics.insert(name, stat);
    }

    // Calculate correlations if requested
    let correlations = if show_correlation {
        analyzer.calculate_agent_tool_correlations(&all_invocations)
    } else {
        Vec::new()
    };

    // Calculate tool chains if requested
    let tool_chains = if show_chains {
        calculate_tool_chains(&all_invocations)
    } else {
        Vec::new()
    };

    // Build ToolAnalysis struct
    #[allow(clippy::cast_possible_truncation)]
    let tool_analysis = models::ToolAnalysis {
        session_id: "aggregated".to_string(), // This is across all sessions
        total_tool_invocations: all_invocations.len() as u32,
        tool_statistics,
        agent_tool_correlations: correlations,
        tool_chains,
        category_breakdown,
    };

    // Create reporter
    let reporter = Reporter::new().with_colors(!cli.no_color);

    // Display results based on format
    match format {
        OutputFormat::Terminal => {
            reporter.print_tool_analysis_detailed(&tool_analysis, show_correlation)?;
        }
        OutputFormat::Json => {
            let json = reporter.tool_analysis_to_json(&tool_analysis)?;
            write_output(&json, output)?;
        }
        OutputFormat::Csv => {
            let csv = reporter.tool_analysis_to_csv(&tool_analysis)?;
            write_output(&csv, output)?;
        }
        OutputFormat::Markdown => {
            let md = reporter.tool_analysis_to_markdown(&tool_analysis)?;
            write_output(&md, output)?;
        }
        OutputFormat::Html => {
            println!(
                "{}",
                "HTML format not yet implemented for tool analysis".yellow()
            );
        }
    }

    Ok(())
}

fn find_session_path(session_id: &str, cli: &Cli) -> Result<PathBuf> {
    let base_dir = if let Some(ref session_dir) = cli.session_dir {
        session_dir.clone()
    } else {
        let home = home::home_dir().context("Could not find home directory")?;
        home.join(".claude").join("projects")
    };

    // Look for the session file in all subdirectories
    for entry in walkdir::WalkDir::new(&base_dir)
        .follow_links(true)
        .into_iter()
        .filter_map(|e| e.ok())
    {
        if entry.file_type().is_file() {
            if let Some(name) = entry.file_name().to_str() {
                if name.ends_with(".jsonl") && name.contains(session_id) {
                    return Ok(entry.path().to_path_buf());
                }
            }
        }
    }

    Err(anyhow::anyhow!("Session file not found: {session_id}"))
}

fn extract_tool_invocations_from_session(
    parser: &SessionParser,
    matcher: &dyn PatternMatcher,
) -> Result<Vec<models::ToolInvocation>> {
    use models::{ContentBlock, Message, ToolCategory, ToolInvocation};

    let mut invocations = Vec::new();

    for entry in parser.entries() {
        if let Message::Assistant { content, .. } = &entry.message {
            for block in content {
                if let ContentBlock::ToolUse { name, input, .. } = block {
                    if name == "Bash" {
                        if let Some(command) = input.get("command").and_then(|v| v.as_str()) {
                            let matches = matcher.find_matches(command);

                            for tool_match in matches {
                                // Parse the command context
                                if let Some((full_cmd, args, flags)) =
                                    tool_analyzer::parse_command_context(command, tool_match.start)
                                {
                                    if let Ok(timestamp) = models::parse_timestamp(&entry.timestamp)
                                    {
                                        // Map category string to ToolCategory enum
                                        let category = match tool_match.category.as_str() {
                                            "package-manager" => ToolCategory::PackageManager,
                                            "version-control" => ToolCategory::Git,
                                            "testing" => ToolCategory::Testing,
                                            "linting" => ToolCategory::Linting,
                                            "cloudflare" => ToolCategory::CloudDeploy,
                                            _ => ToolCategory::Other(tool_match.category.clone()),
                                        };

                                        invocations.push(ToolInvocation {
                                            timestamp,
                                            tool_name: tool_match.tool_name.clone(),
                                            tool_category: category,
                                            command_line: full_cmd,
                                            arguments: args,
                                            flags,
                                            exit_code: None,
                                            agent_context: None,
                                            session_id: entry.session_id.clone(),
                                            message_id: entry.uuid.clone(),
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    Ok(invocations)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_expand_home_dir() {
        let result = expand_home_dir("~/.claude/projects");
        assert!(result.is_ok());

        let path = result.unwrap();
        assert!(path.to_string_lossy().contains(".claude"));
    }

    #[test]
    fn test_expand_home_dir_absolute() {
        let result = expand_home_dir("/absolute/path");
        assert!(result.is_ok());

        let path = result.unwrap();
        assert_eq!(path, PathBuf::from("/absolute/path"));
    }
}