debtmap 0.22.0

Code complexity and technical debt analyzer
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
use crate::{
    analysis::ContextDetector,
    builders::unified_analysis_phases::phases::scoring::{
        SuppressionContextCache, build_suppression_context_cache,
    },
    core::FunctionMetrics,
    data_flow::DataFlowGraph,
    extraction::ExtractedFileData,
    priority::{
        UnifiedAnalysis, UnifiedAnalysisUtils, UnifiedDebtItem,
        call_graph::{CallGraph, FunctionId},
        debt_aggregator::DebtAggregator,
        file_metrics::FileDebtItem,
        scoring::ContextRecommendationEngine,
    },
    progress::ProgressManager,
    risk::lcov::LcovData,
};
use chrono::{DateTime, Utc};
use dashmap::DashMap;
use indicatif::ParallelProgressIterator;
use parking_lot::Mutex;
use rayon::prelude::*;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Filter out unified debt items that are suppressed via debtmap:ignore annotations (spec 215).
///
/// This function checks each item against the suppression context cache and removes
/// items whose functions have `debtmap:ignore[type] -- reason` annotations.
fn filter_suppressed_items(
    items: Vec<UnifiedDebtItem>,
    suppression_cache: &SuppressionContextCache,
) -> Vec<UnifiedDebtItem> {
    items
        .into_iter()
        .filter(|item| {
            // Look up suppression context for this file
            if let Some(context) = suppression_cache.get(&item.location.file) {
                // Filter out if the function is allowed (suppressed)
                !context.is_function_allowed(item.location.line, &item.debt_type)
            } else {
                // No suppression context for this file, keep the item
                true
            }
        })
        .collect()
}

fn clone_function_metrics(functions: &[&FunctionMetrics]) -> Vec<FunctionMetrics> {
    functions.iter().map(|&function| function.clone()).collect()
}

fn should_emit_file_item(item: &FileDebtItem) -> bool {
    let has_god_object = item
        .metrics
        .god_object_analysis
        .as_ref()
        .is_some_and(|analysis| analysis.is_god_object);

    crate::builders::unified_analysis_phases::phases::file_analysis::should_include_file(item.score)
        || has_god_object
}

/// Options for parallel unified analysis
#[derive(Debug, Clone)]
pub struct ParallelUnifiedAnalysisOptions {
    pub parallel: bool,
    pub jobs: Option<usize>,
    pub batch_size: usize,
    pub progress: bool,
    /// Reference time for analysis (for determinism)
    pub reference_time: DateTime<Utc>,
}

impl Default for ParallelUnifiedAnalysisOptions {
    fn default() -> Self {
        Self {
            parallel: true,
            jobs: None,
            batch_size: 100,
            progress: true,
            reference_time: Utc::now(),
        }
    }
}

/// Timing information for analysis phases
#[derive(Debug, Clone)]
pub struct AnalysisPhaseTimings {
    pub call_graph_building: Duration,
    pub trait_resolution: Duration,
    pub coverage_loading: Duration,
    pub data_flow_creation: Duration,
    pub purity_analysis: Duration,
    pub test_detection: Duration,
    pub debt_aggregation: Duration,
    pub function_analysis: Duration,
    pub file_analysis: Duration,
    pub aggregation: Duration,
    pub sorting: Duration,
    pub total: Duration,
}

impl Default for AnalysisPhaseTimings {
    fn default() -> Self {
        Self {
            call_graph_building: Duration::from_secs(0),
            trait_resolution: Duration::from_secs(0),
            coverage_loading: Duration::from_secs(0),
            data_flow_creation: Duration::from_secs(0),
            purity_analysis: Duration::from_secs(0),
            test_detection: Duration::from_secs(0),
            debt_aggregation: Duration::from_secs(0),
            function_analysis: Duration::from_secs(0),
            file_analysis: Duration::from_secs(0),
            aggregation: Duration::from_secs(0),
            sorting: Duration::from_secs(0),
            total: Duration::from_secs(0),
        }
    }
}

/// Context for function analysis - groups all dependencies
struct FunctionAnalysisContext<'a> {
    call_graph: &'a CallGraph,
    debt_aggregator: &'a DebtAggregator,
    data_flow_graph: &'a DataFlowGraph,
    coverage_data: Option<&'a LcovData>,
    framework_exclusions: &'a HashSet<FunctionId>,
    function_pointer_used_functions: Option<&'a HashSet<FunctionId>>,
    risk_analyzer: Option<&'a crate::risk::RiskAnalyzer>,
    project_path: &'a Path,
    file_line_counts: &'a HashMap<PathBuf, usize>,
    // Shared detectors to avoid per-metric regex compilation (spec 196 optimization)
    context_detector: &'a ContextDetector,
    recommendation_engine: &'a ContextRecommendationEngine,
}

/// Optimized test detector with lock-free caching
///
/// Uses DashMap for concurrent cache access without lock contention.
/// This improves parallel scoring performance by 5-10% on large codebases.
pub struct OptimizedTestDetector {
    call_graph: Arc<CallGraph>,
    test_roots: HashSet<FunctionId>,
    reachability_cache: DashMap<FunctionId, bool>,
}

impl OptimizedTestDetector {
    pub fn new(call_graph: Arc<CallGraph>) -> Self {
        let test_roots = Self::find_test_roots(&call_graph);
        Self {
            call_graph,
            test_roots,
            reachability_cache: DashMap::new(),
        }
    }

    fn find_test_roots(call_graph: &Arc<CallGraph>) -> HashSet<FunctionId> {
        let mut test_roots = HashSet::new();

        // Find all functions that are test roots (have no callers and are test functions)
        for func_id in call_graph.get_all_functions() {
            let callers = call_graph.get_callers(func_id);
            if callers.is_empty() && Self::is_test_function(func_id) {
                test_roots.insert(func_id.clone());
            }
        }

        test_roots
    }

    fn is_test_function(func_id: &FunctionId) -> bool {
        let file = func_id.file.to_string_lossy();

        func_id.name.starts_with("test_")
            || func_id.name.contains("::test")
            || file.contains("/tests/")
            || file.contains("_test.rs")
    }

    pub fn is_test_only(&self, func_id: &FunctionId) -> bool {
        // Check cache first (lock-free read via DashMap)
        if let Some(result) = self.reachability_cache.get(func_id) {
            return *result;
        }

        // If it's a test root, it's test-only
        if self.test_roots.contains(func_id) {
            self.reachability_cache.insert(func_id.clone(), true);
            return true;
        }

        // Check if all callers are test-only
        let callers = self.call_graph.get_callers(func_id);
        if callers.is_empty() {
            // No callers and not a test root means it's not test-only
            self.reachability_cache.insert(func_id.clone(), false);
            return false;
        }

        // Use BFS to check if reachable from non-test code
        let is_test_only = self.is_reachable_only_from_tests(func_id);

        // Cache the result
        self.reachability_cache
            .insert(func_id.clone(), is_test_only);

        is_test_only
    }

    fn is_reachable_only_from_tests(&self, func_id: &FunctionId) -> bool {
        let mut visited = HashSet::new();
        let mut queue = vec![func_id.clone()];

        while let Some(current) = queue.pop() {
            if self.reaches_non_test_root(current, &mut visited, &mut queue) {
                return false;
            }
        }

        true
    }

    fn reaches_non_test_root(
        &self,
        current: FunctionId,
        visited: &mut HashSet<FunctionId>,
        queue: &mut Vec<FunctionId>,
    ) -> bool {
        if !visited.insert(current.clone()) {
            return false;
        }

        let callers = self.call_graph.get_callers(&current);
        if callers.is_empty() {
            return !self.test_roots.contains(&current);
        }

        Self::enqueue_unvisited_callers(callers, visited, queue);
        false
    }

    fn enqueue_unvisited_callers(
        callers: Vec<FunctionId>,
        visited: &HashSet<FunctionId>,
        queue: &mut Vec<FunctionId>,
    ) {
        for caller in callers
            .into_iter()
            .filter(|caller| !visited.contains(caller))
        {
            queue.push(caller);
        }
    }

    pub fn find_all_test_only_functions(&self) -> HashSet<FunctionId> {
        let all_functions: Vec<FunctionId> = self.call_graph.get_all_functions().cloned().collect();

        // Parallel detection of test-only functions
        all_functions
            .par_iter()
            .filter(|func_id| self.is_test_only(func_id))
            .cloned()
            .collect()
    }
}

/// Builder for parallel unified analysis
pub struct ParallelUnifiedAnalysisBuilder {
    call_graph: Arc<CallGraph>,
    options: ParallelUnifiedAnalysisOptions,
    timings: AnalysisPhaseTimings,
    risk_analyzer: Option<crate::risk::RiskAnalyzer>,
    project_path: PathBuf,
    /// Cached line counts from Phase 1 analysis, keyed by file path.
    /// Used to avoid redundant file I/O in Phase 3 (spec 195).
    line_count_index: HashMap<PathBuf, usize>,
    /// Pre-extracted file data from unified extraction phase (spec 213).
    /// When present, avoids re-parsing files during analysis.
    extracted_data: Option<Arc<HashMap<PathBuf, ExtractedFileData>>>,
}

impl ParallelUnifiedAnalysisBuilder {
    pub fn new(call_graph: CallGraph, options: ParallelUnifiedAnalysisOptions) -> Self {
        Self {
            call_graph: Arc::new(call_graph),
            options,
            timings: AnalysisPhaseTimings::default(),
            risk_analyzer: None,
            project_path: PathBuf::from("."),
            line_count_index: HashMap::new(),
            extracted_data: None,
        }
    }

    /// Set pre-extracted file data from unified extraction phase (spec 213).
    ///
    /// When extracted data is provided, the builder uses it to populate data flow
    /// analysis without re-parsing files. This prevents proc-macro2 SourceMap overflow.
    pub fn with_extracted_data(mut self, extracted: HashMap<PathBuf, ExtractedFileData>) -> Self {
        self.extracted_data = Some(Arc::new(extracted));
        self
    }

    /// Set the line count index from Phase 1 FileMetrics (spec 195).
    /// This avoids redundant file I/O in Phase 3 by caching total_lines per file.
    pub fn with_line_count_index(mut self, index: HashMap<PathBuf, usize>) -> Self {
        self.line_count_index = index;
        self
    }

    /// Build a line count index from FileMetrics (spec 195).
    /// Call this before execute_phase3_parallel to enable caching.
    pub fn build_line_count_index(
        file_metrics: &[crate::core::FileMetrics],
    ) -> HashMap<PathBuf, usize> {
        file_metrics
            .iter()
            .filter(|fm| fm.total_lines > 0)
            .map(|fm| (fm.path.clone(), fm.total_lines))
            .collect()
    }

    /// Set the risk analyzer for contextual risk analysis
    pub fn with_risk_analyzer(mut self, risk_analyzer: crate::risk::RiskAnalyzer) -> Self {
        // Ensure analyzer uses same reference time as overall analysis (Spec 214)
        let analyzer = risk_analyzer.with_reference_time(self.options.reference_time);
        self.risk_analyzer = Some(analyzer);
        self
    }

    /// Set the project path for contextual risk analysis
    pub fn with_project_path(mut self, project_path: PathBuf) -> Self {
        self.project_path = project_path;
        self
    }

    /// Set preliminary timing values (call graph and coverage loading)
    pub fn set_preliminary_timings(
        &mut self,
        call_graph_building: Duration,
        coverage_loading: Duration,
    ) {
        self.timings.call_graph_building = call_graph_building;
        self.timings.trait_resolution = Duration::from_secs(0);
        self.timings.coverage_loading = coverage_loading;
    }

    /// Execute phase 1: Parallel initialization
    pub fn execute_phase1_parallel(
        &mut self,
        metrics: &[FunctionMetrics],
        debt_items: Option<&[crate::core::DebtItem]>,
    ) -> (
        DataFlowGraph,
        HashMap<String, bool>, // purity analysis
        HashSet<FunctionId>,   // test-only functions
        DebtAggregator,
    ) {
        let start = Instant::now();

        // Subtask 0: Aggregate debt (data flow graph, purity, test detection, debt aggregation) - PARALLEL
        if let Some(manager) = ProgressManager::global() {
            manager.tui_update_subtask(5, 0, crate::tui::app::StageStatus::Active, None);
        }

        // Execute parallel initialization tasks
        let (data_flow, purity, test_funcs, debt_agg) =
            self.execute_phase1_tasks(metrics, debt_items);

        let phase1_time = start.elapsed();
        self.report_phase1_completion(phase1_time);

        if let Some(manager) = ProgressManager::global() {
            manager.tui_update_subtask(5, 0, crate::tui::app::StageStatus::Completed, None);
            std::thread::sleep(std::time::Duration::from_millis(150));
        }

        (data_flow, purity, test_funcs, debt_agg)
    }

    /// Execute the 4 parallel initialization tasks
    fn execute_phase1_tasks(
        &mut self,
        metrics: &[FunctionMetrics],
        debt_items: Option<&[crate::core::DebtItem]>,
    ) -> (
        DataFlowGraph,
        HashMap<String, bool>,
        HashSet<FunctionId>,
        DebtAggregator,
    ) {
        // Create shared references for parallel execution
        let call_graph = Arc::clone(&self.call_graph);
        let metrics_arc = Arc::new(metrics.to_vec());
        let debt_items_opt = debt_items.map(|d| d.to_vec());

        // Use thread-safe containers for results
        let data_flow_result = Arc::new(Mutex::new(None));
        let purity_result = Arc::new(Mutex::new(None));
        let test_funcs_result = Arc::new(Mutex::new(None));
        let debt_agg_result = Arc::new(Mutex::new(None));

        let timings = Arc::new(Mutex::new(self.timings.clone()));

        // Suppress old progress spinners - unified system already shows "4/4 Resolving dependencies"
        // These sub-tasks are handled silently by the unified progress system
        let (df_progress, purity_progress, test_progress, debt_progress) = (
            indicatif::ProgressBar::hidden(),
            indicatif::ProgressBar::hidden(),
            indicatif::ProgressBar::hidden(),
            indicatif::ProgressBar::hidden(),
        );

        let df_progress = Arc::new(df_progress);
        let purity_progress = Arc::new(purity_progress);
        let test_progress = Arc::new(test_progress);
        let debt_progress = Arc::new(debt_progress);

        // Execute all 4 initialization steps in parallel
        rayon::scope(|s| {
            // Task 1: Data flow graph creation
            self.spawn_data_flow_task(
                s,
                Arc::clone(&call_graph),
                Arc::clone(&metrics_arc),
                Arc::clone(&data_flow_result),
                Arc::clone(&timings),
                Arc::clone(&df_progress),
            );

            // Task 2: Purity analysis
            self.spawn_purity_task(
                s,
                Arc::clone(&metrics_arc),
                Arc::clone(&purity_result),
                Arc::clone(&timings),
                Arc::clone(&purity_progress),
            );

            // Task 3: Test detection
            self.spawn_test_detection_task(
                s,
                Arc::clone(&call_graph),
                Arc::clone(&test_funcs_result),
                Arc::clone(&timings),
                Arc::clone(&test_progress),
            );

            // Task 4: Debt aggregation
            self.spawn_debt_aggregation_task(
                s,
                Arc::clone(&metrics_arc),
                debt_items_opt,
                Arc::clone(&debt_agg_result),
                Arc::clone(&timings),
                Arc::clone(&debt_progress),
            );
        });

        // Extract results - parking_lot::Mutex never panics on poisoning
        // The tasks always complete before scope exits, so these should be Some
        let data_flow = data_flow_result
            .lock()
            .take()
            .expect("data flow analysis task completed but produced no result");
        let purity = purity_result
            .lock()
            .take()
            .expect("purity analysis task completed but produced no result");
        let test_funcs = test_funcs_result
            .lock()
            .take()
            .expect("test detection task completed but produced no result");
        let debt_agg = debt_agg_result
            .lock()
            .take()
            .expect("debt aggregation task completed but produced no result");

        // Update timings - parking_lot::Mutex::lock() never fails
        let t = timings.lock();
        self.timings = t.clone();

        (data_flow, purity, test_funcs, debt_agg)
    }

    fn spawn_data_flow_task<'a>(
        &self,
        scope: &rayon::Scope<'a>,
        call_graph: Arc<CallGraph>,
        metrics: Arc<Vec<FunctionMetrics>>,
        result: Arc<Mutex<Option<DataFlowGraph>>>,
        timings: Arc<Mutex<AnalysisPhaseTimings>>,
        progress: Arc<indicatif::ProgressBar>,
    ) {
        // Clone extracted data for the spawned task
        let extracted_data = self.extracted_data.clone();

        scope.spawn(move |_| {
            progress.tick();
            let start = Instant::now();
            progress.set_message("Preparing shared data-flow facts...");
            let data_flow = crate::builders::unified_analysis_phases::phases::preparation::build_data_flow_graph(
                &metrics,
                &call_graph,
                extracted_data.as_deref(),
            );

            // parking_lot::Mutex::lock() never fails (no poisoning)
            timings.lock().data_flow_creation = start.elapsed();

            // parking_lot::Mutex::lock() never fails (no poisoning)
            *result.lock() = Some(data_flow);
            progress.finish_with_message("Data-flow preparation complete");
        });
    }

    fn spawn_purity_task<'a>(
        &self,
        scope: &rayon::Scope<'a>,
        metrics: Arc<Vec<FunctionMetrics>>,
        result: Arc<Mutex<Option<HashMap<String, bool>>>>,
        timings: Arc<Mutex<AnalysisPhaseTimings>>,
        progress: Arc<indicatif::ProgressBar>,
    ) {
        scope.spawn(move |_| {
            progress.tick();
            let start = Instant::now();
            let purity_map =
                crate::builders::unified_analysis_phases::phases::scoring::metrics_to_purity_map(
                    &metrics,
                );
            // parking_lot::Mutex::lock() never fails (no poisoning)
            timings.lock().purity_analysis = start.elapsed();
            *result.lock() = Some(purity_map);
            progress.finish_with_message("Purity analysis complete");
        });
    }

    fn spawn_test_detection_task<'a>(
        &self,
        scope: &rayon::Scope<'a>,
        call_graph: Arc<CallGraph>,
        result: Arc<Mutex<Option<HashSet<FunctionId>>>>,
        timings: Arc<Mutex<AnalysisPhaseTimings>>,
        progress: Arc<indicatif::ProgressBar>,
    ) {
        scope.spawn(move |_| {
            progress.tick();
            let start = Instant::now();
            let test_funcs = crate::builders::unified_analysis_phases::phases::call_graph::find_test_only_functions(&call_graph);
            // parking_lot::Mutex::lock() never fails (no poisoning)
            timings.lock().test_detection = start.elapsed();
            *result.lock() = Some(test_funcs);
            progress.finish_with_message("Test detection complete");
        });
    }

    fn spawn_debt_aggregation_task<'a>(
        &self,
        scope: &rayon::Scope<'a>,
        metrics: Arc<Vec<FunctionMetrics>>,
        debt_items: Option<Vec<crate::core::DebtItem>>,
        result: Arc<Mutex<Option<DebtAggregator>>>,
        timings: Arc<Mutex<AnalysisPhaseTimings>>,
        progress: Arc<indicatif::ProgressBar>,
    ) {
        scope.spawn(move |_| {
            progress.tick();
            let start = Instant::now();
            let debt_aggregator =
                crate::builders::unified_analysis_phases::phases::scoring::setup_debt_aggregator(
                    &metrics,
                    debt_items.as_deref(),
                );

            // parking_lot::Mutex::lock() never fails (no poisoning)
            timings.lock().debt_aggregation = start.elapsed();
            *result.lock() = Some(debt_aggregator);
            progress.finish_with_message("Debt aggregation complete");
        });
    }

    fn report_phase1_completion(&self, phase1_time: Duration) {
        log::debug!(
            "Phase 1 complete in {:?} (DF: {:?}, Purity: {:?}, Test: {:?}, Debt: {:?})",
            phase1_time,
            self.timings.data_flow_creation,
            self.timings.purity_analysis,
            self.timings.test_detection,
            self.timings.debt_aggregation,
        );
    }

    /// Execute phase 2: Parallel function processing using functional pipeline
    #[allow(clippy::too_many_arguments)]
    pub fn execute_phase2_parallel(
        &mut self,
        metrics: &[FunctionMetrics],
        test_only_functions: &HashSet<FunctionId>,
        debt_aggregator: &DebtAggregator,
        data_flow_graph: &DataFlowGraph,
        coverage_data: Option<&LcovData>,
        framework_exclusions: &HashSet<FunctionId>,
        function_pointer_used_functions: Option<&HashSet<FunctionId>>,
    ) -> Vec<UnifiedDebtItem> {
        let start = Instant::now();

        // Subtask 1: Score functions (main computational loop with progress) - PARALLEL
        let total_metrics = metrics.len();
        if let Some(manager) = ProgressManager::global() {
            manager.tui_update_subtask(
                5,
                1,
                crate::tui::app::StageStatus::Active,
                Some((0, total_metrics)),
            );
        }

        // Suppress old progress bar - unified system already shows "4/4 Resolving dependencies"
        let progress: Option<indicatif::ProgressBar> = None;

        // Build suppression context cache for function-level debtmap:ignore annotations (spec 215)
        // This enables filtering of unified debt items based on annotations like:
        //   // debtmap:ignore[testing] -- I/O orchestration function
        let suppression_cache = build_suppression_context_cache(metrics);

        // Pre-create shared detectors once to avoid per-metric regex compilation (spec 196)
        // These are Sync types that can be safely shared across threads
        let context_detector = ContextDetector::new();
        let recommendation_engine = ContextRecommendationEngine::new();

        // Create analysis context for the pipeline
        let context = FunctionAnalysisContext {
            call_graph: &self.call_graph,
            debt_aggregator,
            data_flow_graph,
            coverage_data,
            framework_exclusions,
            function_pointer_used_functions,
            risk_analyzer: self.risk_analyzer.as_ref(),
            project_path: &self.project_path,
            file_line_counts: &self.line_count_index,
            context_detector: &context_detector,
            recommendation_engine: &recommendation_engine,
        };

        // Functional pipeline for processing metrics with progress tracking
        let items: Vec<UnifiedDebtItem> = self.process_metrics_pipeline(
            metrics,
            test_only_functions,
            &context,
            progress.as_ref(),
        );

        self.timings.function_analysis = start.elapsed();

        if let Some(manager) = ProgressManager::global() {
            manager.tui_update_subtask(
                5,
                1,
                crate::tui::app::StageStatus::Completed,
                Some((total_metrics, total_metrics)),
            );
            std::thread::sleep(std::time::Duration::from_millis(150));
        }

        // Finish progress bar with completion message
        if let Some(pb) = progress {
            pb.finish_with_message(format!(
                "Function analysis complete ({} items in {:?})",
                items.len(),
                self.timings.function_analysis
            ));
        }

        // Filter out items that are suppressed via debtmap:ignore annotations (spec 215)
        // This ensures annotations like `// debtmap:ignore[testing]` work in coverage mode
        filter_suppressed_items(items, &suppression_cache)
    }

    /// Process metrics through a functional pipeline
    fn process_metrics_pipeline(
        &self,
        metrics: &[FunctionMetrics],
        test_only_functions: &HashSet<FunctionId>,
        context: &FunctionAnalysisContext,
        progress: Option<&indicatif::ProgressBar>,
    ) -> Vec<UnifiedDebtItem> {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let total_metrics = metrics.len();
        let processed_count = AtomicUsize::new(0);
        // Throttle TUI updates (~50-100 total updates)
        let update_interval = (total_metrics / 100).max(1);

        metrics
            .par_iter()
            .progress_with(
                progress
                    .cloned()
                    .unwrap_or_else(indicatif::ProgressBar::hidden),
            )
            .flat_map(|metric| {
                let result = self.process_single_metric(metric, test_only_functions, context);

                // Update TUI progress (throttled)
                let current = processed_count.fetch_add(1, Ordering::Relaxed) + 1;
                if (current % update_interval == 0 || current == total_metrics)
                    && let Some(manager) = crate::progress::ProgressManager::global()
                {
                    manager.tui_update_subtask(
                        5,
                        1,
                        crate::tui::app::StageStatus::Active,
                        Some((current, total_metrics)),
                    );
                }

                result
            })
            .collect()
    }

    /// Process a single metric through the filtering and transformation pipeline (spec 228)
    fn process_single_metric(
        &self,
        metric: &FunctionMetrics,
        test_only_functions: &HashSet<FunctionId>,
        context: &FunctionAnalysisContext,
    ) -> Vec<UnifiedDebtItem> {
        if !crate::builders::unified_analysis_phases::phases::call_graph::should_process_metric(
            metric,
            &self.call_graph,
            test_only_functions,
        ) {
            return Vec::new();
        }

        // Transform metric to debt items (spec 228: returns Vec for multi-debt)
        self.metric_to_debt_items(metric, context)
    }

    /// Transform a metric into debt items (spec 228: multi-debt support)
    fn metric_to_debt_items(
        &self,
        metric: &FunctionMetrics,
        context: &FunctionAnalysisContext,
    ) -> Vec<UnifiedDebtItem> {
        // Returns Vec<UnifiedDebtItem> - one per debt type found (spec 228)
        // Uses shared detectors from context to avoid per-metric regex compilation (spec 196)
        // Note: risk_analyzer is already a reference in context, no need to clone
        crate::builders::unified_analysis::create_debt_item_from_metric_with_aggregator(
            metric,
            context.call_graph,
            context.coverage_data,
            context.framework_exclusions,
            context.function_pointer_used_functions,
            context.debt_aggregator,
            Some(context.data_flow_graph),
            context.risk_analyzer,
            context.project_path,
            context.file_line_counts,
            context.context_detector,
            context.recommendation_engine,
        )
    }

    /// Execute phase 3: Parallel file analysis
    pub fn execute_phase3_parallel(
        &mut self,
        metrics: &[FunctionMetrics],
        coverage_data: Option<&LcovData>,
        no_god_object: bool,
    ) -> Vec<(FileDebtItem, Vec<FunctionMetrics>)> {
        let start = Instant::now();

        // Group functions by file
        let mut files_map: HashMap<PathBuf, Vec<&FunctionMetrics>> = HashMap::new();
        for metric in metrics {
            files_map
                .entry(metric.file.clone())
                .or_default()
                .push(metric);
        }

        let total_files = files_map.len();

        // Initialize TUI progress tracking (design consistency - DESIGN.md:179)
        // Subtask 2: File analysis (stage 5 = debt scoring)
        if let Some(manager) = crate::progress::ProgressManager::global() {
            manager.tui_update_subtask(
                5,
                2,
                crate::tui::app::StageStatus::Active,
                Some((0, total_files)),
            );
        }

        // Shared progress counter for parallel processing
        let processed_count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let last_update = std::sync::Arc::new(std::sync::Mutex::new(Instant::now()));

        // Suppress old progress bar - unified system already shows subtask progress
        let progress = indicatif::ProgressBar::hidden();

        // Analyze files in parallel with TUI progress updates
        // Store both file items and raw functions for god object aggregation
        let mut file_data: Vec<(FileDebtItem, Vec<FunctionMetrics>)> = files_map
            .par_iter()
            .progress_with(progress.clone())
            .filter_map(|(file_path, functions)| {
                let result =
                    self.analyze_file_parallel(file_path, functions, coverage_data, no_god_object);

                // Update progress (throttled to maintain 60 FPS - DESIGN.md:179)
                let current =
                    processed_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;

                if let Ok(mut last) = last_update.try_lock()
                    && (current % 10 == 0 || last.elapsed() > std::time::Duration::from_millis(100))
                {
                    if let Some(manager) = crate::progress::ProgressManager::global() {
                        manager.tui_update_subtask(
                            5,
                            2,
                            crate::tui::app::StageStatus::Active,
                            Some((current, total_files)),
                        );
                    }
                    *last = Instant::now();
                }

                // Return both the file item and the raw functions
                result.map(|item| {
                    let raw_functions: Vec<FunctionMetrics> =
                        functions.iter().map(|&f| f.clone()).collect();
                    (item, raw_functions)
                })
            })
            .collect();

        // Sort file_data by path to ensure deterministic order (Spec 214 fix)
        // This ensures god objects are added in a stable order for duplicate checks.
        file_data.sort_by(|a, b| a.0.metrics.path.cmp(&b.0.metrics.path));

        self.timings.file_analysis = start.elapsed();

        progress.finish_and_clear();

        // Mark file analysis subtask complete
        if let Some(manager) = crate::progress::ProgressManager::global() {
            manager.tui_update_subtask(
                5,
                2,
                crate::tui::app::StageStatus::Completed,
                Some((total_files, total_files)),
            );
        }

        file_data
    }

    fn analyze_file_parallel(
        &self,
        file_path: &Path,
        functions: &[&FunctionMetrics],
        coverage_data: Option<&LcovData>,
        no_god_object: bool,
    ) -> Option<FileDebtItem> {
        let functions_owned = clone_function_metrics(functions);
        let extracted = self
            .extracted_data
            .as_ref()
            .and_then(|data| data.get(file_path));
        let file_content = std::fs::read_to_string(file_path).ok();
        let mut processed =
            crate::builders::unified_analysis_phases::phases::file_analysis::process_file_metrics_with_facts(
                file_path.to_path_buf(),
                functions_owned,
                crate::builders::unified_analysis_phases::phases::file_analysis::FileAnalysisFacts {
                    content: file_content.as_deref(),
                    extracted,
                    line_count: self.line_count_index.get(file_path).copied(),
                },
                coverage_data,
                no_god_object,
                &self.project_path,
            );
        processed.file_metrics.function_scores.clear();
        let item =
            crate::builders::unified_analysis_phases::phases::file_analysis::create_file_debt_item(
                processed.file_metrics,
                Some(&processed.file_context),
            );

        if should_emit_file_item(&item) {
            Some(item)
        } else {
            None
        }
    }

    /// Build the final unified analysis from parallel results
    pub fn build(
        mut self,
        data_flow_graph: DataFlowGraph,
        purity_analysis: HashMap<String, bool>,
        items: Vec<UnifiedDebtItem>,
        file_data: Vec<(FileDebtItem, Vec<FunctionMetrics>)>,
        coverage_data: Option<&LcovData>,
    ) -> (UnifiedAnalysis, AnalysisPhaseTimings) {
        let start = Instant::now();
        let total_file_items = file_data.len();

        let agg_progress = create_final_aggregation_progress(total_file_items);
        let mut unified = self.initialize_unified_analysis(data_flow_graph, &file_data);

        apply_purity_analysis(&mut unified, purity_analysis);
        add_unified_items(&mut unified, items);
        self.add_finalized_file_items(&mut unified, file_data, coverage_data);

        agg_progress.set_message("Sorting by priority and calculating impact");
        finalize_unified_analysis(&mut unified, coverage_data);
        complete_finalization_subtask(total_file_items);
        finish_aggregation_progress(&agg_progress, &unified);

        self.record_final_timing(start.elapsed());
        self.log_timing_summary();

        (unified, self.timings)
    }

    fn initialize_unified_analysis(
        &self,
        data_flow_graph: DataFlowGraph,
        _file_data: &[(FileDebtItem, Vec<FunctionMetrics>)],
    ) -> UnifiedAnalysis {
        let mut unified = UnifiedAnalysis::new((*self.call_graph).clone());
        unified.data_flow_graph = data_flow_graph;
        register_analyzed_files(&mut unified, &self.line_count_index);
        unified
    }

    fn add_finalized_file_items(
        &self,
        unified: &mut UnifiedAnalysis,
        file_data: Vec<(FileDebtItem, Vec<FunctionMetrics>)>,
        coverage_data: Option<&LcovData>,
    ) {
        let total_file_items = file_data.len();

        for (index, (file_item, raw_functions)) in file_data.into_iter().enumerate() {
            let finalized = crate::builders::unified_analysis::finalize_file_item(
                unified,
                file_item,
                &raw_functions,
                coverage_data,
                self.risk_analyzer.as_ref(),
                &self.project_path,
                &self.call_graph,
            );
            unified.add_file_item(finalized);
            update_finalization_subtask(index + 1, total_file_items);
        }
    }

    fn record_final_timing(&mut self, elapsed: Duration) {
        self.timings.sorting = elapsed;
        self.timings.total = total_analysis_duration(&self.timings);
    }

    fn log_timing_summary(&self) {
        if !self.options.progress {
            return;
        }

        log::debug!("Total parallel analysis time: {:?}", self.timings.total);
        log::debug!(
            "  - Call graph building: {:?}",
            self.timings.call_graph_building
        );
        log::debug!("  - Trait resolution: {:?}", self.timings.trait_resolution);
        log::debug!("  - Coverage loading: {:?}", self.timings.coverage_loading);
        log::debug!("  - Data flow: {:?}", self.timings.data_flow_creation);
        log::debug!("  - Purity: {:?}", self.timings.purity_analysis);
        log::debug!("  - Test detection: {:?}", self.timings.test_detection);
        log::debug!("  - Debt aggregation: {:?}", self.timings.debt_aggregation);
        log::debug!(
            "  - Function analysis: {:?}",
            self.timings.function_analysis
        );
        log::debug!("  - File analysis: {:?}", self.timings.file_analysis);
        log::debug!("  - Sorting: {:?}", self.timings.sorting);
    }
}

fn create_final_aggregation_progress(total_file_items: usize) -> indicatif::ProgressBar {
    let progress = ProgressManager::global()
        .map(|pm| pm.create_spinner("Aggregating analysis results"))
        .unwrap_or_else(indicatif::ProgressBar::hidden);

    if let Some(manager) = ProgressManager::global() {
        manager.tui_update_subtask(
            5,
            3,
            crate::tui::app::StageStatus::Active,
            Some((0, total_file_items.max(1))),
        );
    }

    progress
}

fn register_analyzed_files(
    unified: &mut UnifiedAnalysis,
    line_count_index: &HashMap<PathBuf, usize>,
) {
    for (path, line_count) in line_count_index {
        if *line_count > 0 {
            unified.register_analyzed_file(path.clone(), *line_count);
        }
    }
}

fn apply_purity_analysis(unified: &mut UnifiedAnalysis, purity_analysis: HashMap<String, bool>) {
    for (func_name, is_pure) in purity_analysis {
        if let Some(item) = unified
            .items
            .iter_mut()
            .find(|i| i.location.function == func_name)
        {
            item.is_pure = Some(is_pure);
        }
    }
}

fn add_unified_items(unified: &mut UnifiedAnalysis, items: Vec<UnifiedDebtItem>) {
    for item in items {
        unified.add_item(item);
    }
}

fn finalize_unified_analysis(unified: &mut UnifiedAnalysis, coverage_data: Option<&LcovData>) {
    unified.sort_by_priority();
    unified.calculate_total_impact();
    unified.has_coverage_data = coverage_data.is_some();

    if let Some(lcov) = coverage_data {
        unified.overall_coverage = Some(lcov.get_overall_coverage());
    }
}

fn complete_finalization_subtask(total_file_items: usize) {
    if let Some(manager) = ProgressManager::global() {
        manager.tui_update_subtask(
            5,
            3,
            crate::tui::app::StageStatus::Completed,
            Some((total_file_items.max(1), total_file_items.max(1))),
        );
    }
}

fn finish_aggregation_progress(progress: &indicatif::ProgressBar, unified: &UnifiedAnalysis) {
    progress.finish_with_message(format!(
        "Analysis complete ({} function items, {} file items)",
        unified.items.len(),
        unified.file_items.len()
    ));
}

fn total_analysis_duration(timings: &AnalysisPhaseTimings) -> Duration {
    timings.call_graph_building
        + timings.trait_resolution
        + timings.coverage_loading
        + timings.data_flow_creation
        + timings.purity_analysis
        + timings.test_detection
        + timings.debt_aggregation
        + timings.function_analysis
        + timings.file_analysis
        + timings.aggregation
        + timings.sorting
}

fn update_finalization_subtask(current: usize, total: usize) {
    let Some(manager) = ProgressManager::global() else {
        return;
    };

    let should_refresh = current == total || current == 1 || current % 10 == 0;
    if should_refresh {
        manager.tui_update_subtask(
            5,
            3,
            crate::tui::app::StageStatus::Active,
            Some((current, total.max(1))),
        );
    }
}

/// Trait for parallel analysis
pub trait ParallelAnalyzer {
    fn analyze_parallel(
        &self,
        options: ParallelUnifiedAnalysisOptions,
    ) -> Result<UnifiedAnalysis, anyhow::Error>;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::priority::call_graph::CallType;

    fn function_id(file: &str, name: &str, line: usize) -> FunctionId {
        FunctionId::new(PathBuf::from(file), name.to_string(), line)
    }

    fn graph_with_functions(functions: &[FunctionId]) -> CallGraph {
        let mut graph = CallGraph::new();
        for func in functions.iter() {
            graph.add_function(func.clone(), false, false, 1, 10);
        }
        graph
    }

    #[test]
    fn test_only_detector_marks_helper_called_only_by_tests() {
        let test = function_id("tests/integration.rs", "test_parses_input", 10);
        let helper = function_id("src/parser.rs", "build_fixture", 20);
        let mut graph = graph_with_functions(&[test.clone(), helper.clone()]);
        graph.add_call_parts(test, helper.clone(), CallType::Direct);

        let detector = OptimizedTestDetector::new(Arc::new(graph));

        assert!(detector.is_test_only(&helper));
    }

    #[test]
    fn test_only_detector_rejects_helper_reachable_from_production_root() {
        let test = function_id("tests/integration.rs", "test_parses_input", 10);
        let production = function_id("src/main.rs", "main", 1);
        let helper = function_id("src/parser.rs", "build_fixture", 20);
        let mut graph = graph_with_functions(&[test.clone(), production.clone(), helper.clone()]);
        graph.add_call_parts(test, helper.clone(), CallType::Direct);
        graph.add_call_parts(production, helper.clone(), CallType::Direct);

        let detector = OptimizedTestDetector::new(Arc::new(graph));

        assert!(!detector.is_test_only(&helper));
    }

    #[test]
    fn parallel_phase_uses_canonical_test_only_classification() {
        let attributed_test = function_id("src/parser.rs", "checks_input", 10);
        let helper = function_id("src/parser.rs", "build_fixture", 20);
        let mut graph = CallGraph::new();
        graph.add_function(attributed_test.clone(), false, true, 2, 5);
        graph.add_function(helper.clone(), false, false, 5, 20);
        graph.add_call_parts(attributed_test, helper.clone(), CallType::Direct);
        let expected = graph.find_test_only_functions().into_iter().collect();
        let mut builder = ParallelUnifiedAnalysisBuilder::new(
            graph,
            ParallelUnifiedAnalysisOptions {
                progress: false,
                ..ParallelUnifiedAnalysisOptions::default()
            },
        );

        let (_, _, actual, _) = builder.execute_phase1_parallel(&[], None);

        assert!(actual.contains(&helper));
        assert_eq!(actual, expected);
    }
}