debtmap 0.16.4

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
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
use crate::{
    analysis::ContextDetector,
    analyzers::FileAnalyzer,
    builders::unified_analysis_phases::phases::scoring::{
        build_suppression_context_cache, SuppressionContextCache,
    },
    core::FunctionMetrics,
    data_flow::DataFlowGraph,
    extraction::ExtractedFileData,
    priority::{
        call_graph::{CallGraph, FunctionId},
        debt_aggregator::{DebtAggregator, FunctionId as AggregatorFunctionId},
        file_metrics::FileDebtItem,
        scoring::ContextRecommendationEngine,
        UnifiedAnalysis, UnifiedAnalysisUtils, UnifiedDebtItem,
    },
    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};
use tracing::{debug_span, warn};

/// 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()
}

/// Check if a god object should be suppressed based on file annotations.
/// Same logic as orchestration.rs - checks both file-level and struct-level suppressions.
fn is_god_object_suppressed_parallel(
    god_analysis: &crate::organization::GodObjectAnalysis,
    file_content: &str,
    file_path: &Path,
) -> bool {
    use crate::core::Language;
    use crate::debt::suppression::parse_suppression_comments;
    use crate::organization::DetectionType;
    use crate::priority::DebtType;

    // Determine language from file extension
    let language = file_path
        .extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| match ext {
            "rs" => Language::Rust,
            "py" | "pyw" => Language::Python,
            _ => Language::Rust,
        })
        .unwrap_or(Language::Rust);

    let suppression_context = parse_suppression_comments(file_content, language, file_path);

    // Create a representative GodObject debt type for suppression checking
    let god_object_debt_type = DebtType::GodObject {
        methods: god_analysis.method_count as u32,
        fields: Some(god_analysis.field_count as u32),
        responsibilities: god_analysis.responsibility_count as u32,
        god_object_score: god_analysis.god_object_score,
        lines: god_analysis.lines_of_code as u32,
    };

    // First, always check for file-level suppression at the top of the file
    // A file-level annotation applies to all god objects in the file
    for check_line in 1..=6 {
        if suppression_context.is_suppressed(check_line, &god_object_debt_type) {
            return true;
        }
        if suppression_context.is_function_allowed(check_line, &god_object_debt_type) {
            return true;
        }
    }

    // For GodClass, also check near the struct definition line
    if let DetectionType::GodClass = god_analysis.detection_type {
        let struct_line = god_analysis.struct_line.unwrap_or(1);
        if suppression_context.is_suppressed(struct_line, &god_object_debt_type) {
            return true;
        }
        if suppression_context.is_function_allowed(struct_line, &god_object_debt_type) {
            return true;
        }
    }

    false
}

// Pure functional transformations module
mod transformations {
    use super::*;

    /// Pure function to create function mappings from metrics
    pub fn create_function_mappings(
        metrics: &[FunctionMetrics],
    ) -> Vec<(AggregatorFunctionId, usize, usize)> {
        metrics
            .iter()
            .map(|m| {
                let func_id = AggregatorFunctionId::new(m.file.clone(), m.name.clone(), m.line);
                (func_id, m.line, m.line + m.length)
            })
            .collect()
    }

    /// Pure function to transform metrics into purity map
    pub fn metrics_to_purity_map(metrics: &[FunctionMetrics]) -> HashMap<String, bool> {
        metrics
            .iter()
            .map(|m| (m.name.clone(), m.is_pure.unwrap_or(false)))
            .collect()
    }

    // Note: extract_purity_analysis removed in spec 213.
    // The fallback path now uses UnifiedFileExtractor + populate_all_from_extracted instead.
}

// Pure predicates module for filtering logic
mod predicates {
    use super::*;

    /// Pure predicate: should skip test functions
    pub fn is_test_function(metric: &FunctionMetrics) -> bool {
        metric.is_test || metric.in_test_module
    }

    /// Pure predicate: is closure function
    pub fn is_closure(metric: &FunctionMetrics) -> bool {
        metric.name.contains("<closure@")
    }

    /// Pure predicate: is trivial function
    pub fn is_trivial_function(metric: &FunctionMetrics, callee_count: usize) -> bool {
        metric.cyclomatic == 1 && metric.cognitive == 0 && metric.length <= 3 && callee_count == 1
    }

    /// Pure predicate: should process metric
    pub fn should_process_metric(
        metric: &FunctionMetrics,
        test_only_functions: &HashSet<FunctionId>,
        callee_count: usize,
    ) -> bool {
        // Early returns for test functions and closures
        if is_test_function(metric) || is_closure(metric) {
            return false;
        }

        let func_id = FunctionId::new(metric.file.clone(), metric.name.clone(), metric.line);

        // Skip if in test-only functions set
        if test_only_functions.contains(&func_id) {
            return false;
        }

        // Skip trivial functions
        !is_trivial_function(metric, callee_count)
    }
}

// Pure file analysis transformations
mod file_analysis {
    use super::*;
    use crate::analyzers::file_analyzer::UnifiedFileAnalyzer;
    use crate::priority::file_metrics::FileDebtMetrics;

    /// Pure function to aggregate function metrics into file metrics
    pub fn aggregate_file_metrics(
        functions: &[FunctionMetrics],
        coverage_data: Option<&LcovData>,
    ) -> FileDebtMetrics {
        let file_analyzer = UnifiedFileAnalyzer::new(coverage_data.cloned());
        file_analyzer.aggregate_functions(functions)
    }

    /// Pure function to analyze god object from file content
    pub fn analyze_god_object(
        content: &str,
        file_path: &Path,
        coverage_data: Option<&LcovData>,
    ) -> Result<Option<crate::organization::GodObjectAnalysis>, String> {
        let file_analyzer = UnifiedFileAnalyzer::new(coverage_data.cloned());
        file_analyzer
            .analyze_file(file_path, content)
            .map(|analyzed| analyzed.god_object_analysis)
            .map_err(|e| format!("Failed to analyze god object: {}", e))
    }

    /// Pure function to determine if file should be included based on score
    pub fn should_include_file(score: f64) -> bool {
        score > 50.0
    }
}

/// 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,
    // 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() {
                // Check if this is a test function
                if func_id.name.starts_with("test_")
                    || func_id.name.contains("::test")
                    || func_id.file.to_string_lossy().contains("/tests/")
                    || func_id.file.to_string_lossy().contains("_test.rs")
                {
                    test_roots.insert(func_id.clone());
                }
            }
        }

        test_roots
    }

    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 !visited.insert(current.clone()) {
                continue;
            }

            let callers = self.call_graph.get_callers(&current);
            if callers.is_empty() {
                // Found a root that's not a test
                if !self.test_roots.contains(&current) {
                    return false;
                }
            } else {
                for caller in callers {
                    if !visited.contains(&caller) {
                        queue.push(caller);
                    }
                }
            }
        }

        true
    }

    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();
            let mut data_flow = DataFlowGraph::from_call_graph((*call_graph).clone());

            // Spec 214: Use extraction adapters to populate data flow from extracted data
            let (purity_count, mutation_count, io_count, dep_count, trans_count) =
                if let Some(ref extracted) = extracted_data {
                    progress.set_message("Populating from extracted data (spec 214)...");
                    let stats = crate::extraction::adapters::data_flow::populate_data_flow(
                        &mut data_flow,
                        extracted,
                    );
                    (
                        stats.purity_entries,
                        stats.purity_entries, // Mutations counted as part of purity
                        stats.io_operations,
                        stats.variable_deps,
                        stats.transformations,
                    )
                } else {
                    // Fallback: Extract all files first, then populate via adapter
                    progress.set_message("Extracting file data (fallback path)...");

                    // Collect unique file paths from metrics
                    let file_paths: HashSet<PathBuf> = metrics.iter().map(|m| m.file.clone()).collect();

                    // Extract all data from files using the unified extractor
                    let fallback_extracted: HashMap<PathBuf, ExtractedFileData> = file_paths
                        .into_iter()
                        .filter(|p| p.extension().map(|e| e == "rs").unwrap_or(false))
                        .filter_map(|path| {
                            std::fs::read_to_string(&path)
                                .ok()
                                .and_then(|content| {
                                    crate::extraction::UnifiedFileExtractor::extract(&path, &content).ok()
                                })
                                .map(|data| (path, data))
                        })
                        .collect();

                    progress.set_message("Populating from extracted data (fallback)...");
                    let stats = crate::extraction::adapters::data_flow::populate_data_flow(
                        &mut data_flow,
                        &fallback_extracted,
                    );
                    (
                        stats.purity_entries,
                        stats.purity_entries, // Mutations counted as part of purity
                        stats.io_operations,
                        stats.variable_deps,
                        stats.transformations,
                    )
                };

            // Populate purity info from metrics as fallback (matches sequential behavior)
            // This ensures consistent scoring when source files aren't available (e.g., in tests)
            progress.set_message("Populating purity analysis from metrics...");
            for metric in metrics.iter() {
                let func_id = FunctionId::new(metric.file.clone(), metric.name.clone(), metric.line);
                let purity_info = crate::data_flow::PurityInfo {
                    is_pure: metric.is_pure.unwrap_or(false),
                    confidence: metric.purity_confidence.unwrap_or(0.0),
                    impurity_reasons: if !metric.is_pure.unwrap_or(false) {
                        vec!["Function may have side effects".to_string()]
                    } else {
                        vec![]
                    },
                };
                data_flow.set_purity_info(func_id, purity_info);
            }

            // 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(format!(
                "Data flow complete: {} functions, {} mutations, {} I/O ops, {} deps, {} transforms",
                purity_count,
                mutation_count,
                io_count,
                dep_count,
                trans_count
            ));
        });
    }

    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 = transformations::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 detector = OptimizedTestDetector::new(call_graph);
            let test_funcs = detector.find_all_test_only_functions();
            // 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 mut debt_aggregator = DebtAggregator::new();

            if let Some(debt_items) = debt_items {
                let function_mappings = transformations::create_function_mappings(&metrics);
                debt_aggregator.aggregate_debt(debt_items, &function_mappings);
            }

            // 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,
            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 {
                    if 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> {
        // Get callee count for triviality check
        let func_id = FunctionId::new(metric.file.clone(), metric.name.clone(), metric.line);
        let callee_count = self.call_graph.get_callees(&func_id).len();

        // Apply filtering predicates
        if !predicates::should_process_metric(metric, test_only_functions, callee_count) {
            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.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() {
                    if 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> {
        // Transform to owned functions
        let functions_owned: Vec<FunctionMetrics> = functions.iter().map(|&f| f.clone()).collect();

        // Pure: aggregate function metrics
        let mut file_metrics =
            file_analysis::aggregate_file_metrics(&functions_owned, coverage_data);

        // Spec 195: Use cached line count from Phase 1 if available
        let cached_line_count = self.line_count_index.get(file_path).copied();

        // Early filtering: Skip god object analysis for small files (spec 195)
        // Uses cached line count when available to avoid unnecessary file I/O
        let estimated_lines = cached_line_count.unwrap_or_else(|| {
            // Fallback: estimate from function metrics (less accurate but avoids I/O)
            functions_owned.iter().map(|f| f.length).sum::<usize>()
        });
        let skip_god_object_analysis =
            no_god_object || (estimated_lines < 500 && file_metrics.function_count < 20);

        // Spec 214: Use extracted data when available (avoids file I/O)
        let extracted_file_data = self
            .extracted_data
            .as_ref()
            .and_then(|data| data.get(file_path));

        if let Some(extracted) = extracted_file_data {
            // Use extracted data - no file I/O needed
            file_metrics.total_lines = extracted.total_lines;
            file_metrics.uncovered_lines =
                ((1.0 - file_metrics.coverage_percent) * extracted.total_lines as f64) as usize;

            // Use god object adapter with extracted data
            file_metrics.god_object_analysis = if skip_god_object_analysis {
                None
            } else {
                crate::extraction::adapters::god_object::analyze_god_object(file_path, extracted)
            };
        } else {
            // Fallback: read file content when extracted data not available
            let needs_file_read = cached_line_count.is_none() || !skip_god_object_analysis;

            if needs_file_read {
                if let Ok(content) = std::fs::read_to_string(file_path) {
                    let actual_line_count = content.lines().count();
                    file_metrics.total_lines = actual_line_count;

                    // Recalculate uncovered lines based on actual line count
                    file_metrics.uncovered_lines =
                        ((1.0 - file_metrics.coverage_percent) * actual_line_count as f64) as usize;

                    // Handle god object detection with accurate line count
                    file_metrics.god_object_analysis = if skip_god_object_analysis {
                        None
                    } else {
                        let analysis_result =
                            file_analysis::analyze_god_object(&content, file_path, coverage_data);

                        let analyzed = analysis_result.unwrap_or(None);

                        // Use heuristic fallback if:
                        // 1. Analysis failed (analyzed is None), OR
                        // 2. Analysis succeeded but said not god object, BUT heuristic thresholds are met
                        // This ensures simple god objects (many low-complexity methods) are caught
                        // (Spec 212: Uses shared heuristics from organization::god_object::heuristics)
                        if analyzed.as_ref().is_some_and(|a| a.is_god_object) {
                            // Analysis found a god object, use it
                            analyzed
                        } else {
                            // Try heuristic fallback with preserved analysis data
                            crate::organization::god_object::heuristics::fallback_with_preserved_analysis(
                                file_metrics.function_count,
                                actual_line_count,
                                file_metrics.total_complexity,
                                analyzed.as_ref(),
                            ).or(analyzed)
                        }
                    };
                } else {
                    // Fallback to estimated metrics if file can't be read
                    file_metrics.god_object_analysis = if no_god_object {
                        None
                    } else {
                        self.analyze_god_object_with_io(file_path, coverage_data)
                    };
                }
            } else {
                // Spec 195: Use cached line count - no file I/O needed
                file_metrics.total_lines = cached_line_count.unwrap_or(estimated_lines);
                file_metrics.uncovered_lines = ((1.0 - file_metrics.coverage_percent)
                    * file_metrics.total_lines as f64)
                    as usize;
                file_metrics.god_object_analysis = None; // Small files skip god object analysis
            }
        } // End of else block for extracted data fallback

        // Calculate function scores from items already created in phase 2
        // Note: In parallel execution, items are not yet in unified analysis at this point
        // So function_scores will remain empty, which is consistent with the builder.build() approach
        // where items are added after file analysis. This maintains functional purity.
        file_metrics.function_scores = Vec::new();

        // Detect file context for scoring adjustments (spec 166/168)
        use crate::analysis::FileContextDetector;
        use crate::core::Language;
        let language = Language::from_path(file_path);
        let detector = FileContextDetector::new(language);
        let file_context = detector.detect(file_path, &functions_owned);

        // Create FileDebtItem with context-aware scoring
        let item = crate::priority::FileDebtItem::from_metrics(file_metrics, Some(&file_context));

        // Include file if it meets score threshold OR is a god object (spec 207)
        // God objects should always be included as they represent architectural issues
        let has_god_object = item
            .metrics
            .god_object_analysis
            .as_ref()
            .is_some_and(|analysis| analysis.is_god_object);

        if file_analysis::should_include_file(item.score) || has_god_object {
            Some(item)
        } else {
            None
        }
    }

    /// I/O wrapper for god object analysis
    fn analyze_god_object_with_io(
        &self,
        file_path: &Path,
        coverage_data: Option<&LcovData>,
    ) -> Option<crate::organization::GodObjectAnalysis> {
        let _span = debug_span!("analyze_god_object", path = %file_path.display()).entered();

        // I/O: Read file content
        let content = std::fs::read_to_string(file_path)
            .map_err(|e| {
                warn!(file = %file_path.display(), error = %e, "Failed to read file");
                e
            })
            .ok()?;

        // Pure: Analyze content
        file_analysis::analyze_god_object(&content, file_path, coverage_data)
            .map_err(|e| {
                warn!(file = %file_path.display(), error = %e, "Failed to analyze god object");
                e
            })
            .ok()
            .flatten() // Flatten Option<Option<GodObjectAnalysis>> to Option<GodObjectAnalysis>
    }

    /// 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();

        // Create progress spinner for final aggregation
        let agg_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))),
            );
        }

        let mut unified = UnifiedAnalysis::new((*self.call_graph).clone());
        unified.data_flow_graph = data_flow_graph;

        // Spec 201: Register all analyzed files for accurate total LOC calculation
        // Use cached total_lines from FileDebtMetrics (avoids redundant file I/O)
        for (file_item, _) in &file_data {
            if file_item.metrics.total_lines > 0 {
                unified.register_analyzed_file(
                    file_item.metrics.path.clone(),
                    file_item.metrics.total_lines,
                );
            }
        }

        // Add purity information
        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);
            }
        }

        // Add all items
        for item in items {
            unified.add_item(item);
        }

        // Add file items and create god object UnifiedDebtItems (spec 207)
        for (index, (file_item, raw_functions)) in file_data.into_iter().enumerate() {
            // Check if this file has god object analysis
            if let Some(ref god_analysis) = file_item.metrics.god_object_analysis {
                if god_analysis.is_god_object {
                    // Check if this god object should be suppressed via debtmap:ignore[god_object]
                    let is_suppressed = std::fs::read_to_string(&file_item.metrics.path)
                        .ok()
                        .is_some_and(|content| {
                            is_god_object_suppressed_parallel(
                                god_analysis,
                                &content,
                                &file_item.metrics.path,
                            )
                        });

                    if is_suppressed {
                        // Skip creating the god object debt item, but still process file item
                        // Clear god_object_analysis from file metrics when suppressed
                        let mut file_item = file_item;
                        file_item.metrics.god_object_analysis = None;
                        let file_item_with_deps =
                            enrich_file_item_with_dependencies(file_item, &unified.items);
                        unified.add_file_item(file_item_with_deps);
                        update_finalization_subtask(index + 1, total_file_items);
                        continue;
                    }

                    // Aggregate from raw metrics first for complexity (includes ALL functions, even tests)
                    use crate::priority::god_object_aggregation::{
                        aggregate_coverage_from_raw_metrics, aggregate_from_raw_metrics,
                        aggregate_god_object_metrics, extract_member_functions,
                    };

                    let mut aggregated_metrics = aggregate_from_raw_metrics(&raw_functions);

                    // Aggregate coverage from ALL raw functions (not just debt items)
                    // This ensures god objects show accurate coverage even when member
                    // functions are filtered out by complexity thresholds.
                    if let Some(lcov) = coverage_data {
                        aggregated_metrics.weighted_coverage =
                            aggregate_coverage_from_raw_metrics(&raw_functions, lcov);
                    }

                    // Enrich with contextual risk
                    // NOTE: Dependencies are already aggregated from raw metrics (complete architectural view).
                    let member_functions =
                        extract_member_functions(unified.items.iter(), &file_item.metrics.path);
                    if !member_functions.is_empty() {
                        let item_metrics = aggregate_god_object_metrics(&member_functions);

                        // Spec 248: Prefer direct file-level git analysis over member aggregation
                        aggregated_metrics.aggregated_contextual_risk = self
                            .risk_analyzer
                            .as_ref()
                            .and_then(|analyzer| {
                                crate::builders::unified_analysis::analyze_file_git_context(
                                    &file_item.metrics.path,
                                    analyzer,
                                    &self.project_path,
                                )
                            })
                            .or(item_metrics.aggregated_contextual_risk); // Fallback to member aggregation
                    } else {
                        // Spec 248: When no member functions, try direct file analysis
                        aggregated_metrics.aggregated_contextual_risk =
                            self.risk_analyzer.as_ref().and_then(|analyzer| {
                                crate::builders::unified_analysis::analyze_file_git_context(
                                    &file_item.metrics.path,
                                    analyzer,
                                    &self.project_path,
                                )
                            });
                    }
                    // Dependencies are already populated from raw metrics (complete architectural view)

                    // Enrich god_analysis with aggregated entropy and error swallowing data
                    let mut god_analysis = god_analysis.clone();
                    god_analysis.aggregated_entropy = aggregated_metrics.aggregated_entropy.clone();
                    god_analysis.aggregated_error_swallowing_count =
                        if aggregated_metrics.total_error_swallowing_count > 0 {
                            Some(aggregated_metrics.total_error_swallowing_count)
                        } else {
                            None
                        };
                    god_analysis.aggregated_error_swallowing_patterns =
                        if !aggregated_metrics.error_swallowing_patterns.is_empty() {
                            Some(aggregated_metrics.error_swallowing_patterns.clone())
                        } else {
                            None
                        };

                    // Create god object UnifiedDebtItem using same function as sequential path
                    let mut god_item =
                        crate::builders::unified_analysis::create_god_object_debt_item(
                            &file_item.metrics.path,
                            &file_item.metrics,
                            &god_analysis,
                            aggregated_metrics,
                            coverage_data,
                            Some(&self.call_graph),
                        );

                    // Generate context suggestion for AI agents (spec 263)
                    use crate::priority::context::{generate_context_suggestion, ContextConfig};
                    let context_config = ContextConfig::default();
                    god_item.context_suggestion =
                        generate_context_suggestion(&god_item, &self.call_graph, &context_config);

                    unified.add_item(god_item);
                }
            }

            // Spec 201: Enrich file item with dependency metrics aggregated from function-level data
            let file_item_with_deps = enrich_file_item_with_dependencies(file_item, &unified.items);
            unified.add_file_item(file_item_with_deps);
            update_finalization_subtask(index + 1, total_file_items);
        }

        agg_progress.set_message("Sorting by priority and calculating impact");

        // Final sorting and impact calculation
        unified.sort_by_priority();
        unified.calculate_total_impact();

        // Set coverage data availability flag (spec 108)
        unified.has_coverage_data = coverage_data.is_some();

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

        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))),
            );
        }

        agg_progress.finish_with_message(format!(
            "Analysis complete ({} function items, {} file items)",
            unified.items.len(),
            unified.file_items.len()
        ));

        self.timings.sorting = start.elapsed();
        self.timings.total = self.timings.call_graph_building
            + self.timings.trait_resolution
            + self.timings.coverage_loading
            + self.timings.data_flow_creation
            + self.timings.purity_analysis
            + self.timings.test_detection
            + self.timings.debt_aggregation
            + self.timings.function_analysis
            + self.timings.file_analysis
            + self.timings.aggregation
            + self.timings.sorting;

        if self.options.progress {
            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);
        }

        (unified, self.timings)
    }
}

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))),
        );
    }
}

/// Enrich file item with dependency metrics aggregated from function-level data (spec 201)
fn enrich_file_item_with_dependencies(
    mut file_item: crate::priority::FileDebtItem,
    unified_items: &im::Vector<crate::priority::UnifiedDebtItem>,
) -> crate::priority::FileDebtItem {
    use crate::priority::god_object_aggregation::{
        aggregate_dependency_metrics, extract_member_functions,
    };

    let member_functions = extract_member_functions(unified_items.iter(), &file_item.metrics.path);
    let (callers, callees, afferent, efferent) = aggregate_dependency_metrics(&member_functions);

    // Update file metrics with aggregated dependency data
    file_item.metrics.afferent_coupling = afferent;
    file_item.metrics.efferent_coupling = efferent;
    file_item.metrics.instability =
        crate::output::unified::calculate_instability(afferent, efferent);
    file_item.metrics.dependents = callers.into_iter().take(10).collect();
    file_item.metrics.dependencies_list = callees.into_iter().take(10).collect();

    file_item
}

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