gitstack 5.3.0

Git history viewer with insights - Author stats, file heatmap, code ownership
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
mod actions;
mod key_handlers;

use std::io;
use std::path::PathBuf;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use std::time::{Duration, Instant, SystemTime};

use anyhow::Result;
use crossterm::{
    event::{
        self as crossterm_event, DisableMouseCapture, EnableMouseCapture, Event, KeyEventKind,
        MouseButton, MouseEventKind,
    },
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use git2::Repository;
use ratatui::{backend::CrosstermBackend, Terminal};

use gitstack::{
    calculate_file_heatmap, calculate_project_health, classify_intent, detect_sessions,
    fetch_remote_at_path, get_commit_diff, get_head_hash_cached, get_index_mtime_cached,
    get_repo_info_cached, get_status_cached, get_working_file_diff, list_branches_cached,
    load_events, load_events_fast, parse_cli_args, parse_tui_options, pull, push, run_cli_mode,
    tui, ActivityTimeline, App, BlameLine, ChangeCouplingAnalysis, CliCommand, CodeOwnership,
    CommitDiff, CommitImpactAnalysis, CommitQualityAnalysis, GitEvent, InputMode, ProjectHealth,
    SidebarPanel, TuiFocusTarget, TuiOptions,
};

use key_handlers::{
    handle_blame_view_keys, handle_branch_compare_keys, handle_branch_create_keys,
    handle_branch_select_keys, handle_change_coupling_keys, handle_commit_input_keys,
    handle_detail_keys, handle_file_history_keys, handle_filter_keys, handle_handoff_view_keys,
    handle_heatmap_view_keys, handle_help_keys, handle_impact_score_keys,
    handle_next_actions_view_keys, handle_normal_keys, handle_ownership_view_keys,
    handle_patch_view_keys, handle_pr_create_keys, handle_preset_save_keys,
    handle_quality_score_keys, handle_quick_action_keys, handle_related_files_keys,
    handle_review_pack_view_keys, handle_review_queue_keys, handle_stash_view_keys,
    handle_stats_view_keys, handle_status_view_keys, handle_timeline_view_keys,
    handle_topology_view_keys,
};

/// Number of events to display initially (for fast startup)
const INITIAL_LOAD_COUNT: usize = 10;

/// Maximum number of events to load (for large repository support)
const MAX_LOAD_COUNT: usize = 2000;

/// Background fetch state
pub(crate) struct RemoteFetchState {
    /// Channel to receive fetch results
    result_rx: Option<Receiver<Result<(), String>>>,
    /// Whether to suppress error display (true for automatic fetches)
    quiet_mode: bool,
    /// Timestamp of the last fetch
    last_fetch: Instant,
}

impl RemoteFetchState {
    fn new() -> Self {
        Self {
            result_rx: None,
            quiet_mode: false,
            last_fetch: Instant::now(),
        }
    }

    /// Whether a fetch is currently in progress
    fn is_running(&self) -> bool {
        self.result_rx.is_some()
    }

    /// Start a fetch in the background
    fn start(&mut self, repo_path: PathBuf, quiet: bool) {
        if self.is_running() {
            return; // Prevent double execution
        }

        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            let result = fetch_remote_at_path(&repo_path).map_err(|e| e.to_string());
            let _ = tx.send(result);
        });

        self.result_rx = Some(rx);
        self.quiet_mode = quiet;
    }

    /// Check fetch result (Some if completed, None if running or not started)
    fn check_result(&mut self) -> Option<Result<(), String>> {
        let rx = self.result_rx.as_ref()?;
        match rx.try_recv() {
            Ok(result) => {
                self.result_rx = None;
                self.last_fetch = Instant::now();
                Some(result)
            }
            Err(mpsc::TryRecvError::Empty) => None, // Still running
            Err(mpsc::TryRecvError::Disconnected) => {
                self.result_rx = None;
                Some(Err("Fetch thread crashed".to_string()))
            }
        }
    }
}

/// Background event loading state
pub(crate) struct BackgroundLoadState {
    /// Channel to receive results
    result_rx: Option<Receiver<Vec<GitEvent>>>,
}

impl BackgroundLoadState {
    fn new() -> Self {
        Self { result_rx: None }
    }

    /// Whether loading is in progress
    fn is_running(&self) -> bool {
        self.result_rx.is_some()
    }

    /// Start loading additional events in the background
    pub(crate) fn start(&mut self, skip: usize, limit: usize) {
        if self.is_running() {
            return;
        }

        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            // Load up to limit events starting from the skip-th entry
            if let Ok(all_events) = load_events(skip + limit) {
                let additional: Vec<GitEvent> = all_events.into_iter().skip(skip).collect();
                let _ = tx.send(additional);
            } else {
                let _ = tx.send(Vec::new());
            }
        });

        self.result_rx = Some(rx);
    }

    /// Check loading result
    fn check_result(&mut self) -> Option<Vec<GitEvent>> {
        let rx = self.result_rx.as_ref()?;
        match rx.try_recv() {
            Ok(events) => {
                self.result_rx = None;
                Some(events)
            }
            Err(mpsc::TryRecvError::Empty) => None,
            Err(mpsc::TryRecvError::Disconnected) => {
                self.result_rx = None;
                Some(Vec::new())
            }
        }
    }
}

/// Background health calculation state
struct BackgroundHealthState {
    /// Channel to receive results
    result_rx: Option<Receiver<ProjectHealth>>,
}

impl BackgroundHealthState {
    fn new() -> Self {
        Self { result_rx: None }
    }

    /// Whether calculation is in progress
    fn is_running(&self) -> bool {
        self.result_rx.is_some()
    }

    /// Start health calculation in the background
    fn start(&mut self, events: Vec<GitEvent>) {
        if self.is_running() {
            return;
        }

        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            let repo = match git2::Repository::discover(".") {
                Ok(r) => r,
                Err(_) => return,
            };
            let mut file_cache: std::collections::HashMap<String, Vec<String>> =
                std::collections::HashMap::new();
            let event_refs: Vec<&GitEvent> = events.iter().collect();
            for event in &event_refs {
                if !file_cache.contains_key(&event.short_hash) {
                    if let Ok(files) =
                        gitstack::get_commit_files_from_repo(&repo, &event.short_hash)
                    {
                        file_cache.insert(event.short_hash.clone(), files);
                    }
                }
            }
            let file_cache_ref = &file_cache;
            let heatmap =
                calculate_file_heatmap(&event_refs, |hash| file_cache_ref.get(hash).cloned());
            let health = calculate_project_health(
                &event_refs,
                |hash| file_cache_ref.get(hash).cloned(),
                None,
                None,
                None,
                &heatmap,
            );
            let _ = tx.send(health);
        });

        self.result_rx = Some(rx);
    }

    /// Check calculation result
    fn check_result(&mut self) -> Option<ProjectHealth> {
        let rx = self.result_rx.as_ref()?;
        match rx.try_recv() {
            Ok(health) => {
                self.result_rx = None;
                Some(health)
            }
            Err(mpsc::TryRecvError::Empty) => None,
            Err(mpsc::TryRecvError::Disconnected) => {
                self.result_rx = None;
                None
            }
        }
    }
}

/// Background risk calculation state
struct BackgroundRiskState {
    /// Channel to receive results
    result_rx: Option<Receiver<(f64, gitstack::RiskLevel)>>,
}

impl BackgroundRiskState {
    fn new() -> Self {
        Self { result_rx: None }
    }

    /// Whether calculation is in progress
    fn is_running(&self) -> bool {
        self.result_rx.is_some()
    }

    /// Start risk calculation in the background
    fn start(&mut self, events: Vec<GitEvent>, statuses: Vec<gitstack::git::FileStatus>) {
        if self.is_running() {
            return;
        }

        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            let repo = match git2::Repository::discover(".") {
                Ok(r) => r,
                Err(_) => return,
            };
            let event_refs: Vec<&GitEvent> = events.iter().collect();
            let mut file_cache: std::collections::HashMap<String, Vec<String>> =
                std::collections::HashMap::new();
            for event in &event_refs {
                if !file_cache.contains_key(&event.short_hash) {
                    if let Ok(files) =
                        gitstack::get_commit_files_from_repo(&repo, &event.short_hash)
                    {
                        file_cache.insert(event.short_hash.clone(), files);
                    }
                }
            }
            let file_cache_ref = &file_cache;
            let heatmap =
                calculate_file_heatmap(&event_refs, |hash| file_cache_ref.get(hash).cloned());
            let ownership = gitstack::stats::CodeOwnership {
                entries: vec![],
                total_files: 0,
            };
            let result = gitstack::calculate_staged_risk(&statuses, &heatmap, &ownership);
            let _ = tx.send(result);
        });

        self.result_rx = Some(rx);
    }

    /// Check calculation result
    fn check_result(&mut self) -> Option<(f64, gitstack::RiskLevel)> {
        let rx = self.result_rx.as_ref()?;
        match rx.try_recv() {
            Ok(result) => {
                self.result_rx = None;
                Some(result)
            }
            Err(mpsc::TryRecvError::Empty) => None,
            Err(mpsc::TryRecvError::Disconnected) => {
                self.result_rx = None;
                None
            }
        }
    }
}

/// Background diff calculation state
pub(crate) struct BackgroundDiffState {
    /// Channel to receive results
    result_rx: Option<Receiver<(String, CommitDiff)>>,
    /// Hash currently being computed
    pending_hash: Option<String>,
}

impl BackgroundDiffState {
    fn new() -> Self {
        Self {
            result_rx: None,
            pending_hash: None,
        }
    }

    /// Whether calculation is in progress
    pub(crate) fn is_running(&self) -> bool {
        self.result_rx.is_some()
    }

    /// Start diff calculation in the background
    pub(crate) fn start(&mut self, hash: String) {
        if self.is_running() {
            return;
        }

        let hash_clone = hash.clone();
        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            if let Ok(diff) = get_commit_diff(&hash_clone) {
                let _ = tx.send((hash_clone, diff));
            }
        });

        self.pending_hash = Some(hash);
        self.result_rx = Some(rx);
    }

    /// Check calculation result
    fn check_result(&mut self) -> Option<(String, CommitDiff)> {
        let rx = self.result_rx.as_ref()?;
        match rx.try_recv() {
            Ok(result) => {
                self.result_rx = None;
                self.pending_hash = None;
                Some(result)
            }
            Err(mpsc::TryRecvError::Empty) => None,
            Err(mpsc::TryRecvError::Disconnected) => {
                self.result_rx = None;
                self.pending_hash = None;
                None
            }
        }
    }
}

/// Git operation type (Pull or Push)
pub(crate) enum GitOp {
    Pull,
    Push,
}

/// Background Git operation state (Pull/Push)
pub(crate) struct BackgroundGitOpState {
    /// Channel to receive results
    result_rx: Option<Receiver<Result<(), String>>>,
    /// Current operation type
    operation: Option<GitOp>,
}

impl BackgroundGitOpState {
    fn new() -> Self {
        Self {
            result_rx: None,
            operation: None,
        }
    }

    /// Whether an operation is in progress
    pub(crate) fn is_running(&self) -> bool {
        self.result_rx.is_some()
    }

    /// Start pull in the background
    pub(crate) fn start_pull(&mut self) {
        if self.is_running() {
            return;
        }

        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            let result = pull().map_err(|e| e.to_string());
            let _ = tx.send(result);
        });

        self.result_rx = Some(rx);
        self.operation = Some(GitOp::Pull);
    }

    /// Start push in the background
    pub(crate) fn start_push(&mut self) {
        if self.is_running() {
            return;
        }

        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            let result = push().map_err(|e| e.to_string());
            let _ = tx.send(result);
        });

        self.result_rx = Some(rx);
        self.operation = Some(GitOp::Push);
    }

    /// Check operation result
    fn check_result(&mut self) -> Option<(GitOp, Result<(), String>)> {
        let rx = self.result_rx.as_ref()?;
        match rx.try_recv() {
            Ok(result) => {
                let op = self.operation.take().unwrap_or(GitOp::Pull);
                self.result_rx = None;
                Some((op, result))
            }
            Err(mpsc::TryRecvError::Empty) => None,
            Err(mpsc::TryRecvError::Disconnected) => {
                let op = self.operation.take().unwrap_or(GitOp::Pull);
                self.result_rx = None;
                Some((op, Err("Git operation thread crashed".to_string())))
            }
        }
    }
}

/// Analysis result types for background computation
pub(crate) enum AnalysisResult {
    Timeline(Box<ActivityTimeline>),
    Ownership(CodeOwnership),
    ImpactScore(CommitImpactAnalysis),
    ChangeCoupling(ChangeCouplingAnalysis),
    QualityScore(CommitQualityAnalysis),
}

/// Background analysis state
pub(crate) struct BackgroundAnalysisState {
    /// Channel to receive results
    pub(crate) result_rx: Option<Receiver<AnalysisResult>>,
}

impl BackgroundAnalysisState {
    fn new() -> Self {
        Self { result_rx: None }
    }

    /// Whether analysis is in progress
    pub(crate) fn is_running(&self) -> bool {
        self.result_rx.is_some()
    }

    /// Check analysis result
    fn check_result(&mut self) -> Option<AnalysisResult> {
        let rx = self.result_rx.as_ref()?;
        match rx.try_recv() {
            Ok(result) => {
                self.result_rx = None;
                Some(result)
            }
            Err(mpsc::TryRecvError::Empty) => None,
            Err(mpsc::TryRecvError::Disconnected) => {
                self.result_rx = None;
                None
            }
        }
    }
}

/// Background blame state
pub(crate) struct BackgroundBlameState {
    /// Channel to receive results
    result_rx: Option<Receiver<(String, Vec<BlameLine>)>>,
}

impl BackgroundBlameState {
    fn new() -> Self {
        Self { result_rx: None }
    }

    /// Whether blame is in progress
    pub(crate) fn is_running(&self) -> bool {
        self.result_rx.is_some()
    }

    /// Start blame in the background
    pub(crate) fn start(&mut self, path: String) {
        if self.is_running() {
            return;
        }

        let path_clone = path.clone();
        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            if let Ok(blame) = gitstack::get_blame(&path_clone) {
                let _ = tx.send((path_clone, blame));
            }
        });

        self.result_rx = Some(rx);
    }

    /// Check blame result
    fn check_result(&mut self) -> Option<(String, Vec<BlameLine>)> {
        let rx = self.result_rx.as_ref()?;
        match rx.try_recv() {
            Ok(result) => {
                self.result_rx = None;
                Some(result)
            }
            Err(mpsc::TryRecvError::Empty) => None,
            Err(mpsc::TryRecvError::Disconnected) => {
                self.result_rx = None;
                None
            }
        }
    }
}

/// Collection of all background operation states
struct BackgroundStates {
    load: BackgroundLoadState,
    health: BackgroundHealthState,
    risk: BackgroundRiskState,
    diff: BackgroundDiffState,
    git_op: BackgroundGitOpState,
    analysis: BackgroundAnalysisState,
    blame: BackgroundBlameState,
}

/// Check for input events (with configurable timeout)
fn check_input(timeout_ms: u64) -> Result<Option<Event>> {
    if crossterm_event::poll(Duration::from_millis(timeout_ms))? {
        Ok(Some(crossterm_event::read()?))
    } else {
        Ok(None)
    }
}

fn apply_tui_options(app: &mut App, options: &TuiOptions) {
    if let Some(TuiFocusTarget::Files) = options.focus {
        app.input_mode = InputMode::StatusView;
    }
}

fn apply_post_repo_focus(app: &mut App, options: &TuiOptions) {
    if options.focus == Some(TuiFocusTarget::Files) {
        if let Ok(statuses) = get_status_cached(app.get_repo()) {
            app.file_statuses = statuses;
            if app.status_selected_index >= app.file_statuses.len() {
                app.status_selected_index = 0;
            }
        }
    }
}

fn adjust_scroll_for_resize(app: &mut App, term_height: u16) {
    let list_lines = term_height.saturating_sub(8) as usize;
    let detail_lines = term_height.saturating_sub(10) as usize;

    if app.show_detail {
        app.detail_adjust_scroll(detail_lines);
    }

    match app.input_mode {
        InputMode::TopologyView => app.topology_adjust_scroll(list_lines),
        InputMode::StatsView => app.stats_adjust_scroll(list_lines),
        InputMode::HeatmapView => app.heatmap_adjust_scroll(list_lines),
        InputMode::FileHistoryView => app.file_history_adjust_scroll(list_lines),
        InputMode::BlameView => app.blame_adjust_scroll(list_lines),
        InputMode::OwnershipView => app.ownership_adjust_scroll(list_lines),
        InputMode::StashView => app.stash_adjust_scroll(list_lines),
        InputMode::BranchCompareView => app.branch_compare_adjust_scroll(list_lines),
        InputMode::RelatedFilesView => app.related_files_adjust_scroll(list_lines),
        InputMode::ImpactScoreView => app.impact_score_adjust_scroll(list_lines),
        InputMode::ChangeCouplingView => app.change_coupling_adjust_scroll(list_lines),
        InputMode::QualityScoreView => app.quality_score_adjust_scroll(list_lines),
        InputMode::ReviewPackView => app.review_pack_adjust_scroll(list_lines),
        InputMode::NextActionsView => app.next_actions_adjust_scroll(list_lines),
        InputMode::HandoffView => app.handoff_adjust_scroll(list_lines),
        _ => {}
    }
}

fn main() -> Result<()> {
    let args: Vec<String> = std::env::args().collect();
    let tui_options = parse_tui_options(&args);

    // Check for CLI mode
    if let Some(command) = parse_cli_args() {
        if command != CliCommand::Benchmark {
            return run_cli_mode(command);
        }
    }

    // Benchmark mode
    if args.iter().any(|a| a == "--benchmark") {
        return run_benchmark_mode(&tui_options);
    }

    // TUI mode
    run_tui_mode(&tui_options)
}

/// Benchmark mode: run initialization only and measure time
fn run_benchmark_mode(tui_options: &TuiOptions) -> Result<()> {
    let start = Instant::now();

    let mut app = App::new();
    apply_tui_options(&mut app, tui_options);

    if let Ok(repo) = Repository::discover(".") {
        app.set_repo(repo);
        apply_post_repo_focus(&mut app, tui_options);
    }

    if let Ok(repo_info) = get_repo_info_cached(app.get_repo()) {
        let initial_events = load_events_fast(INITIAL_LOAD_COUNT).unwrap_or_default();
        app.load(repo_info, initial_events);

        if let Ok(head_hash) = get_head_hash_cached(app.get_repo()) {
            app.set_head_hash(head_hash);
        }
    }

    let elapsed = start.elapsed();
    println!(
        "Initialization time: {:.2}ms",
        elapsed.as_secs_f64() * 1000.0
    );
    println!("Events loaded: {}", app.event_count());
    Ok(())
}

/// TUI mode: terminal setup -> app initialization -> main loop
fn run_tui_mode(tui_options: &TuiOptions) -> Result<()> {
    // Install panic hook to restore terminal state on panic
    let original_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |panic_info| {
        let _ = disable_raw_mode();
        let _ = execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture);
        original_hook(panic_info);
    }));

    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let mut app = App::new();
    apply_tui_options(&mut app, tui_options);
    let mut bg_load_state = BackgroundLoadState::new();

    if let Ok(repo) = Repository::discover(".") {
        app.set_repo(repo);
        apply_post_repo_focus(&mut app, tui_options);
    }

    initialize_repo_data(&mut app, &mut bg_load_state);

    let mut bg = BackgroundStates {
        load: bg_load_state,
        health: BackgroundHealthState::new(),
        risk: BackgroundRiskState::new(),
        diff: BackgroundDiffState::new(),
        git_op: BackgroundGitOpState::new(),
        analysis: BackgroundAnalysisState::new(),
        blame: BackgroundBlameState::new(),
    };
    let result = run_app(&mut terminal, &mut app, &mut bg);

    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    result
}

/// Initial loading of repository data
fn initialize_repo_data(app: &mut App, bg_load_state: &mut BackgroundLoadState) {
    if let Ok(repo_info) = get_repo_info_cached(app.get_repo()) {
        let initial_events = load_events_fast(INITIAL_LOAD_COUNT).unwrap_or_default();
        let initial_count = initial_events.len();
        app.load(repo_info, initial_events);

        if let Ok(head_hash) = get_head_hash_cached(app.get_repo()) {
            app.set_head_hash(head_hash);
        }

        if let Ok(branches) = list_branches_cached(app.get_repo()) {
            app.update_branches(branches);
        }
        if let Ok(statuses) = get_status_cached(app.get_repo()) {
            app.update_file_statuses(statuses);
        }

        // Annotate events with AI session info and intent classification
        annotate_events_with_ai(app);

        if initial_count >= INITIAL_LOAD_COUNT {
            app.start_loading();
            bg_load_state.start(0, MAX_LOAD_COUNT);
        }
    }
}

/// Annotate events with AI session IDs and inferred intents
fn annotate_events_with_ai(app: &mut App) {
    // Detect AI sessions and store in cache
    let events: Vec<GitEvent> = app.events().cloned().collect();
    let sessions = detect_sessions(&events);

    // Annotate events with session_id
    if !sessions.is_empty() {
        let session_map: std::collections::HashMap<String, u32> = sessions
            .iter()
            .flat_map(|s| s.commits.iter().map(move |hash| (hash.clone(), s.id)))
            .collect();

        app.annotate_events(|event| {
            if let Some(&sid) = session_map.get(&event.short_hash) {
                event.session_id = Some(sid);
            }
            if event.inferred_intent.is_none() {
                event.inferred_intent = Some(classify_intent(&event.message, &[]));
            }
        });
    } else {
        // Still annotate intents even without sessions
        app.annotate_events(|event| {
            if event.inferred_intent.is_none() {
                event.inferred_intent = Some(classify_intent(&event.message, &[]));
            }
        });
    }

    app.session_cache = if sessions.is_empty() {
        None
    } else {
        Some(sessions)
    };
}

/// Minimum interval for local change checks (seconds)
const LOCAL_CHECK_MIN_INTERVAL: u64 = 1;

/// Maximum interval for local change checks (seconds)
const LOCAL_CHECK_MAX_INTERVAL: u64 = 5;

/// Remote fetch interval (seconds)
const REMOTE_FETCH_INTERVAL: u64 = 60;

/// Adaptive check interval
///
/// Doubles the interval when no changes detected (1s -> 2s -> 4s -> 5s)
/// Resets to minimum interval immediately when changes are detected
struct AdaptiveCheckInterval {
    /// Current interval (seconds)
    current_interval: u64,
    /// Timestamp of the last check
    last_check: Instant,
}

impl AdaptiveCheckInterval {
    fn new() -> Self {
        Self {
            current_interval: LOCAL_CHECK_MIN_INTERVAL,
            last_check: Instant::now(),
        }
    }

    /// Whether a check should be performed
    fn should_check(&self) -> bool {
        self.last_check.elapsed().as_secs() >= self.current_interval
    }

    /// No change: double the interval (up to maximum)
    fn on_no_change(&mut self) {
        self.current_interval = (self.current_interval * 2).min(LOCAL_CHECK_MAX_INTERVAL);
        self.last_check = Instant::now();
    }

    /// Change detected: reset interval to minimum
    fn on_change(&mut self) {
        self.current_interval = LOCAL_CHECK_MIN_INTERVAL;
        self.last_check = Instant::now();
    }
}

fn run_app(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut App,
    bg: &mut BackgroundStates,
) -> Result<()> {
    // State for local change detection
    let mut tracked_head = get_head_hash_cached(app.get_repo()).ok();
    let mut tracked_index_mtime: Option<SystemTime> = get_index_mtime_cached(app.get_repo()).ok();
    let mut adaptive_check = AdaptiveCheckInterval::new();

    // State for remote fetching
    let mut fetch_state = RemoteFetchState::new();
    let repo_path = std::env::current_dir().ok();

    // Rendering optimization: redraw only on state changes
    let mut needs_redraw = true;

    loop {
        // When Commits panel is active: lazy load diff for selected commit (background)
        if app.active_sidebar_panel == SidebarPanel::Commits
            && !app.show_detail
            && app.detail_diff_cache.is_none()
            && !bg.diff.is_running()
        {
            if let Some(event) = app.selected_event() {
                let hash = event.short_hash.clone();
                if bg.diff.pending_hash.as_deref() != Some(&hash) {
                    bg.diff.start(hash);
                }
            }
        }

        // When Files panel is active: lazy load diff
        if app.active_sidebar_panel == SidebarPanel::Files {
            if let Some(status) = app.file_statuses.get(app.status_selected_index) {
                let current_path = status.path.clone();
                let is_staged = status.kind.is_staged();
                if app.file_diff_cache_path() != Some(current_path.as_str()) {
                    if let Ok(patch) = get_working_file_diff(&current_path, is_staged) {
                        app.set_file_diff(patch, current_path);
                        needs_redraw = true;
                    }
                }
            }
        }

        // Auto-clear expired status messages
        if app.status_message.is_some() {
            let was_some = app.status_message.is_some();
            app.clear_expired_status_message();
            if was_some && app.status_message.is_none() {
                needs_redraw = true;
            }
        }

        // Render (only on state changes)
        if needs_redraw {
            terminal.draw(|frame| tui::render(frame, app))?;
            needs_redraw = false;
        }

        // Check results of background event loading
        // Replace with full set (including diff stats)
        if let Some(full_events) = bg.load.check_result() {
            if !full_events.is_empty() {
                let count = full_events.len();
                app.all_events_replace(full_events);
                app.filtered_indices_reset(count);
            }
            app.finish_loading();
            // Annotate events with AI session info and intent classification
            annotate_events_with_ai(app);
            // Start health calculation in background (non-blocking)
            let events_for_health: Vec<GitEvent> = app.events().cloned().collect();
            bg.health.start(events_for_health);
            needs_redraw = true;
        }

        // Check results of background diff calculation
        if let Some((_hash, diff)) = bg.diff.check_result() {
            app.set_detail_diff(diff);
            needs_redraw = true;
        }

        // Check results of background Git operation (Pull/Push)
        if let Some((op, result)) = bg.git_op.check_result() {
            match (&op, &result) {
                (GitOp::Pull, Ok(())) => {
                    app.set_status_message(app.language.status_pulled().to_string());
                    // Reload events in background after pull
                    key_handlers::reload_events_bg(&mut bg.load);
                    if let Ok(head_hash) = get_head_hash_cached(app.get_repo()) {
                        app.set_head_hash(head_hash);
                    }
                    if let Ok(statuses) = get_status_cached(app.get_repo()) {
                        app.update_file_statuses(statuses);
                    }
                }
                (GitOp::Push, Ok(())) => {
                    app.set_status_message(app.language.status_pushed().to_string());
                }
                (GitOp::Pull, Err(e)) => {
                    app.set_status_message(format!("{}: {}", app.language.status_pull_failed(), e));
                }
                (GitOp::Push, Err(e)) => {
                    app.set_status_message(format!("{}: {}", app.language.status_push_failed(), e));
                }
            }
            needs_redraw = true;
        }

        // Check results of background analysis
        if let Some(result) = bg.analysis.check_result() {
            match result {
                AnalysisResult::Timeline(timeline) => app.start_timeline_view(*timeline),
                AnalysisResult::Ownership(ownership) => app.start_ownership_view(ownership),
                AnalysisResult::ImpactScore(analysis) => app.start_impact_score_view(analysis),
                AnalysisResult::ChangeCoupling(analysis) => {
                    app.start_change_coupling_view(analysis)
                }
                AnalysisResult::QualityScore(analysis) => app.start_quality_score_view(analysis),
            }
            needs_redraw = true;
        }

        // Check results of background blame
        if let Some((path, blame)) = bg.blame.check_result() {
            app.close_detail();
            app.start_blame_view(path, blame);
            needs_redraw = true;
        }

        // Check results of background fetch
        if let Some(result) = fetch_state.check_result() {
            match result {
                Ok(()) => {
                    app.set_status_message(app.language.status_fetched().to_string());
                    // Reload events in background after fetch
                    key_handlers::reload_events_bg(&mut bg.load);
                    if let Ok(current_head) = get_head_hash_cached(app.get_repo()) {
                        app.set_head_hash(current_head.clone());
                        tracked_head = Some(current_head);
                    }
                }
                Err(e) if !fetch_state.quiet_mode => {
                    app.set_status_message(format!(
                        "{}: {}",
                        app.language.status_fetch_failed(),
                        e
                    ));
                }
                Err(_) => {} // Silently ignore errors during automatic fetch
            }
            needs_redraw = true;
        }

        // Check results of background health calculation
        if let Some(health) = bg.health.check_result() {
            app.health_view.cache = Some(health);
            needs_redraw = true;
        }

        // Check results of background risk calculation
        if let Some((score, level)) = bg.risk.check_result() {
            app.staged_risk_score = Some(score);
            app.staged_risk_level = Some(level);
            needs_redraw = true;
        }

        // Automatic remote fetch (60-second interval)
        if !fetch_state.is_running()
            && fetch_state.last_fetch.elapsed().as_secs() >= REMOTE_FETCH_INTERVAL
        {
            if let Some(ref path) = repo_path {
                fetch_state.start(path.clone(), true); // quiet=true
            }
        }

        // Auto-update via local change detection (adaptive interval, or 500ms in watch mode)
        let should_check = if app.watch_mode {
            adaptive_check.last_check.elapsed().as_millis() >= 500
        } else {
            adaptive_check.should_check()
        };
        if should_check {
            let mut change_detected = false;

            // HEAD change check (detect commits/merges)
            if let Ok(current_head) = get_head_hash_cached(app.get_repo()) {
                if tracked_head.as_ref() != Some(&current_head) {
                    // HEAD changed - reload events in background
                    key_handlers::reload_events_bg(&mut bg.load);
                    // Also update branch info
                    if let Ok(repo_info) = get_repo_info_cached(app.get_repo()) {
                        app.update_branch(repo_info.branch);
                    }
                    if let Ok(branches) = list_branches_cached(app.get_repo()) {
                        app.update_branches(branches);
                    }
                    app.set_head_hash(current_head.clone());
                    tracked_head = Some(current_head);
                    // Start health recalculation in background (non-blocking)
                    let events_for_health: Vec<GitEvent> = app.events().cloned().collect();
                    bg.health.start(events_for_health);
                    change_detected = true;
                    needs_redraw = true;
                }
            }

            // Index change check (detect staging changes)
            if let Ok(current_mtime) = get_index_mtime_cached(app.get_repo()) {
                if tracked_index_mtime.as_ref() != Some(&current_mtime) {
                    // Always update file statuses (sidebar always visible)
                    if let Ok(statuses) = get_status_cached(app.get_repo()) {
                        app.update_file_statuses(statuses.clone());
                        // Trigger background risk calculation
                        if !bg.risk.is_running() {
                            let events_for_risk: Vec<GitEvent> = app.events().cloned().collect();
                            bg.risk.start(events_for_risk, statuses);
                        }
                    }
                    needs_redraw = true;
                    tracked_index_mtime = Some(current_mtime);
                    change_detected = true;
                }
            }

            // Adjust next check interval based on whether changes were detected
            if change_detected {
                adaptive_check.on_change();
            } else {
                adaptive_check.on_no_change();
            }
        }

        // Check key input (longer timeout when idle for power saving)
        let poll_timeout = if needs_redraw { 100 } else { 500 };
        if let Some(event) = check_input(poll_timeout)? {
            if let Event::Resize(_, rows) = event {
                adjust_scroll_for_resize(app, rows);
                needs_redraw = true;
            } else if let Event::Mouse(mouse) = event {
                // Switch sidebar panel on mouse click
                if mouse.kind == MouseEventKind::Down(MouseButton::Left) {
                    let click_col = mouse.column;
                    let click_row = mouse.row;
                    let area: ratatui::layout::Rect = terminal.size().unwrap_or_default().into();
                    let layout = tui::calculate_layout_areas(area, app);
                    for (i, panel_area) in layout.sidebar_panels.iter().enumerate() {
                        if click_col >= panel_area.x
                            && click_col < panel_area.x + panel_area.width
                            && click_row >= panel_area.y
                            && click_row < panel_area.y + panel_area.height
                        {
                            let panels = SidebarPanel::all();
                            app.active_sidebar_panel = panels[i];
                            app.sidebar_focused = true;
                            needs_redraw = true;
                            break;
                        }
                    }
                }
            } else if let Event::Key(key) = event {
                // Process only KeyEventKind::Press (ignore release events)
                if key.kind != KeyEventKind::Press {
                    continue;
                }
                // Redraw on key input
                needs_redraw = true;
                match app.input_mode {
                    InputMode::Filter => handle_filter_keys(app, key),
                    InputMode::PresetSave => handle_preset_save_keys(app, key),
                    InputMode::BranchSelect => handle_branch_select_keys(app, key, &mut bg.load),
                    InputMode::BranchCreate => handle_branch_create_keys(app, key, &mut bg.load),
                    InputMode::QuickActionView => {
                        handle_quick_action_keys(app, key, &mut bg.analysis)
                    }
                    InputMode::Normal if app.show_help => handle_help_keys(app, key),
                    InputMode::Normal if app.show_detail => {
                        handle_detail_keys(app, key, terminal, &mut bg.diff, &mut bg.blame)
                    }
                    InputMode::StatusView => handle_status_view_keys(app, key, &mut bg.git_op),
                    InputMode::CommitInput => {
                        if handle_commit_input_keys(app, key, &mut bg.load) {
                            continue;
                        }
                    }
                    InputMode::TopologyView => {
                        handle_topology_view_keys(app, key, terminal, &mut bg.load)
                    }
                    InputMode::BranchCompareView => handle_branch_compare_keys(app, key, terminal),
                    InputMode::RelatedFilesView => handle_related_files_keys(app, key, terminal),
                    InputMode::StatsView => handle_stats_view_keys(app, key, terminal),
                    InputMode::HeatmapView => handle_heatmap_view_keys(app, key, terminal),
                    InputMode::FileHistoryView => handle_file_history_keys(app, key, terminal),
                    InputMode::TimelineView => handle_timeline_view_keys(app, key),
                    InputMode::BlameView => handle_blame_view_keys(app, key, terminal),
                    InputMode::OwnershipView => handle_ownership_view_keys(app, key, terminal),
                    InputMode::ImpactScoreView => handle_impact_score_keys(app, key, terminal),
                    InputMode::ChangeCouplingView => {
                        handle_change_coupling_keys(app, key, terminal)
                    }
                    InputMode::QualityScoreView => handle_quality_score_keys(app, key, terminal),
                    InputMode::StashView => handle_stash_view_keys(app, key, terminal),
                    InputMode::PatchView => handle_patch_view_keys(app, key, terminal),
                    InputMode::ReviewQueueView => handle_review_queue_keys(app, key),
                    InputMode::PrCreate => handle_pr_create_keys(app, key),
                    InputMode::ReviewPackView => handle_review_pack_view_keys(app, key, terminal),
                    InputMode::NextActionsView => handle_next_actions_view_keys(app, key, terminal),
                    InputMode::HandoffView => handle_handoff_view_keys(app, key, terminal),
                    InputMode::Normal => handle_normal_keys(
                        app,
                        key,
                        terminal,
                        &mut fetch_state,
                        &repo_path,
                        &mut bg.load,
                    ),
                }
            }
        }

        if app.should_quit {
            return Ok(());
        }
    }
}