hotspots-core 1.21.1

Core library for static analysis and Local Risk Score (LRS) computation across TypeScript, JavaScript, Go, Python, Rust, Java, and C#
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
//! Configuration file support for Hotspots
//!
//! Loads project-specific configuration from JSON files.
//!
//! Search order:
//! 1. Explicit path (--config CLI flag)
//! 2. `.hotspotsrc.json` in project root
//! 3. `hotspots.config.json` in project root
//! 4. `"hotspots"` key in `package.json`
//!
//! All fields are optional. CLI flags take precedence over config file values.

use anyhow::{Context, Result};
use globset::{Glob, GlobSet, GlobSetBuilder};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// Default exclude patterns always applied (merged with any user-specified excludes).
const DEFAULT_EXCLUDES: &[&str] = &[
    // Test files
    "**/*.test.ts",
    "**/*.test.tsx",
    "**/*.test.js",
    "**/*.test.jsx",
    "**/*.spec.ts",
    "**/*.spec.tsx",
    "**/*.spec.js",
    "**/*.spec.jsx",
    "**/__tests__/**",
    "**/__mocks__/**",
    "**/__snapshots__/**",
    // Python test conventions
    "**/test_*.py",
    "**/*_test.py",
    // Go test and generated conventions
    "**/*_test.go",
    "**/vendor/**",
    "**/*.pb.go",
    "**/zz_generated*.go",
    "**/mock_*.go",
    // JS/TS build output and generated code
    "**/node_modules/**",
    "**/dist/**",
    "**/build/**",
    "**/.next/**",
    "**/.nuxt/**",
    "**/.output/**",
    "**/.cache/**",
    "**/.turbo/**",
    "**/storybook-static/**",
    "**/*.min.js",
    "**/*.min.ts",
    "**/*.bundle.js",
    "**/__generated__/**",
    "**/generated/**",
    "**/*.generated.ts",
    "**/*.generated.js",
    "**/*.pb.ts",
    "**/*.pb.js",
    // Python virtualenvs and cache
    "**/venv/**",
    "**/.venv/**",
    "**/__pycache__/**",
    // Django auto-generated migrations
    "**/migrations/**",
    // Java/Kotlin build output
    "**/target/**",
    "**/out/**",
];

/// Hotspots configuration loaded from a JSON config file
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HotspotsConfig {
    /// Glob patterns for files to include (default: all supported extensions)
    #[serde(default)]
    pub include: Vec<String>,

    /// Glob patterns for files to exclude (default: test files, node_modules, dist)
    #[serde(default)]
    pub exclude: Vec<String>,

    /// Custom risk band thresholds
    #[serde(default)]
    pub thresholds: Option<ThresholdConfig>,

    /// Custom metric weights for LRS calculation
    #[serde(default)]
    pub weights: Option<WeightConfig>,

    /// Warning thresholds for proactive alerts
    #[serde(default)]
    pub warning_thresholds: Option<WarningThresholdConfig>,

    /// Minimum LRS to report (default: 0.0, report all)
    #[serde(default)]
    pub min_lrs: Option<f64>,

    /// Maximum number of results to show
    #[serde(default)]
    pub top: Option<usize>,

    /// Activity risk scoring weights
    #[serde(default)]
    pub scoring: Option<ScoringWeightsConfig>,

    /// Number of days back to look for co-change pairs (default: 90)
    #[serde(default)]
    pub co_change_window_days: Option<u64>,

    /// Minimum number of co-changes required to report a pair (default: 3)
    #[serde(default)]
    pub co_change_min_count: Option<usize>,

    /// Use per-function git log -L for touch metrics (default: false).
    /// Warm runs use the on-disk cache and are as fast as file-level.
    /// Set to true for full precision; the default is hybrid touch mode (see hybrid_touch_threshold).
    #[serde(default)]
    pub per_function_touches: Option<bool>,

    /// Enable hybrid touch mode: file-level for all functions, then per-function
    /// only for functions in files with touch_count_30d >= this threshold.
    /// Overrides per_function_touches when set. Recommended: 3–10.
    #[serde(default)]
    pub hybrid_touch_threshold: Option<usize>,

    /// Percentile threshold for driving dimension detection (1–99, default: 75).
    /// A function must exceed this percentile in a metric to trigger that driver label.
    /// Lower values = more functions get specific labels; higher = only extreme outliers.
    #[serde(default)]
    pub driver_threshold_percentile: Option<u8>,

    /// Node count above which betweenness centrality switches from exact to approximate
    /// (default: 2000). Below this threshold the exact O(N²) Brandes algorithm runs;
    /// above it, k-source pivot sampling is used instead.
    #[serde(default)]
    pub betweenness_exact_threshold: Option<usize>,

    /// Number of pivot sources for approximate betweenness centrality (default: 256).
    /// Higher values improve accuracy at proportional cost. Only used when the graph
    /// exceeds `betweenness_exact_threshold`. Must be at least 1.
    #[serde(default)]
    pub betweenness_approx_k: Option<usize>,

    /// Skip all call graph computation when the repo has more than this many functions
    /// (default: no limit). Use this on very large repos where graph algorithms dominate
    /// CPU. When skipped, PageRank, betweenness, SCC, fan-in/fan-out, and dependency
    /// depth are all omitted from output.
    #[serde(default)]
    pub callgraph_skip_above: Option<usize>,

    /// Pattern detection thresholds. Overrides defaults from `docs/patterns.md`.
    #[serde(default)]
    pub patterns: Option<PatternThresholdsConfig>,
}

/// Custom risk band thresholds
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ThresholdConfig {
    /// LRS threshold for moderate risk (default: 3.0)
    pub moderate: Option<f64>,
    /// LRS threshold for high risk (default: 6.0)
    pub high: Option<f64>,
    /// LRS threshold for critical risk (default: 9.0)
    pub critical: Option<f64>,
}

/// Custom metric weights for LRS calculation
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WeightConfig {
    /// Weight for cyclomatic complexity (default: 1.0)
    pub cc: Option<f64>,
    /// Weight for nesting depth (default: 0.8)
    pub nd: Option<f64>,
    /// Weight for fan-out (default: 0.6)
    pub fo: Option<f64>,
    /// Weight for non-structured exits (default: 0.7)
    pub ns: Option<f64>,
}

/// Weights for activity-weighted risk scoring
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ScoringWeightsConfig {
    /// Weight for churn factor (default: 0.5)
    pub churn: Option<f64>,
    /// Weight for touch frequency factor (default: 0.3)
    pub touch: Option<f64>,
    /// Weight for recency factor (default: 0.2)
    pub recency: Option<f64>,
    /// Weight for fan-in factor (default: 0.4)
    pub fan_in: Option<f64>,
    /// Weight for SCC penalty (default: 0.3)
    pub scc: Option<f64>,
    /// Weight for dependency depth penalty (default: 0.1)
    pub depth: Option<f64>,
    /// Weight for neighbor churn factor (default: 0.2)
    pub neighbor_churn: Option<f64>,
}

/// Pattern detection thresholds — override defaults from `docs/patterns.md`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PatternThresholdsConfig {
    pub complex_branching_cc: Option<usize>,
    pub complex_branching_nd: Option<usize>,
    pub deeply_nested_nd: Option<usize>,
    pub exit_heavy_ns: Option<usize>,
    pub god_function_loc: Option<usize>,
    pub god_function_fo: Option<usize>,
    pub long_function_loc: Option<usize>,
    pub churn_magnet_churn: Option<usize>,
    pub churn_magnet_cc: Option<usize>,
    pub cyclic_hub_scc: Option<usize>,
    pub cyclic_hub_fan_in: Option<usize>,
    pub hub_function_fan_in: Option<usize>,
    pub hub_function_cc: Option<usize>,
    pub middle_man_fan_in: Option<usize>,
    pub middle_man_fo: Option<usize>,
    pub middle_man_cc_max: Option<usize>,
    pub neighbor_risk_churn: Option<usize>,
    pub neighbor_risk_fo: Option<usize>,
    pub shotgun_target_fan_in: Option<usize>,
    pub shotgun_target_churn: Option<usize>,
    pub stale_complex_cc: Option<usize>,
    pub stale_complex_loc: Option<usize>,
    pub stale_complex_days: Option<u32>,
}

/// Warning thresholds for proactive alerts
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WarningThresholdConfig {
    /// Watch threshold minimum - approaching moderate (default: 2.5)
    pub watch_min: Option<f64>,
    /// Watch threshold maximum - approaching moderate (default: 3.0)
    pub watch_max: Option<f64>,
    /// Attention threshold minimum - approaching high (default: 5.5)
    pub attention_min: Option<f64>,
    /// Attention threshold maximum - approaching high (default: 6.0)
    pub attention_max: Option<f64>,
    /// Rapid growth threshold - percent increase (default: 50.0)
    pub rapid_growth_percent: Option<f64>,
}

/// Resolved configuration with compiled glob patterns
#[derive(Debug)]
pub struct ResolvedConfig {
    /// Compiled include patterns (empty means include all)
    pub include: Option<GlobSet>,
    /// Compiled exclude patterns
    pub exclude: GlobSet,
    /// Risk band thresholds
    pub moderate_threshold: f64,
    pub high_threshold: f64,
    pub critical_threshold: f64,
    /// LRS weights
    pub weight_cc: f64,
    pub weight_nd: f64,
    pub weight_fo: f64,
    pub weight_ns: f64,
    /// Warning thresholds
    pub watch_min: f64,
    pub watch_max: f64,
    pub attention_min: f64,
    pub attention_max: f64,
    pub rapid_growth_percent: f64,
    /// Filters
    pub min_lrs: Option<f64>,
    pub top_n: Option<usize>,
    /// Co-change mining parameters
    pub co_change_window_days: u64,
    pub co_change_min_count: usize,
    /// Whether to use per-function git log -L for touch metrics
    pub per_function_touches: bool,
    /// Hybrid touch threshold: Some(n) = file-level first, per-function for files with ≥n touches
    pub hybrid_touch_threshold: Option<usize>,
    /// Percentile threshold for driving dimension detection (1–99)
    pub driver_threshold_percentile: u8,
    /// Node count above which betweenness switches to approximate algorithm
    pub betweenness_exact_threshold: usize,
    /// Number of pivot sources for approximate betweenness
    pub betweenness_approx_k: usize,
    /// Skip all call graph computation above this function count (usize::MAX = never skip)
    pub callgraph_skip_above: usize,
    /// Activity risk scoring weights
    pub scoring_weights: crate::scoring::ScoringWeights,
    /// Pattern detection thresholds
    pub pattern_thresholds: crate::patterns::Thresholds,
    /// Path the config was loaded from (None if defaults)
    pub config_path: Option<PathBuf>,
}

impl HotspotsConfig {
    /// Validate the configuration for logical errors
    pub fn validate(&self) -> Result<()> {
        if let Some(ref t) = self.thresholds {
            validate_thresholds(t)?;
        }
        if let Some(ref w) = self.weights {
            validate_weights(w)?;
        }
        if let Some(ref wt) = self.warning_thresholds {
            validate_warning_thresholds(wt)?;
        }
        if let Some(ref s) = self.scoring {
            validate_scoring(s)?;
        }
        if let Some(ref p) = self.patterns {
            validate_pattern_thresholds(p)?;
        }
        validate_scalar_fields(self)?;
        validate_glob_patterns(&self.include, &self.exclude)
    }
}

fn validate_scalar_fields(c: &HotspotsConfig) -> Result<()> {
    if let Some(min) = c.min_lrs {
        if min < 0.0 {
            anyhow::bail!("min_lrs must be non-negative (got {})", min);
        }
    }
    if let Some(w) = c.co_change_window_days {
        if w == 0 {
            anyhow::bail!("co_change_window_days must be at least 1");
        }
    }
    if let Some(m) = c.co_change_min_count {
        if m == 0 {
            anyhow::bail!("co_change_min_count must be at least 1");
        }
    }
    if let Some(p) = c.driver_threshold_percentile {
        if p == 0 || p >= 100 {
            anyhow::bail!(
                "driver_threshold_percentile must be between 1 and 99 (got {})",
                p
            );
        }
    }
    if let Some(k) = c.betweenness_approx_k {
        if k == 0 {
            anyhow::bail!("betweenness_approx_k must be at least 1");
        }
    }
    Ok(())
}

fn validate_glob_patterns(include: &[String], exclude: &[String]) -> Result<()> {
    for pattern in include {
        Glob::new(pattern).with_context(|| format!("invalid include pattern: {}", pattern))?;
    }
    for pattern in exclude {
        Glob::new(pattern).with_context(|| format!("invalid exclude pattern: {}", pattern))?;
    }
    Ok(())
}

fn validate_thresholds(t: &ThresholdConfig) -> Result<()> {
    let moderate = t.moderate.unwrap_or(3.0);
    let high = t.high.unwrap_or(6.0);
    let critical = t.critical.unwrap_or(9.0);
    if moderate <= 0.0 {
        anyhow::bail!("thresholds.moderate must be positive (got {})", moderate);
    }
    if high <= 0.0 {
        anyhow::bail!("thresholds.high must be positive (got {})", high);
    }
    if critical <= 0.0 {
        anyhow::bail!("thresholds.critical must be positive (got {})", critical);
    }
    if moderate >= high {
        anyhow::bail!(
            "thresholds.moderate ({}) must be less than thresholds.high ({})",
            moderate,
            high
        );
    }
    if high >= critical {
        anyhow::bail!(
            "thresholds.high ({}) must be less than thresholds.critical ({})",
            high,
            critical
        );
    }
    Ok(())
}

fn validate_weights(w: &WeightConfig) -> Result<()> {
    for (name, val) in [("cc", w.cc), ("nd", w.nd), ("fo", w.fo), ("ns", w.ns)] {
        if let Some(v) = val {
            if v < 0.0 {
                anyhow::bail!("weights.{} must be non-negative (got {})", name, v);
            }
            if v > 10.0 {
                anyhow::bail!("weights.{} must be at most 10.0 (got {})", name, v);
            }
        }
    }
    Ok(())
}

fn validate_warning_thresholds(wt: &WarningThresholdConfig) -> Result<()> {
    let watch_min = wt.watch_min.unwrap_or(2.5);
    let watch_max = wt.watch_max.unwrap_or(3.0);
    let attention_min = wt.attention_min.unwrap_or(5.5);
    let attention_max = wt.attention_max.unwrap_or(6.0);
    let rapid_growth = wt.rapid_growth_percent.unwrap_or(50.0);
    if watch_min <= 0.0 {
        anyhow::bail!(
            "warning_thresholds.watch_min must be positive (got {})",
            watch_min
        );
    }
    if watch_max <= 0.0 {
        anyhow::bail!(
            "warning_thresholds.watch_max must be positive (got {})",
            watch_max
        );
    }
    if attention_min <= 0.0 {
        anyhow::bail!(
            "warning_thresholds.attention_min must be positive (got {})",
            attention_min
        );
    }
    if attention_max <= 0.0 {
        anyhow::bail!(
            "warning_thresholds.attention_max must be positive (got {})",
            attention_max
        );
    }
    if rapid_growth <= 0.0 {
        anyhow::bail!(
            "warning_thresholds.rapid_growth_percent must be positive (got {})",
            rapid_growth
        );
    }
    if watch_min >= watch_max {
        anyhow::bail!(
            "warning_thresholds.watch_min ({}) must be less than watch_max ({})",
            watch_min,
            watch_max
        );
    }
    if attention_min >= attention_max {
        anyhow::bail!(
            "warning_thresholds.attention_min ({}) must be less than attention_max ({})",
            attention_min,
            attention_max
        );
    }
    Ok(())
}

fn validate_scoring(s: &ScoringWeightsConfig) -> Result<()> {
    for (name, val) in [
        ("churn", s.churn),
        ("touch", s.touch),
        ("recency", s.recency),
        ("fan_in", s.fan_in),
        ("scc", s.scc),
        ("depth", s.depth),
        ("neighbor_churn", s.neighbor_churn),
    ] {
        if let Some(v) = val {
            if v < 0.0 {
                anyhow::bail!("scoring.{} must be non-negative (got {})", name, v);
            }
            if v > 10.0 {
                anyhow::bail!("scoring.{} must be at most 10.0 (got {})", name, v);
            }
        }
    }
    Ok(())
}

fn validate_pattern_thresholds(p: &PatternThresholdsConfig) -> Result<()> {
    // All thresholds must be at least 1 when specified
    let usize_fields: &[(&str, Option<usize>)] = &[
        ("complex_branching_cc", p.complex_branching_cc),
        ("complex_branching_nd", p.complex_branching_nd),
        ("deeply_nested_nd", p.deeply_nested_nd),
        ("exit_heavy_ns", p.exit_heavy_ns),
        ("god_function_loc", p.god_function_loc),
        ("god_function_fo", p.god_function_fo),
        ("long_function_loc", p.long_function_loc),
        ("churn_magnet_churn", p.churn_magnet_churn),
        ("churn_magnet_cc", p.churn_magnet_cc),
        ("cyclic_hub_scc", p.cyclic_hub_scc),
        ("cyclic_hub_fan_in", p.cyclic_hub_fan_in),
        ("hub_function_fan_in", p.hub_function_fan_in),
        ("hub_function_cc", p.hub_function_cc),
        ("middle_man_fan_in", p.middle_man_fan_in),
        ("middle_man_fo", p.middle_man_fo),
        ("middle_man_cc_max", p.middle_man_cc_max),
        ("neighbor_risk_churn", p.neighbor_risk_churn),
        ("neighbor_risk_fo", p.neighbor_risk_fo),
        ("shotgun_target_fan_in", p.shotgun_target_fan_in),
        ("shotgun_target_churn", p.shotgun_target_churn),
        ("stale_complex_cc", p.stale_complex_cc),
        ("stale_complex_loc", p.stale_complex_loc),
    ];
    for (name, val) in usize_fields {
        if let Some(v) = val {
            if *v == 0 {
                anyhow::bail!("patterns.{} must be at least 1 (got 0)", name);
            }
        }
    }
    if let Some(v) = p.stale_complex_days {
        if v == 0 {
            anyhow::bail!("patterns.stale_complex_days must be at least 1 (got 0)");
        }
    }
    Ok(())
}

impl HotspotsConfig {
    /// Resolve config into compiled form ready for use
    pub fn resolve(&self) -> Result<ResolvedConfig> {
        self.validate()?;

        // Compile include patterns
        let include = if self.include.is_empty() {
            None
        } else {
            let mut builder = GlobSetBuilder::new();
            for pattern in &self.include {
                builder.add(Glob::new(pattern)?);
            }
            Some(builder.build()?)
        };

        // Compile exclude patterns: defaults always apply; user patterns are additive.
        let exclude = {
            let mut builder = GlobSetBuilder::new();
            for pattern in DEFAULT_EXCLUDES {
                builder.add(Glob::new(pattern)?);
            }
            for pattern in &self.exclude {
                builder.add(Glob::new(pattern)?);
            }
            builder.build()?
        };

        let (moderate, high, critical) = match &self.thresholds {
            Some(t) => (
                t.moderate.unwrap_or(3.0),
                t.high.unwrap_or(6.0),
                t.critical.unwrap_or(9.0),
            ),
            None => (3.0, 6.0, 9.0),
        };

        let (w_cc, w_nd, w_fo, w_ns) = match &self.weights {
            Some(w) => (
                w.cc.unwrap_or(1.0),
                w.nd.unwrap_or(0.8),
                w.fo.unwrap_or(0.6),
                w.ns.unwrap_or(0.7),
            ),
            None => (1.0, 0.8, 0.6, 0.7),
        };

        let (watch_min, watch_max, attention_min, attention_max, rapid_growth_percent) =
            match &self.warning_thresholds {
                Some(wt) => (
                    wt.watch_min.unwrap_or(2.5),
                    wt.watch_max.unwrap_or(3.0),
                    wt.attention_min.unwrap_or(5.5),
                    wt.attention_max.unwrap_or(6.0),
                    wt.rapid_growth_percent.unwrap_or(50.0),
                ),
                None => (2.5, 3.0, 5.5, 6.0, 50.0),
            };

        let scoring_weights = match &self.scoring {
            Some(s) => {
                let defaults = crate::scoring::ScoringWeights::default();
                crate::scoring::ScoringWeights {
                    churn: s.churn.unwrap_or(defaults.churn),
                    touch: s.touch.unwrap_or(defaults.touch),
                    recency: s.recency.unwrap_or(defaults.recency),
                    fan_in: s.fan_in.unwrap_or(defaults.fan_in),
                    scc: s.scc.unwrap_or(defaults.scc),
                    depth: s.depth.unwrap_or(defaults.depth),
                    neighbor_churn: s.neighbor_churn.unwrap_or(defaults.neighbor_churn),
                }
            }
            None => crate::scoring::ScoringWeights::default(),
        };

        let pattern_thresholds = match &self.patterns {
            Some(p) => {
                let d = crate::patterns::Thresholds::default();
                crate::patterns::Thresholds {
                    complex_branching_cc: p.complex_branching_cc.unwrap_or(d.complex_branching_cc),
                    complex_branching_nd: p.complex_branching_nd.unwrap_or(d.complex_branching_nd),
                    deeply_nested_nd: p.deeply_nested_nd.unwrap_or(d.deeply_nested_nd),
                    exit_heavy_ns: p.exit_heavy_ns.unwrap_or(d.exit_heavy_ns),
                    god_function_loc: p.god_function_loc.unwrap_or(d.god_function_loc),
                    god_function_fo: p.god_function_fo.unwrap_or(d.god_function_fo),
                    long_function_loc: p.long_function_loc.unwrap_or(d.long_function_loc),
                    churn_magnet_churn: p.churn_magnet_churn.unwrap_or(d.churn_magnet_churn),
                    churn_magnet_cc: p.churn_magnet_cc.unwrap_or(d.churn_magnet_cc),
                    cyclic_hub_scc: p.cyclic_hub_scc.unwrap_or(d.cyclic_hub_scc),
                    cyclic_hub_fan_in: p.cyclic_hub_fan_in.unwrap_or(d.cyclic_hub_fan_in),
                    hub_function_fan_in: p.hub_function_fan_in.unwrap_or(d.hub_function_fan_in),
                    hub_function_cc: p.hub_function_cc.unwrap_or(d.hub_function_cc),
                    middle_man_fan_in: p.middle_man_fan_in.unwrap_or(d.middle_man_fan_in),
                    middle_man_fo: p.middle_man_fo.unwrap_or(d.middle_man_fo),
                    middle_man_cc_max: p.middle_man_cc_max.unwrap_or(d.middle_man_cc_max),
                    neighbor_risk_churn: p.neighbor_risk_churn.unwrap_or(d.neighbor_risk_churn),
                    neighbor_risk_fo: p.neighbor_risk_fo.unwrap_or(d.neighbor_risk_fo),
                    shotgun_target_fan_in: p
                        .shotgun_target_fan_in
                        .unwrap_or(d.shotgun_target_fan_in),
                    shotgun_target_churn: p.shotgun_target_churn.unwrap_or(d.shotgun_target_churn),
                    stale_complex_cc: p.stale_complex_cc.unwrap_or(d.stale_complex_cc),
                    stale_complex_loc: p.stale_complex_loc.unwrap_or(d.stale_complex_loc),
                    stale_complex_days: p.stale_complex_days.unwrap_or(d.stale_complex_days),
                }
            }
            None => crate::patterns::Thresholds::default(),
        };

        Ok(ResolvedConfig {
            include,
            exclude,
            moderate_threshold: moderate,
            high_threshold: high,
            critical_threshold: critical,
            weight_cc: w_cc,
            weight_nd: w_nd,
            weight_fo: w_fo,
            weight_ns: w_ns,
            watch_min,
            watch_max,
            attention_min,
            attention_max,
            rapid_growth_percent,
            min_lrs: self.min_lrs,
            top_n: self.top,
            scoring_weights,
            pattern_thresholds,
            co_change_window_days: self.co_change_window_days.unwrap_or(90),
            co_change_min_count: self.co_change_min_count.unwrap_or(3),
            per_function_touches: self.per_function_touches.unwrap_or(false),
            hybrid_touch_threshold: self.hybrid_touch_threshold,
            driver_threshold_percentile: self.driver_threshold_percentile.unwrap_or(75),
            betweenness_exact_threshold: self.betweenness_exact_threshold.unwrap_or(2000),
            betweenness_approx_k: self.betweenness_approx_k.unwrap_or(256),
            callgraph_skip_above: self.callgraph_skip_above.unwrap_or(usize::MAX),
            config_path: None,
        })
    }
}

impl ResolvedConfig {
    /// Check if a file path should be included based on include/exclude patterns
    pub fn should_include(&self, path: &Path) -> bool {
        let path_str = path.to_string_lossy();

        // Check exclude first
        if self.exclude.is_match(path_str.as_ref()) {
            return false;
        }

        // If include patterns exist, file must match at least one
        if let Some(ref include) = self.include {
            return include.is_match(path_str.as_ref());
        }

        true
    }

    /// Build a ResolvedConfig with all defaults (no config file)
    pub fn defaults() -> Result<Self> {
        HotspotsConfig::default().resolve()
    }
}

/// Discover and load a config file from the project root
///
/// Search order:
/// 1. `.hotspotsrc.json`
/// 2. `hotspots.config.json`
/// 3. `"hotspots"` key in `package.json`
///
/// Returns `None` if no config file is found (use defaults).
pub fn discover_config(project_root: &Path) -> Result<Option<(HotspotsConfig, PathBuf)>> {
    // 1. .hotspotsrc.json
    let rc_path = project_root.join(".hotspotsrc.json");
    if rc_path.exists() {
        let config = load_config_file(&rc_path)?;
        return Ok(Some((config, rc_path)));
    }

    // 2. hotspots.config.json
    let config_path = project_root.join("hotspots.config.json");
    if config_path.exists() {
        let config = load_config_file(&config_path)?;
        return Ok(Some((config, config_path)));
    }

    // 3. package.json "hotspots" key
    let pkg_path = project_root.join("package.json");
    if pkg_path.exists() {
        if let Some(config) = load_from_package_json(&pkg_path)? {
            return Ok(Some((config, pkg_path)));
        }
    }

    Ok(None)
}

/// Load config from an explicit file path
pub fn load_config_file(path: &Path) -> Result<HotspotsConfig> {
    let content = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read config file: {}", path.display()))?;

    let config: HotspotsConfig = serde_json::from_str(&content)
        .with_context(|| format!("failed to parse config file: {}", path.display()))?;

    config
        .validate()
        .with_context(|| format!("invalid config in: {}", path.display()))?;

    Ok(config)
}

/// Load hotspots config from the "hotspots" key in package.json
fn load_from_package_json(path: &Path) -> Result<Option<HotspotsConfig>> {
    let content = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;

    let pkg: serde_json::Value = serde_json::from_str(&content)
        .with_context(|| format!("failed to parse {}", path.display()))?;

    match pkg.get("hotspots") {
        Some(hotspots_value) => {
            let config: HotspotsConfig = serde_json::from_value(hotspots_value.clone())
                .with_context(|| format!("invalid hotspots config in {}", path.display()))?;
            config
                .validate()
                .with_context(|| format!("invalid hotspots config in {}", path.display()))?;
            Ok(Some(config))
        }
        None => Ok(None),
    }
}

/// Load and resolve config for a project
///
/// If `config_path` is provided, loads from that file.
/// Otherwise, discovers config from the project root.
/// Returns default config if nothing is found.
pub fn load_and_resolve(project_root: &Path, config_path: Option<&Path>) -> Result<ResolvedConfig> {
    let (config, source_path) = if let Some(path) = config_path {
        let config = load_config_file(path)?;
        (config, Some(path.to_path_buf()))
    } else {
        match discover_config(project_root)? {
            Some((config, path)) => (config, Some(path)),
            None => (HotspotsConfig::default(), None),
        }
    };

    let mut resolved = config.resolve()?;
    resolved.config_path = source_path;
    Ok(resolved)
}

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

    #[test]
    fn test_default_config_is_valid() {
        let config = HotspotsConfig::default();
        config.validate().expect("default config should be valid");
        let resolved = config.resolve().expect("default config should resolve");
        assert!(resolved.include.is_none());
        assert_eq!(resolved.weight_cc, 1.0);
        assert_eq!(resolved.weight_nd, 0.8);
        assert_eq!(resolved.weight_fo, 0.6);
        assert_eq!(resolved.weight_ns, 0.7);
        assert_eq!(resolved.moderate_threshold, 3.0);
        assert_eq!(resolved.high_threshold, 6.0);
        assert_eq!(resolved.critical_threshold, 9.0);
    }

    #[test]
    fn test_parse_minimal_config() {
        let json = r#"{}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        config.validate().unwrap();
    }

    #[test]
    fn test_parse_full_config() {
        let json = r#"{
            "include": ["src/**/*.ts", "src/**/*.tsx"],
            "exclude": ["**/*.test.ts", "**/node_modules/**"],
            "thresholds": {
                "moderate": 4.0,
                "high": 7.0,
                "critical": 10.0
            },
            "weights": {
                "cc": 1.2,
                "nd": 0.9,
                "fo": 0.5,
                "ns": 0.8
            },
            "min_lrs": 2.0,
            "top": 20
        }"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        config.validate().unwrap();
        let resolved = config.resolve().unwrap();
        assert!(resolved.include.is_some());
        assert_eq!(resolved.moderate_threshold, 4.0);
        assert_eq!(resolved.high_threshold, 7.0);
        assert_eq!(resolved.critical_threshold, 10.0);
        assert_eq!(resolved.weight_cc, 1.2);
        assert_eq!(resolved.min_lrs, Some(2.0));
        assert_eq!(resolved.top_n, Some(20));
    }

    #[test]
    fn test_reject_unknown_fields() {
        let json = r#"{"unknown_field": true}"#;
        let result: Result<HotspotsConfig, _> = serde_json::from_str(json);
        assert!(result.is_err(), "unknown fields should be rejected");
    }

    #[test]
    fn test_reject_negative_weight() {
        let json = r#"{"weights": {"cc": -1.0}}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_reject_weight_over_10() {
        let json = r#"{"weights": {"cc": 11.0}}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_reject_negative_threshold() {
        let json = r#"{"thresholds": {"moderate": -1.0}}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_reject_unordered_thresholds() {
        let json = r#"{"thresholds": {"moderate": 6.0, "high": 3.0, "critical": 9.0}}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_reject_invalid_glob_pattern() {
        let json = r#"{"include": ["[invalid"]}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_should_include_default_excludes() {
        let resolved = ResolvedConfig::defaults().unwrap();
        assert!(!resolved.should_include(Path::new("src/foo.test.ts")));
        assert!(!resolved.should_include(Path::new("node_modules/pkg/index.js")));
        assert!(!resolved.should_include(Path::new("dist/bundle.js")));
        assert!(resolved.should_include(Path::new("src/api.ts")));
        assert!(resolved.should_include(Path::new("src/components/Button.tsx")));
    }

    #[test]
    fn test_should_include_custom_patterns() {
        let config: HotspotsConfig = serde_json::from_str(
            r#"{
            "include": ["src/**/*.ts"],
            "exclude": ["src/generated/**"]
        }"#,
        )
        .unwrap();
        let resolved = config.resolve().unwrap();
        assert!(resolved.should_include(Path::new("src/api.ts")));
        assert!(!resolved.should_include(Path::new("lib/util.ts")));
        assert!(!resolved.should_include(Path::new("src/generated/types.ts")));
    }

    #[test]
    fn test_discover_hotspotsrc() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join(".hotspotsrc.json");
        fs::write(&config_path, r#"{"min_lrs": 5.0}"#).unwrap();

        let result = discover_config(dir.path()).unwrap();
        assert!(result.is_some());
        let (config, path) = result.unwrap();
        assert_eq!(config.min_lrs, Some(5.0));
        assert_eq!(path, config_path);
    }

    #[test]
    fn test_discover_hotspots_config_json() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("hotspots.config.json");
        fs::write(&config_path, r#"{"top": 10}"#).unwrap();

        let result = discover_config(dir.path()).unwrap();
        assert!(result.is_some());
        let (config, _) = result.unwrap();
        assert_eq!(config.top, Some(10));
    }

    #[test]
    fn test_discover_package_json() {
        let dir = tempfile::tempdir().unwrap();
        let pkg_path = dir.path().join("package.json");
        fs::write(
            &pkg_path,
            r#"{
            "name": "my-project",
            "version": "1.0.0",
            "hotspots": {
                "exclude": ["**/*.test.ts"],
                "min_lrs": 3.0
            }
        }"#,
        )
        .unwrap();

        let result = discover_config(dir.path()).unwrap();
        assert!(result.is_some());
        let (config, _) = result.unwrap();
        assert_eq!(config.min_lrs, Some(3.0));
        assert_eq!(config.exclude, vec!["**/*.test.ts"]);
    }

    #[test]
    fn test_discover_package_json_without_hotspots_key() {
        let dir = tempfile::tempdir().unwrap();
        let pkg_path = dir.path().join("package.json");
        fs::write(&pkg_path, r#"{"name": "my-project", "version": "1.0.0"}"#).unwrap();

        let result = discover_config(dir.path()).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_discover_priority_order() {
        let dir = tempfile::tempdir().unwrap();

        // Create both config files - .hotspotsrc.json should win
        fs::write(dir.path().join(".hotspotsrc.json"), r#"{"min_lrs": 1.0}"#).unwrap();
        fs::write(
            dir.path().join("hotspots.config.json"),
            r#"{"min_lrs": 2.0}"#,
        )
        .unwrap();

        let result = discover_config(dir.path()).unwrap();
        let (config, _) = result.unwrap();
        assert_eq!(
            config.min_lrs,
            Some(1.0),
            ".hotspotsrc.json should take priority"
        );
    }

    #[test]
    fn test_no_config_returns_none() {
        let dir = tempfile::tempdir().unwrap();
        let result = discover_config(dir.path()).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_load_and_resolve_defaults() {
        let dir = tempfile::tempdir().unwrap();
        let resolved = load_and_resolve(dir.path(), None).unwrap();
        assert!(resolved.config_path.is_none());
        assert_eq!(resolved.weight_cc, 1.0);
    }

    #[test]
    fn test_load_and_resolve_explicit_path() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("custom.json");
        fs::write(&config_path, r#"{"weights": {"cc": 2.0}}"#).unwrap();

        let resolved = load_and_resolve(dir.path(), Some(&config_path)).unwrap();
        assert_eq!(resolved.weight_cc, 2.0);
        assert_eq!(resolved.config_path, Some(config_path));
    }

    #[test]
    fn test_partial_weights_use_defaults_for_rest() {
        let json = r#"{"weights": {"cc": 2.0}}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        let resolved = config.resolve().unwrap();
        assert_eq!(resolved.weight_cc, 2.0);
        assert_eq!(resolved.weight_nd, 0.8); // default
        assert_eq!(resolved.weight_fo, 0.6); // default
        assert_eq!(resolved.weight_ns, 0.7); // default
    }

    #[test]
    fn test_partial_thresholds_use_defaults_for_rest() {
        let json = r#"{"thresholds": {"critical": 12.0}}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        let resolved = config.resolve().unwrap();
        assert_eq!(resolved.moderate_threshold, 3.0); // default
        assert_eq!(resolved.high_threshold, 6.0); // default
        assert_eq!(resolved.critical_threshold, 12.0);
    }

    #[test]
    fn test_default_warning_thresholds() {
        let config = HotspotsConfig::default();
        let resolved = config.resolve().unwrap();
        assert_eq!(resolved.watch_min, 2.5);
        assert_eq!(resolved.watch_max, 3.0);
        assert_eq!(resolved.attention_min, 5.5);
        assert_eq!(resolved.attention_max, 6.0);
        assert_eq!(resolved.rapid_growth_percent, 50.0);
    }

    #[test]
    fn test_parse_warning_thresholds() {
        let json = r#"{
            "warning_thresholds": {
                "watch_min": 2.0,
                "watch_max": 3.5,
                "attention_min": 5.0,
                "attention_max": 7.0,
                "rapid_growth_percent": 75.0
            }
        }"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        config.validate().unwrap();
        let resolved = config.resolve().unwrap();
        assert_eq!(resolved.watch_min, 2.0);
        assert_eq!(resolved.watch_max, 3.5);
        assert_eq!(resolved.attention_min, 5.0);
        assert_eq!(resolved.attention_max, 7.0);
        assert_eq!(resolved.rapid_growth_percent, 75.0);
    }

    #[test]
    fn test_partial_warning_thresholds_use_defaults() {
        let json = r#"{"warning_thresholds": {"rapid_growth_percent": 100.0}}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        let resolved = config.resolve().unwrap();
        assert_eq!(resolved.watch_min, 2.5); // default
        assert_eq!(resolved.watch_max, 3.0); // default
        assert_eq!(resolved.attention_min, 5.5); // default
        assert_eq!(resolved.attention_max, 6.0); // default
        assert_eq!(resolved.rapid_growth_percent, 100.0);
    }

    #[test]
    fn test_reject_negative_watch_min() {
        let json = r#"{"warning_thresholds": {"watch_min": -1.0}}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_reject_negative_rapid_growth() {
        let json = r#"{"warning_thresholds": {"rapid_growth_percent": -10.0}}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_reject_unordered_watch_thresholds() {
        let json = r#"{"warning_thresholds": {"watch_min": 3.0, "watch_max": 2.0}}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_reject_unordered_attention_thresholds() {
        let json = r#"{"warning_thresholds": {"attention_min": 7.0, "attention_max": 5.0}}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_full_config_with_warnings() {
        let json = r#"{
            "thresholds": {
                "moderate": 3.0,
                "high": 6.0,
                "critical": 9.0
            },
            "warning_thresholds": {
                "watch_min": 2.5,
                "watch_max": 3.0,
                "attention_min": 5.5,
                "attention_max": 6.0,
                "rapid_growth_percent": 50.0
            }
        }"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        config.validate().unwrap();
        let resolved = config.resolve().unwrap();
        assert_eq!(resolved.watch_min, 2.5);
        assert_eq!(resolved.watch_max, 3.0);
        assert_eq!(resolved.attention_min, 5.5);
        assert_eq!(resolved.attention_max, 6.0);
        assert_eq!(resolved.rapid_growth_percent, 50.0);
    }

    #[test]
    fn test_scoring_weights_defaults() {
        let config = HotspotsConfig::default();
        let resolved = config.resolve().unwrap();
        let defaults = crate::scoring::ScoringWeights::default();
        assert_eq!(resolved.scoring_weights.churn, defaults.churn);
        assert_eq!(resolved.scoring_weights.touch, defaults.touch);
        assert_eq!(resolved.scoring_weights.recency, defaults.recency);
        assert_eq!(resolved.scoring_weights.fan_in, defaults.fan_in);
        assert_eq!(resolved.scoring_weights.scc, defaults.scc);
        assert_eq!(resolved.scoring_weights.depth, defaults.depth);
        assert_eq!(
            resolved.scoring_weights.neighbor_churn,
            defaults.neighbor_churn
        );
    }

    #[test]
    fn test_scoring_weights_from_config() {
        let json = r#"{
            "scoring": {
                "churn": 0.8,
                "touch": 0.5,
                "fan_in": 0.6
            }
        }"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        config.validate().unwrap();
        let resolved = config.resolve().unwrap();
        assert_eq!(resolved.scoring_weights.churn, 0.8);
        assert_eq!(resolved.scoring_weights.touch, 0.5);
        assert_eq!(resolved.scoring_weights.fan_in, 0.6);
        // Unspecified fields fall back to defaults
        let defaults = crate::scoring::ScoringWeights::default();
        assert_eq!(resolved.scoring_weights.recency, defaults.recency);
        assert_eq!(resolved.scoring_weights.scc, defaults.scc);
    }

    #[test]
    fn test_reject_negative_scoring_weight() {
        let json = r#"{"scoring": {"churn": -0.1}}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_reject_scoring_weight_over_10() {
        let json = r#"{"scoring": {"fan_in": 11.0}}"#;
        let config: HotspotsConfig = serde_json::from_str(json).unwrap();
        assert!(config.validate().is_err());
    }
}