repotoire 0.8.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
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
//! Graph-based health scorer
//!
//! Uses the code graph to compute positive architectural signals,
//! combined with finding penalties for the final score.

use crate::config::ProjectConfig;
use crate::detectors::api_surface::is_api_surface;
use crate::graph::{GraphQuery, GraphQueryExt};
use crate::models::{Finding, FindingStatus, Grade, Severity};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashSet};
use tracing::{debug, info};

/// Mark compound smells (multiple different issues co-located) for prioritization
/// Research shows compound smells correlate with 78% more dependencies (arXiv:2509.03896)
/// NOTE: This adds metadata only - does NOT change severity (to preserve accurate scoring)
pub fn escalate_compound_smells(findings: &mut [Finding]) {
    // Group findings by location (file + overlapping line ranges)
    // BTreeMap for deterministic iteration order
    let mut location_groups: BTreeMap<String, Vec<usize>> = BTreeMap::new();

    for (idx, finding) in findings.iter().enumerate() {
        if finding.affected_files.is_empty() {
            continue;
        }

        let file = finding.affected_files[0].to_string_lossy().to_string();
        let line_start = finding.line_start.unwrap_or(0);
        let _line_end = finding.line_end.unwrap_or(line_start);

        // Use 50-line buckets to group nearby findings
        let bucket = line_start / 50;
        let key = format!("{}:{}", file, bucket);

        location_groups.entry(key).or_default().push(idx);
    }

    // Check each location for compound smells
    for (_location, indices) in location_groups.iter() {
        if indices.len() < 2 {
            continue;
        }

        // Count unique detector types
        let unique_detectors: HashSet<&str> = indices
            .iter()
            .map(|&idx| findings[idx].detector.as_str())
            .collect();

        let detector_count = unique_detectors.len();

        if detector_count < 2 {
            continue;
        }
        // Mark as compound smell (for prioritization in UI/reports)
        for &idx in indices {
            if findings[idx].description.starts_with("[COMPOUND") {
                continue;
            }
            // Add metadata without changing severity
            findings[idx].description = format!(
                "[COMPOUND: {} co-located issues] {}",
                detector_count, findings[idx].description
            );
            // Boost confidence for compound smells, clamped to 1.0 (#67)
            findings[idx].confidence =
                Some((findings[idx].confidence.unwrap_or(0.7) + 0.1).min(1.0));
        }
        debug!(
            "Marked {} findings as compound smell ({} detectors)",
            indices.len(),
            detector_count
        );
    }
}

/// Maximum bonus percentages for each positive signal
const MAX_MODULARITY_BONUS: f64 = 0.10; // 10% max
const MAX_COHESION_BONUS: f64 = 0.05; // 5% max
const MAX_CLEAN_DEPS_BONUS: f64 = 0.10; // 10% max
const MAX_COMPLEXITY_DIST_BONUS: f64 = 0.05; // 5% max
const MAX_TEST_COVERAGE_BONUS: f64 = 0.05; // 5% max

/// Breakdown of a single pillar score
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PillarBreakdown {
    /// Pillar name
    pub name: String,
    /// Base score before bonuses (100 - penalties)
    pub base_score: f64,
    /// Total bonus from positive signals (0.0 - 0.35)
    pub bonus_ratio: f64,
    /// Final score after bonuses
    pub final_score: f64,
    /// Individual bonus contributions
    pub bonuses: Vec<(String, f64)>,
    /// Penalty from findings
    pub penalty_points: f64,
    /// Number of findings affecting this pillar
    pub finding_count: usize,
}

/// Complete score breakdown for transparency
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ScoreBreakdown {
    /// Overall health score (0-100+)
    pub overall_score: f64,
    /// Letter grade
    pub grade: crate::models::Grade,
    /// Structure pillar breakdown
    pub structure: PillarBreakdown,
    /// Quality pillar breakdown  
    pub quality: PillarBreakdown,
    /// Architecture pillar breakdown
    pub architecture: PillarBreakdown,
    /// Graph-derived metrics
    pub graph_metrics: GraphMetrics,
}

/// Metrics derived from the code graph
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GraphMetrics {
    /// Number of modules (directories with code)
    pub module_count: usize,
    /// Average coupling between modules (0-1, lower is better)
    pub avg_coupling: f64,
    /// Average cohesion within modules (0-1, higher is better)
    pub avg_cohesion: f64,
    /// Number of circular dependency cycles
    pub cycle_count: usize,
    /// Percentage of functions with complexity <= 10
    pub simple_function_ratio: f64,
    /// Percentage of files that are tests
    pub test_file_ratio: f64,
    /// Total functions analyzed
    pub total_functions: usize,
    /// Total files analyzed
    pub total_files: usize,
    /// Total lines of code across all files
    pub total_loc: usize,
}

/// Which pillar a finding belongs to
#[derive(Debug, Clone, Copy, PartialEq)]
enum Pillar {
    Structure,
    Quality,
    Architecture,
}

/// Format a single pillar breakdown into markdown lines.
fn format_pillar_breakdown(pillar: &PillarBreakdown, lines: &mut Vec<String>) {
    lines.push(format!(
        "## {} Score: {:.1}\n",
        pillar.name, pillar.final_score
    ));
    lines.push(format!(
        "- Base: 100 - {:.2} penalties = {:.1}",
        pillar.penalty_points, pillar.base_score
    ));
    let total_bonus: f64 = pillar.bonuses.iter().map(|(_, v)| v).sum::<f64>() * 100.0;
    let capped = if pillar.penalty_points > 0.0 {
        total_bonus.min(pillar.penalty_points * 0.5)
    } else {
        total_bonus
    };
    let active_bonuses: Vec<_> = pillar.bonuses.iter().filter(|(_, v)| *v > 0.001).collect();
    if !active_bonuses.is_empty() {
        lines.push("- Bonuses (additive, capped at 50% of penalty):".to_string());
        for (name, value) in &active_bonuses {
            let pts = value * 100.0;
            lines.push(format!("  - {name}: +{pts:.1} pts"));
        }
    }
    if capped < total_bonus {
        lines.push(format!(
            "  - *(capped from {:.1} to {:.1} pts)*",
            total_bonus, capped
        ));
    }
    lines.push(format!("- Final: {:.1}", pillar.final_score));
    lines.push(format!("- Findings: {}\n", pillar.finding_count));
}

/// Classify a finding into a pillar based on its category and detector name.
/// Every category maps to exactly one pillar — no splitting.
fn classify_pillar(category: &str, detector: &str, is_security: bool) -> Pillar {
    // Security always → Quality (it's a code quality issue)
    if is_security {
        return Pillar::Quality;
    }

    match category {
        // Structure: code shape, readability, size, naming
        c if c.contains("complex") => Pillar::Structure,
        c if c.contains("naming") => Pillar::Structure,
        c if c.contains("readab") => Pillar::Structure,
        c if c.contains("style") => Pillar::Structure,
        c if c.contains("maintainab") => Pillar::Structure,

        // Architecture: module boundaries, dependencies, coupling
        c if c.contains("architect") => Pillar::Architecture,
        c if c.contains("bottleneck") => Pillar::Architecture,
        c if c.contains("circular") => Pillar::Architecture,
        c if c.contains("coupling") => Pillar::Architecture,

        // Quality: correctness, reliability, performance, error handling
        c if c.contains("security") => Pillar::Quality,
        c if c.contains("reliab") => Pillar::Quality,
        c if c.contains("correct") => Pillar::Quality,
        c if c.contains("performance") => Pillar::Quality,
        c if c.contains("error") => Pillar::Quality,
        c if c.contains("safety") => Pillar::Quality,

        // Fallback: use detector name heuristics
        _ => {
            if detector.contains("dependency") || detector.contains("import") {
                Pillar::Architecture
            } else if detector.contains("large")
                || detector.contains("nesting")
                || detector.contains("dead")
                || detector.contains("naming")
            {
                Pillar::Structure
            } else {
                // Default: Quality (correctness, misc)
                Pillar::Quality
            }
        }
    }
}

/// Graph-aware health scorer
pub struct GraphScorer<'a> {
    graph: &'a dyn GraphQuery,
    config: &'a ProjectConfig,
    repo_path: &'a std::path::Path,
}

impl<'a> GraphScorer<'a> {
    // repotoire:ignore[surprisal] — constructor with many parameters is expected for scorer
    pub fn new(
        graph: &'a dyn GraphQuery,
        config: &'a ProjectConfig,
        repo_path: &'a std::path::Path,
    ) -> Self {
        Self {
            graph,
            config,
            repo_path,
        }
    }

    /// Calculate complete health score with breakdown
    pub fn calculate(&self, findings: &[Finding]) -> ScoreBreakdown {
        // Compute graph metrics first
        let metrics = self.compute_graph_metrics();

        let project_type = self.config.project_type(self.repo_path);
        debug!(
            "Scoring with project type {:?} (coupling mult: {:.1}x, complexity mult: {:.1}x)",
            project_type,
            project_type.coupling_multiplier(),
            project_type.complexity_multiplier(),
        );

        // Calculate bonuses from graph analysis
        let modularity_bonus = self.calculate_modularity_bonus(&metrics);
        let cohesion_bonus = self.calculate_cohesion_bonus(&metrics);
        let clean_deps_bonus = self.calculate_clean_deps_bonus(&metrics);
        let complexity_bonus = self.calculate_complexity_bonus(&metrics);
        let test_bonus = self.calculate_test_bonus(&metrics);

        debug!(
            "Graph bonuses: modularity={:.1}%, cohesion={:.1}%, clean_deps={:.1}%, complexity={:.1}%, tests={:.1}%",
            modularity_bonus * 100.0,
            cohesion_bonus * 100.0,
            clean_deps_bonus * 100.0,
            complexity_bonus * 100.0,
            test_bonus * 100.0
        );

        // Flat severity-based penalties — each finding subtracts from 100 based on
        // its severity, independent of repo size. A vulnerability is a vulnerability
        // whether it's in 1k or 500k LOC.
        //
        // Calibrated against 56 open-source repos with noise-reduced detectors
        // (~80-100 high-confidence findings per repo). With these weights:
        //   - 1 critical finding (e.g., SQL injection) = -5 points
        //   - 20 medium findings (e.g., complexity) = -10 points
        //   - A clean repo with 0 findings = 100
        //   - A typical well-maintained repo (~20 findings) = ~85-90
        //   - A repo with serious issues (~80+ findings) = ~60-75
        let severity_weight = |severity: &Severity| -> f64 {
            match severity {
                Severity::Critical => 5.0,
                Severity::High => 2.0,
                Severity::Medium => 0.5,
                Severity::Low => 0.1,
                Severity::Info => 0.0,
            }
        };

        let mut structure_penalty = 0.0;
        let mut quality_penalty = 0.0;
        let mut architecture_penalty = 0.0;
        let mut structure_count = 0;
        let mut quality_count = 0;
        let mut architecture_count = 0;

        for finding in findings {
            if finding.status == FindingStatus::Baselined {
                continue;
            }
            let base = severity_weight(&finding.severity);

            let category = finding.category.as_deref().unwrap_or("");
            let detector = finding.detector.to_lowercase();

            let is_security = self.is_security_finding(finding);
            let security_mult = if is_security {
                self.config.scoring.security_multiplier
            } else {
                1.0
            };
            let effective = base * security_mult;

            // Route findings to pillars based on category
            let pillar = classify_pillar(category, &detector, is_security);

            // Reduce architecture penalties for API surface findings —
            // high fan-in is expected for public API entry points (arXiv:2406.19254)
            let api_discount =
                if pillar == Pillar::Architecture && self.is_api_surface_finding(finding) {
                    0.5
                } else {
                    1.0
                };

            let (penalty, count) = match pillar {
                Pillar::Quality => (&mut quality_penalty, &mut quality_count),
                Pillar::Structure => (&mut structure_penalty, &mut structure_count),
                Pillar::Architecture => (&mut architecture_penalty, &mut architecture_count),
            };
            *penalty += effective * api_discount;
            *count += 1;
        }
        // Build pillar breakdowns
        let structure = self.build_pillar(
            "Structure",
            structure_penalty,
            structure_count,
            vec![("Complexity distribution", complexity_bonus)],
        );

        let quality = self.build_pillar(
            "Quality",
            quality_penalty,
            quality_count,
            vec![("Test coverage signal", test_bonus)],
        );

        let architecture = self.build_pillar(
            "Architecture",
            architecture_penalty,
            architecture_count,
            vec![
                ("Modularity (low coupling)", modularity_bonus),
                ("Cohesion", cohesion_bonus),
                ("Clean dependencies (no cycles)", clean_deps_bonus),
            ],
        );

        // Weighted overall score — normalize weights if they don't sum to 1.0 (#36)
        let mut weights = self.config.scoring.pillar_weights.clone();
        if !weights.is_valid() {
            tracing::warn!(
                "Pillar weights sum to {:.3} (expected 1.0), normalizing",
                weights.structure + weights.quality + weights.architecture
            );
            weights.normalize();
        }
        let overall = structure.final_score * weights.structure
            + quality.final_score * weights.quality
            + architecture.final_score * weights.architecture;

        let overall = overall.max(5.0);

        // Never report 100.0 if there are active medium+ findings — cap at 99.9
        let has_medium_plus = findings.iter().any(|f| {
            f.status != FindingStatus::Baselined
                && matches!(
                    f.severity,
                    Severity::Critical | Severity::High | Severity::Medium
                )
        });
        let overall = if has_medium_plus && overall >= 99.95 {
            99.9
        } else {
            overall
        };

        let grade = self.calculate_grade(overall, findings);

        info!(
            "Health score: {:.1} ({}) - Structure: {:.1}, Quality: {:.1}, Architecture: {:.1}",
            overall, grade, structure.final_score, quality.final_score, architecture.final_score
        );

        ScoreBreakdown {
            overall_score: overall,
            grade,
            structure,
            quality,
            architecture,
            graph_metrics: metrics,
        }
    }

    /// Build a pillar breakdown
    fn build_pillar(
        &self,
        name: &str,
        penalty: f64,
        finding_count: usize,
        bonuses: Vec<(&str, f64)>,
    ) -> PillarBreakdown {
        let base_score = (100.0 - penalty).clamp(25.0, 100.0);
        // Additive bonuses: each bonus adds up to its max % as points
        // e.g. 5% test bonus = +5 points, not *1.05 multiplier
        let total_bonus: f64 = bonuses.iter().map(|(_, b)| b).sum();
        let bonus_points = total_bonus * 100.0;
        // Bonuses can recover at most half the penalty — they can't fully mask issues.
        // If penalty=4 and bonus=5, you recover 2 (not 5), giving 98 not 101.
        let capped_bonus = if penalty > 0.0 {
            bonus_points.min(penalty * 0.5)
        } else {
            bonus_points
        };
        let final_score = (base_score + capped_bonus).min(100.0);

        PillarBreakdown {
            name: name.to_string(),
            base_score,
            bonus_ratio: total_bonus,
            final_score,
            bonuses: bonuses
                .into_iter()
                .map(|(n, v)| (n.to_string(), v))
                .collect(),
            penalty_points: penalty,
            finding_count,
        }
    }

    /// Compute all graph metrics.
    ///
    /// Uses NodeIndex-based API when available (CodeGraph), avoiding
    /// Vec<CodeNode> cloning and (StrKey, StrKey) pair allocation.
    fn compute_graph_metrics(&self) -> GraphMetrics {
        let i = self.graph.interner();
        let func_idxs = self.graph.functions_idx();
        let file_idxs = self.graph.files_idx();

        // Use NodeIndex-based path when available (non-empty = CodeGraph)
        if !func_idxs.is_empty() || !file_idxs.is_empty() {
            return self.compute_graph_metrics_indexed(i, func_idxs, file_idxs);
        }

        // Fallback: old API for non-CodeGraph implementors
        let functions = self.graph.get_functions();
        let files = self.graph.get_files();

        let modules: HashSet<String> = files
            .iter()
            .filter_map(|f| {
                let path = std::path::Path::new(f.path(i));
                path.parent().map(|p| p.to_string_lossy().to_string())
            })
            .collect();

        let (total_calls, cross_module_calls) = {
            let calls = self.graph.get_calls();
            let mut total = 0usize;
            let mut cross = 0usize;
            for &(src_qn, tgt_qn) in &calls {
                total += 1;
                let src_node = self.graph.get_node(i.resolve(src_qn));
                let tgt_node = self.graph.get_node(i.resolve(tgt_qn));
                if let (Some(src), Some(tgt)) = (src_node, tgt_node) {
                    let src_path = i.resolve(src.file_path);
                    let dst_path = i.resolve(tgt.file_path);
                    let src_mod = std::path::Path::new(src_path).parent();
                    let dst_mod = std::path::Path::new(dst_path).parent();
                    if src_mod != dst_mod {
                        cross += 1;
                    }
                }
            }
            (total, cross)
        };

        let avg_coupling = if total_calls == 0 {
            0.0
        } else {
            cross_module_calls as f64 / total_calls as f64
        };
        let intra_module_calls = total_calls - cross_module_calls;
        let avg_cohesion = if total_calls == 0 {
            1.0
        } else {
            intra_module_calls as f64 / total_calls as f64
        };
        let import_cycles = self.graph.find_import_cycles();
        let cycle_count = import_cycles.len();
        let simple_count = functions
            .iter()
            .filter(|f| f.complexity_opt().unwrap_or(1) <= 10)
            .count();
        let simple_ratio = if functions.is_empty() {
            1.0
        } else {
            simple_count as f64 / functions.len() as f64
        };
        let test_files = files
            .iter()
            .filter(|f| self.is_test_file(f.path(i)))
            .count();
        let test_ratio = if files.is_empty() {
            0.0
        } else {
            test_files as f64 / files.len() as f64
        };
        let total_loc: usize = files
            .iter()
            .map(|f| f.get_i64("loc").unwrap_or(0) as usize)
            .sum();

        GraphMetrics {
            module_count: modules.len(),
            avg_coupling,
            avg_cohesion,
            cycle_count,
            simple_function_ratio: simple_ratio,
            test_file_ratio: test_ratio,
            total_functions: functions.len(),
            total_files: files.len(),
            total_loc,
        }
    }

    /// NodeIndex-based graph metrics implementation for CodeGraph.
    fn compute_graph_metrics_indexed(
        &self,
        i: &crate::graph::interner::StringInterner,
        func_idxs: &[crate::graph::NodeIndex],
        file_idxs: &[crate::graph::NodeIndex],
    ) -> GraphMetrics {
        // Count modules (unique directories)
        let modules: HashSet<String> = file_idxs
            .iter()
            .filter_map(|&idx| {
                let f = self.graph.node_idx(idx)?;
                let path = std::path::Path::new(f.path(i));
                path.parent().map(|p| p.to_string_lossy().to_string())
            })
            .collect();

        // Compute coupling stats from call edges (zero-copy: NodeIndex pairs).
        let call_edges = self.graph.all_call_edges();
        let total_calls = call_edges.len();
        let cross_module_calls = call_edges
            .iter()
            .filter(|&&(src_idx, tgt_idx)| {
                if let (Some(src), Some(tgt)) =
                    (self.graph.node_idx(src_idx), self.graph.node_idx(tgt_idx))
                {
                    let src_mod = std::path::Path::new(i.resolve(src.file_path)).parent();
                    let dst_mod = std::path::Path::new(i.resolve(tgt.file_path)).parent();
                    src_mod != dst_mod
                } else {
                    false
                }
            })
            .count();

        debug!(
            "Call graph: {} total calls, {} cross-module, {} modules",
            total_calls,
            cross_module_calls,
            modules.len()
        );

        let avg_coupling = if total_calls == 0 {
            0.0
        } else {
            cross_module_calls as f64 / total_calls as f64
        };

        let intra_module_calls = total_calls - cross_module_calls;
        let avg_cohesion = if total_calls == 0 {
            1.0
        } else {
            intra_module_calls as f64 / total_calls as f64
        };

        debug!(
            "Coupling: {:.1}%, Cohesion: {:.1}%",
            avg_coupling * 100.0,
            avg_cohesion * 100.0
        );

        let cycle_count = self.graph.import_cycles_idx().len();

        let func_count = func_idxs.len();
        let simple_count = func_idxs
            .iter()
            .filter_map(|&idx| self.graph.node_idx(idx))
            .filter(|f| f.complexity_opt().unwrap_or(1) <= 10)
            .count();
        let simple_ratio = if func_count == 0 {
            1.0
        } else {
            simple_count as f64 / func_count as f64
        };

        let file_count = file_idxs.len();
        let test_files = file_idxs
            .iter()
            .filter_map(|&idx| self.graph.node_idx(idx))
            .filter(|f| self.is_test_file(f.path(i)))
            .count();
        let test_ratio = if file_count == 0 {
            0.0
        } else {
            test_files as f64 / file_count as f64
        };

        let total_loc: usize = file_idxs
            .iter()
            .filter_map(|&idx| self.graph.node_idx(idx))
            .map(|f| f.get_i64("loc").unwrap_or(0) as usize)
            .sum();

        GraphMetrics {
            module_count: modules.len(),
            avg_coupling,
            avg_cohesion,
            cycle_count,
            simple_function_ratio: simple_ratio,
            test_file_ratio: test_ratio,
            total_functions: func_count,
            total_files: file_count,
            total_loc,
        }
    }

    /// Calculate modularity bonus (low coupling is good)
    fn calculate_modularity_bonus(&self, metrics: &GraphMetrics) -> f64 {
        let cm = self
            .config
            .project_type(self.repo_path)
            .coupling_multiplier();
        // Scale thresholds by coupling multiplier:
        // - Web (1.0x): full bonus at ≤0.3, none at ≥0.7
        // - Compiler (3.0x): full bonus at ≤0.9, none at ≥1.0
        let full_threshold = (0.3 * cm).min(1.0);
        let zero_threshold = (0.7 * cm).min(1.0);
        let range = (zero_threshold - full_threshold).max(0.01);
        let coupling_score =
            1.0 - ((metrics.avg_coupling - full_threshold) / range).clamp(0.0, 1.0);
        coupling_score * MAX_MODULARITY_BONUS
    }

    /// Calculate cohesion bonus (high cohesion is good)
    fn calculate_cohesion_bonus(&self, metrics: &GraphMetrics) -> f64 {
        let cm = self
            .config
            .project_type(self.repo_path)
            .coupling_multiplier();
        // High-coupling project types expect less cohesion
        let full_threshold = (0.7 / cm).max(0.15);
        let zero_threshold = (0.3 / cm).max(0.05);
        let range = (full_threshold - zero_threshold).max(0.01);
        let cohesion_score = ((metrics.avg_cohesion - zero_threshold) / range).clamp(0.0, 1.0);
        cohesion_score * MAX_COHESION_BONUS
    }

    /// Calculate clean dependencies bonus (no cycles is good)
    fn calculate_clean_deps_bonus(&self, metrics: &GraphMetrics) -> f64 {
        // 0 cycles = full bonus, each cycle reduces by 20%
        let penalty = (metrics.cycle_count as f64 * 0.2).min(1.0);
        (1.0 - penalty) * MAX_CLEAN_DEPS_BONUS
    }

    /// Calculate complexity distribution bonus
    fn calculate_complexity_bonus(&self, metrics: &GraphMetrics) -> f64 {
        let xm = self
            .config
            .project_type(self.repo_path)
            .complexity_multiplier();
        // Scale thresholds by complexity multiplier:
        // - Web (1.0x): full bonus at 90%+ simple, none at 50%
        // - Kernel (2.0x): full bonus at 45%+ simple, none at 25%
        let full_threshold = (0.9 / xm).max(0.3);
        let zero_threshold = (0.5 / xm).max(0.1);
        let range = (full_threshold - zero_threshold).max(0.01);
        let score = ((metrics.simple_function_ratio - zero_threshold) / range).clamp(0.0, 1.0);
        score * MAX_COMPLEXITY_DIST_BONUS
    }

    /// Calculate test coverage signal bonus
    fn calculate_test_bonus(&self, metrics: &GraphMetrics) -> f64 {
        // 20%+ test files = full bonus
        // 0% = no bonus
        let score = (metrics.test_file_ratio / 0.2).clamp(0.0, 1.0);
        score * MAX_TEST_COVERAGE_BONUS
    }

    /// Check if a finding is security-related
    fn is_security_finding(&self, finding: &Finding) -> bool {
        let category = finding.category.as_deref().unwrap_or("");
        let detector = finding.detector.to_lowercase();

        category.contains("security")
            || category.contains("inject")
            || detector.contains("sql")
            || detector.contains("xss")
            || detector.contains("secret")
            || detector.contains("credential")
            || detector.contains("command")
            || detector.contains("traversal")
            || detector.contains("ssrf")
            || detector.contains("taint")
            || finding.cwe_id.is_some()
    }

    /// Check if a finding targets an API surface function (exported + high fan-in).
    /// Architecture penalties on API entry points are less actionable since high
    /// coupling is inherent to public APIs.
    fn is_api_surface_finding(&self, finding: &Finding) -> bool {
        let Some(file) = finding.affected_files.first() else {
            return false;
        };
        let Some(line) = finding.line_start else {
            return false;
        };
        is_api_surface(self.graph, &file.to_string_lossy(), line)
    }

    /// Check if a file path is a test file
    fn is_test_file(&self, path: &str) -> bool {
        let lower = path.to_lowercase();
        lower.contains("/test/")
            || lower.contains("/tests/")
            || lower.contains("/__tests__/")
            || lower.contains("/spec/")
            || lower.starts_with("test/")
            || lower.starts_with("tests/")
            || lower.ends_with("_test.go")
            || lower.ends_with("_test.py")
            || lower.ends_with("_test.rs")
            || lower.ends_with(".test.ts")
            || lower.ends_with(".test.js")
            || lower.ends_with(".spec.ts")
            || lower.ends_with(".spec.js")
    }

    /// Calculate letter grade
    fn calculate_grade(&self, score: f64, _findings: &[Finding]) -> Grade {
        // Grade is purely based on score - no caps
        // The score already reflects severity of findings
        // Capping based on criticals double-penalizes and punishes FPs in scripts/tests

        if score >= 97.0 {
            Grade::APlus
        } else if score >= 93.0 {
            Grade::A
        } else if score >= 90.0 {
            Grade::AMinus
        } else if score >= 87.0 {
            Grade::BPlus
        } else if score >= 83.0 {
            Grade::B
        } else if score >= 80.0 {
            Grade::BMinus
        } else if score >= 77.0 {
            Grade::CPlus
        } else if score >= 73.0 {
            Grade::C
        } else if score >= 70.0 {
            Grade::CMinus
        } else if score >= 67.0 {
            Grade::DPlus
        } else if score >= 63.0 {
            Grade::D
        } else if score >= 60.0 {
            Grade::DMinus
        } else {
            Grade::F
        }
    }

    /// Generate human-readable explanation of the score
    pub fn explain(&self, breakdown: &ScoreBreakdown) -> String {
        let mut lines = Vec::new();
        let m = &breakdown.graph_metrics;
        let kloc = m.total_loc as f64 / 1000.0;

        lines.push(format!(
            "# Health Score: {:.1} ({})\n",
            breakdown.overall_score, breakdown.grade
        ));

        lines.push("## Scoring Formula\n".to_string());
        let weights = &self.config.scoring.pillar_weights;
        lines.push("```".to_string());
        lines.push(format!(
            "Overall = Structure × {:.2} + Quality × {:.2} + Architecture × {:.2}",
            weights.structure, weights.quality, weights.architecture
        ));
        lines.push("Pillar  = (100 - penalties) + graph_bonuses".to_string());
        lines.push("Penalty = severity_weight per finding (flat, not density-based)".to_string());
        lines.push("```\n".to_string());
        lines.push("Severity weights: Critical=5.0, High=2.0, Medium=0.5, Low=0.1\n".to_string());

        // Graph metrics
        lines.push("## Graph Analysis\n".to_string());
        lines.push(format!(
            "- **Lines of code**: {} ({:.1} kLOC)",
            m.total_loc, kloc
        ));
        lines.push(format!("- **Modules**: {}", m.module_count));
        lines.push(format!(
            "- **Coupling**: {:.1}% cross-module calls (lower is better)",
            m.avg_coupling * 100.0
        ));
        lines.push(format!(
            "- **Cohesion**: {:.1}% intra-module calls (higher is better)",
            m.avg_cohesion * 100.0
        ));
        lines.push(format!(
            "- **Cycles**: {} circular dependencies",
            m.cycle_count
        ));
        lines.push(format!(
            "- **Simple functions**: {:.1}% have complexity ≤ 10",
            m.simple_function_ratio * 100.0
        ));
        lines.push(format!(
            "- **Test files**: {:.1}%\n",
            m.test_file_ratio * 100.0
        ));

        // Pillar breakdowns
        for pillar in [
            &breakdown.structure,
            &breakdown.quality,
            &breakdown.architecture,
        ] {
            format_pillar_breakdown(pillar, &mut lines);
        }

        lines.join("\n")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::ProjectType;
    use crate::graph::builder::GraphBuilder;
    use tempfile::TempDir;

    fn make_config(project_type: Option<ProjectType>) -> (TempDir, ProjectConfig) {
        let dir = TempDir::new().expect("create temp dir");
        let mut config = ProjectConfig::default();
        config.project_type = project_type;
        (dir, config)
    }

    #[test]
    fn test_empty_codebase() {
        let graph = GraphBuilder::new().freeze();
        let (dir, config) = make_config(None);
        let scorer = GraphScorer::new(&graph, &config, dir.path());

        let breakdown = scorer.calculate(&[]);

        // Empty codebase with no findings should score well
        assert!(breakdown.overall_score >= 90.0);
    }

    #[test]
    fn test_critical_finding_caps_grade() {
        let graph = GraphBuilder::new().freeze();
        let (dir, config) = make_config(None);
        let scorer = GraphScorer::new(&graph, &config, dir.path());

        let findings = vec![Finding {
            severity: Severity::Critical,
            detector: "test".to_string(),
            title: "Critical issue".to_string(),
            ..Default::default()
        }];

        let breakdown = scorer.calculate(&findings);

        // Grade is now purely score-based (no caps)
        // With minimal findings on an empty graph, score should be high = A range
        assert!(
            matches!(
                breakdown.grade,
                Grade::APlus
                    | Grade::A
                    | Grade::AMinus
                    | Grade::BPlus
                    | Grade::B
                    | Grade::BMinus
                    | Grade::CPlus
                    | Grade::C
                    | Grade::CMinus
            ),
            "Expected reasonable grade, got {}",
            breakdown.grade
        );
    }

    #[test]
    fn test_graph_bonuses() {
        let mut builder = GraphBuilder::new();

        // Add some test structure
        use crate::graph::CodeNode;
        builder.add_node(CodeNode::file("src/main.rs"));
        builder.add_node(CodeNode::file("src/lib.rs"));
        builder.add_node(CodeNode::file("tests/test_main.rs")); // Test file
        builder
            .add_node(CodeNode::function("main", "src/main.rs").with_property("complexity", 5i64));
        builder
            .add_node(CodeNode::function("helper", "src/lib.rs").with_property("complexity", 3i64));
        builder.add_node(
            CodeNode::function("test_main", "tests/test_main.rs").with_property("complexity", 2i64),
        );
        let graph = builder.freeze();

        let (dir, config) = make_config(None);
        let scorer = GraphScorer::new(&graph, &config, dir.path());

        let metrics = scorer.compute_graph_metrics();

        assert_eq!(metrics.total_files, 3);
        assert_eq!(metrics.total_functions, 3);
        // 1 out of 3 files is a test file
        assert!(
            (metrics.test_file_ratio - 0.333).abs() < 0.01,
            "test_file_ratio={}",
            metrics.test_file_ratio
        );
        assert_eq!(metrics.simple_function_ratio, 1.0); // All functions have complexity < 10
    }

    #[test]
    fn test_compiler_gets_lenient_modularity_bonus() {
        let graph = GraphBuilder::new().freeze();
        let (dir, compiler_config) = make_config(Some(ProjectType::Compiler));
        let compiler_scorer = GraphScorer::new(&graph, &compiler_config, dir.path());

        let (_, web_config) = make_config(Some(ProjectType::Web));
        let web_scorer = GraphScorer::new(&graph, &web_config, dir.path());

        // 60% cross-module coupling: bad for web, ok for compiler
        let metrics = GraphMetrics {
            avg_coupling: 0.6,
            avg_cohesion: 0.4,
            ..Default::default()
        };

        let compiler_bonus = compiler_scorer.calculate_modularity_bonus(&metrics);
        let web_bonus = web_scorer.calculate_modularity_bonus(&metrics);

        assert!(
            compiler_bonus > web_bonus,
            "Compiler bonus ({:.4}) should be > web bonus ({:.4}) at 60% coupling",
            compiler_bonus,
            web_bonus
        );
    }

    #[test]
    fn test_kernel_gets_lenient_complexity_bonus() {
        let graph = GraphBuilder::new().freeze();
        let (dir, kernel_config) = make_config(Some(ProjectType::Kernel));
        let kernel_scorer = GraphScorer::new(&graph, &kernel_config, dir.path());

        let (_, web_config) = make_config(Some(ProjectType::Web));
        let web_scorer = GraphScorer::new(&graph, &web_config, dir.path());

        // Only 55% simple functions: bad for web, ok for kernel
        let metrics = GraphMetrics {
            simple_function_ratio: 0.55,
            ..Default::default()
        };

        let kernel_bonus = kernel_scorer.calculate_complexity_bonus(&metrics);
        let web_bonus = web_scorer.calculate_complexity_bonus(&metrics);

        assert!(
            kernel_bonus > web_bonus,
            "Kernel bonus ({:.4}) should be > web bonus ({:.4}) at 55% simple",
            kernel_bonus,
            web_bonus
        );
    }

    #[test]
    fn test_web_default_thresholds_unchanged() {
        let graph = GraphBuilder::new().freeze();
        let (dir, config) = make_config(Some(ProjectType::Web));
        let scorer = GraphScorer::new(&graph, &config, dir.path());

        let metrics = GraphMetrics {
            avg_coupling: 0.5,
            avg_cohesion: 0.5,
            simple_function_ratio: 0.7,
            ..Default::default()
        };

        // Coupling 0.5 is between 0.3 (full) and 0.7 (none) — should get 50% bonus
        let mod_bonus = scorer.calculate_modularity_bonus(&metrics);
        assert!(
            (mod_bonus - 0.05).abs() < 0.001,
            "Expected ~0.05, got {}",
            mod_bonus
        );
    }

    #[test]
    fn test_baselined_findings_excluded_from_score() {
        let graph = GraphBuilder::new().freeze();
        let (dir, config) = make_config(None);
        let scorer = GraphScorer::new(&graph, &config, dir.path());

        // Score with no findings
        let baseline_score = scorer.calculate(&[]);

        // Score with a baselined finding — should be identical
        let findings = vec![Finding {
            severity: Severity::High,
            detector: "test".to_string(),
            title: "Accepted issue".to_string(),
            status: FindingStatus::Baselined,
            ..Default::default()
        }];
        let with_baselined = scorer.calculate(&findings);

        assert_eq!(
            baseline_score.overall_score, with_baselined.overall_score,
            "Baselined findings should not affect the score"
        );
    }
}