hotspots-core 1.42.1

Core library for finding the riskiest code by combining complexity with git change history (Local Risk Score) across TypeScript, JavaScript, Go, Python, Rust, Java, C#, and C
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
//! Trend semantics - extract high-signal trends from snapshot history
//!
//! Analyzes historical snapshots to identify:
//! - Risk velocity (rate of LRS change)
//! - Hotspot stability (consistency of high-risk functions)
//! - Refactor effectiveness (sustained improvements)
//!
//! Global invariants enforced:
//! - Deterministic ordering (by commit timestamp, then SHA)
//! - No snapshot mutation
//! - Trends are derived, not stored

use crate::snapshot::{Index, Snapshot};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

/// Flat velocity tolerance (epsilon)
const FLAT_VELOCITY_EPSILON: f64 = 1e-9;

/// Significant improvement threshold for refactor detection
const REFACTOR_IMPROVEMENT_THRESHOLD: f64 = -1.0;

/// Rebound threshold after improvement
const REFACTOR_REBOUND_THRESHOLD: f64 = 0.5;

/// Velocity direction
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum VelocityDirection {
    Positive,
    Negative,
    Flat,
}

/// Risk velocity for a function
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct RiskVelocity {
    pub function_id: String,
    pub velocity: f64,
    pub direction: VelocityDirection,
    pub first_lrs: f64,
    pub last_lrs: f64,
    pub commit_count: usize,
}

/// Hotspot stability classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HotspotStability {
    Stable,
    Emerging,
    Volatile,
}

/// Hotspot analysis for a function
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct HotspotAnalysis {
    pub function_id: String,
    pub stability: HotspotStability,
    pub overlap_ratio: f64,
    pub appearances_in_top_k: usize,
    pub total_snapshots: usize,
}

/// Refactor effectiveness classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RefactorOutcome {
    Successful,
    Partial,
    Cosmetic,
}

/// Refactor effectiveness analysis
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct RefactorAnalysis {
    pub function_id: String,
    pub outcome: RefactorOutcome,
    pub improvement_delta: f64,
    pub sustained_commits: usize,
    pub rebound_detected: bool,
}

/// Complete trends analysis
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct TrendsAnalysis {
    pub velocities: Vec<RiskVelocity>,
    pub hotspots: Vec<HotspotAnalysis>,
    pub refactors: Vec<RefactorAnalysis>,
}

impl TrendsAnalysis {
    /// Serialize to JSON string
    pub fn to_json(&self) -> Result<String> {
        serde_json::to_string_pretty(self).context("failed to serialize trends analysis to JSON")
    }
}

/// Load snapshots from history using a sliding window
///
/// # Arguments
///
/// * `repo_root` - Repository root path
/// * `window_size` - Maximum number of snapshots to include (default: 10)
///
/// # Returns
///
/// Vector of snapshots ordered by commit timestamp (ascending), then SHA
pub fn load_snapshot_window(repo_root: &Path, window_size: usize) -> Result<Vec<Snapshot>> {
    // Load index
    let index_path = crate::snapshot::index_path(repo_root);
    let index = Index::load_or_new(&index_path).context("failed to load index")?;

    if index.commits.is_empty() {
        return Ok(Vec::new());
    }

    // Get last N commits (index is already sorted by timestamp, then SHA)
    let commits_to_load = if index.commits.len() <= window_size {
        &index.commits[..]
    } else {
        &index.commits[index.commits.len() - window_size..]
    };

    // Load snapshots
    let mut snapshots = Vec::new();
    for entry in commits_to_load {
        if let Some(snapshot) = crate::snapshot::load_snapshot(repo_root, &entry.sha)? {
            snapshots.push(snapshot);
        }
    }

    // Ensure deterministic ordering (by timestamp, then SHA)
    snapshots.sort_by(|a, b| {
        a.commit
            .timestamp
            .cmp(&b.commit.timestamp)
            .then_with(|| a.commit.sha.cmp(&b.commit.sha))
    });

    Ok(snapshots)
}

/// Compute risk velocity for all functions in a window
///
/// Formula: `(LRS_last - LRS_first) / (commit_count - 1)`
/// Requires at least 2 data points.
pub fn compute_risk_velocities(snapshots: &[Snapshot]) -> Vec<RiskVelocity> {
    if snapshots.len() < 2 {
        return Vec::new();
    }

    // Collect function LRS values across snapshots
    let mut function_lrs: HashMap<String, Vec<(usize, f64)>> = HashMap::new();

    for (snapshot_idx, snapshot) in snapshots.iter().enumerate() {
        for func in &snapshot.functions {
            function_lrs
                .entry(func.function_id.clone())
                .or_default()
                .push((snapshot_idx, func.lrs));
        }
    }

    let mut velocities = Vec::new();

    for (function_id, lrs_points) in function_lrs {
        // Require at least 2 data points
        if lrs_points.len() < 2 {
            continue;
        }

        // Skip baseline-only functions (only appear in first snapshot)
        if lrs_points.len() == 1 && lrs_points[0].0 == 0 {
            continue;
        }

        // Sort by snapshot index
        let mut sorted_points = lrs_points;
        sorted_points.sort_by_key(|(idx, _)| *idx);

        let (first_lrs, last_lrs) = match (sorted_points.first(), sorted_points.last()) {
            (Some(first), Some(last)) => (first.1, last.1),
            _ => continue,
        };
        let commit_count = sorted_points.len();

        // Compute velocity: (LRS_last - LRS_first) / (commit_count - 1)
        let velocity = if commit_count > 1 {
            (last_lrs - first_lrs) / (commit_count - 1) as f64
        } else {
            0.0
        };

        // Determine direction
        let direction = if velocity.abs() < FLAT_VELOCITY_EPSILON {
            VelocityDirection::Flat
        } else if velocity > 0.0 {
            VelocityDirection::Positive
        } else {
            VelocityDirection::Negative
        };

        velocities.push(RiskVelocity {
            function_id,
            velocity,
            direction,
            first_lrs,
            last_lrs,
            commit_count,
        });
    }

    // Sort deterministically by function_id
    velocities.sort_by(|a, b| a.function_id.cmp(&b.function_id));

    velocities
}

/// Identify top K functions by LRS in a snapshot
fn top_k_functions(snapshot: &Snapshot, k: usize) -> Vec<String> {
    let mut functions: Vec<(&crate::snapshot::FunctionSnapshot, f64)> =
        snapshot.functions.iter().map(|f| (f, f.lrs)).collect();

    // Sort by LRS descending
    functions.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

    // Take top K
    functions
        .into_iter()
        .take(k)
        .map(|(f, _)| f.function_id.clone())
        .collect()
}

/// Compute hotspot stability for functions
///
/// Identifies top K functions per snapshot and computes overlap ratio.
pub fn compute_hotspot_stability(snapshots: &[Snapshot], top_k: usize) -> Vec<HotspotAnalysis> {
    // A single snapshot trivially satisfies the "stable" formula (100%
    // overlap with itself) but that's misleading — stability implies
    // consistency across history that doesn't exist yet with one data
    // point. Mirror `compute_risk_velocities`'s n<2 guard. See #229.
    if snapshots.len() < 2 {
        return Vec::new();
    }

    // Collect top K functions per snapshot
    let mut top_k_per_snapshot: Vec<Vec<String>> = Vec::new();
    for snapshot in snapshots {
        top_k_per_snapshot.push(top_k_functions(snapshot, top_k));
    }

    // Collect all unique function IDs that appear in top K
    let mut all_top_k_functions: std::collections::HashSet<String> =
        std::collections::HashSet::new();
    for top_k_list in &top_k_per_snapshot {
        for function_id in top_k_list {
            all_top_k_functions.insert(function_id.clone());
        }
    }

    let mut hotspot_analyses = Vec::new();

    for function_id in all_top_k_functions {
        // Count appearances in top K
        let appearances = top_k_per_snapshot
            .iter()
            .filter(|top_k_list| top_k_list.contains(&function_id))
            .count();

        let total_snapshots = snapshots.len();
        let overlap_ratio = appearances as f64 / total_snapshots as f64;

        // Classify stability
        let stability = if overlap_ratio >= 0.8 {
            HotspotStability::Stable
        } else if overlap_ratio >= 0.5 {
            HotspotStability::Emerging
        } else {
            HotspotStability::Volatile
        };

        hotspot_analyses.push(HotspotAnalysis {
            function_id,
            stability,
            overlap_ratio,
            appearances_in_top_k: appearances,
            total_snapshots,
        });
    }

    // Sort deterministically by function_id
    hotspot_analyses.sort_by(|a, b| a.function_id.cmp(&b.function_id));

    hotspot_analyses
}

/// Collect per-function LRS deltas across all snapshot pairs
fn collect_function_deltas(snapshots: &[Snapshot]) -> HashMap<String, Vec<(usize, f64)>> {
    let mut function_deltas: HashMap<String, Vec<(usize, f64)>> = HashMap::new();
    for i in 1..snapshots.len() {
        let prev_funcs: HashMap<&str, &crate::snapshot::FunctionSnapshot> = snapshots[i - 1]
            .functions
            .iter()
            .map(|f| (f.function_id.as_str(), f))
            .collect();
        let curr_funcs: HashMap<&str, &crate::snapshot::FunctionSnapshot> = snapshots[i]
            .functions
            .iter()
            .map(|f| (f.function_id.as_str(), f))
            .collect();
        for (function_id, curr_func) in &curr_funcs {
            if let Some(prev_func) = prev_funcs.get(function_id) {
                let delta = curr_func.lrs - prev_func.lrs;
                function_deltas
                    .entry(function_id.to_string())
                    .or_default()
                    .push((i, delta));
            }
        }
    }
    function_deltas
}

/// Check how many commits a refactor improvement was sustained and whether it rebounded
fn check_sustainment_and_rebound(
    deltas: &[(usize, f64)],
    first_improvement_idx: usize,
    snapshots_len: usize,
) -> (usize, bool) {
    let mut sustained_commits = 1;
    let mut rebound_detected = false;
    for i in first_improvement_idx..snapshots_len.min(first_improvement_idx + 3) {
        if i >= snapshots_len {
            break;
        }
        if let Some((_, delta)) = deltas.iter().find(|(idx, _)| *idx == i) {
            if *delta <= REFACTOR_IMPROVEMENT_THRESHOLD {
                sustained_commits += 1;
            } else if *delta >= REFACTOR_REBOUND_THRESHOLD {
                rebound_detected = true;
                break;
            }
        }
    }
    (sustained_commits, rebound_detected)
}

/// Compute refactor effectiveness for functions
///
/// Detects significant negative LRS deltas and classifies outcomes.
pub fn compute_refactor_effectiveness(snapshots: &[Snapshot]) -> Vec<RefactorAnalysis> {
    if snapshots.len() < 2 {
        return Vec::new();
    }

    let function_deltas = collect_function_deltas(snapshots);
    let mut refactor_analyses = Vec::new();

    for (function_id, deltas) in function_deltas {
        let improvements: Vec<(usize, f64)> = deltas
            .iter()
            .filter(|(_, d)| *d <= REFACTOR_IMPROVEMENT_THRESHOLD)
            .copied()
            .collect();
        if improvements.is_empty() {
            continue;
        }

        let first_idx = improvements[0].0;
        let improvement_delta = improvements[0].1;
        let (sustained_commits, rebound_detected) =
            check_sustainment_and_rebound(&deltas, first_idx, snapshots.len());

        let outcome = if sustained_commits >= 2 && !rebound_detected {
            RefactorOutcome::Successful
        } else if sustained_commits >= 2 && rebound_detected {
            RefactorOutcome::Partial
        } else {
            RefactorOutcome::Cosmetic
        };

        refactor_analyses.push(RefactorAnalysis {
            function_id,
            outcome,
            improvement_delta,
            sustained_commits,
            rebound_detected,
        });
    }

    refactor_analyses.sort_by(|a, b| a.function_id.cmp(&b.function_id));
    refactor_analyses
}

/// Compute complete trends analysis
pub fn analyze_trends(
    repo_root: &Path,
    window_size: usize,
    top_k: usize,
) -> Result<TrendsAnalysis> {
    let snapshots = load_snapshot_window(repo_root, window_size)?;

    let velocities = compute_risk_velocities(&snapshots);
    let hotspots = compute_hotspot_stability(&snapshots, top_k);
    let refactors = compute_refactor_effectiveness(&snapshots);

    Ok(TrendsAnalysis {
        velocities,
        hotspots,
        refactors,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::git::GitContext;
    use crate::report::{FunctionRiskReport, MetricsReport, RiskReport};
    use crate::snapshot::FunctionSnapshot;

    fn create_test_snapshot(
        sha: &str,
        parent_sha: &str,
        functions: Vec<FunctionSnapshot>,
    ) -> Snapshot {
        let git_context = GitContext {
            head_sha: sha.to_string(),
            parent_shas: vec![parent_sha.to_string()],
            timestamp: 1705600000,
            branch: Some("main".to_string()),
            is_detached: false,
            message: Some("test commit".to_string()),
            author: Some("Test Author".to_string()),
            is_fix_commit: Some(false),
            is_revert_commit: Some(false),
            ticket_ids: vec![],
        };

        let reports: Vec<FunctionRiskReport> = functions
            .iter()
            .map(|f| FunctionRiskReport {
                file: f.file.clone(),
                function: f.function_id.split("::").last().unwrap_or("").to_string(),
                line: f.line,
                language: f.language,
                metrics: f.metrics.clone(),
                risk: RiskReport {
                    r_cc: 0.0,
                    r_nd: 0.0,
                    r_fo: 0.0,
                    r_ns: 0.0,
                },
                lrs: f.lrs,
                band: f.band,
                suppression_reason: None,
                patterns: vec![],
                pattern_details: None,
                callees: vec![],
                explanation: None,
            })
            .collect();

        Snapshot::new(git_context, reports)
    }

    #[test]
    fn test_risk_velocity_positive() {
        let snapshots = vec![
            create_test_snapshot(
                "sha1",
                "sha0",
                vec![FunctionSnapshot {
                    function_id: "src/foo.ts::func".to_string(),
                    file: "src/foo.ts".to_string(),
                    line: 1,
                    language: crate::language::Language::TypeScript,
                    metrics: MetricsReport {
                        cc: 1,
                        nd: 0,
                        fo: 0,
                        ns: 0,
                        loc: 10,
                    },
                    lrs: 1.0,
                    band: crate::risk::RiskBand::Low,
                    suppression_reason: None,
                    churn: None,
                    touch_count_30d: None,
                    days_since_last_change: None,
                    callgraph: None,
                    activity_risk: None,
                    risk_factors: None,
                    percentile: None,
                    driver: None,
                    driver_detail: None,
                    quadrant: None,
                    patterns: vec![],
                    pattern_details: None,
                    subsystem: None,
                    authors_90d: None,
                    directed_coupling: None,
                    jaccard_label_stability: None,
                    convention_bug_fix_count: None,
                    burst_score: None,
                    commit_count: None,
                    author_count: None,
                    author_entropy: None,
                    isolation_rate: None,
                    age_days: None,
                    last_touch_days: None,
                    newcomer_rate: None,
                    explanation: None,
                }],
            ),
            create_test_snapshot(
                "sha2",
                "sha1",
                vec![FunctionSnapshot {
                    function_id: "src/foo.ts::func".to_string(),
                    file: "src/foo.ts".to_string(),
                    line: 1,
                    language: crate::language::Language::TypeScript,
                    metrics: MetricsReport {
                        cc: 2,
                        nd: 1,
                        fo: 0,
                        ns: 0,
                        loc: 10,
                    },
                    lrs: 3.0,
                    band: crate::risk::RiskBand::Moderate,
                    suppression_reason: None,
                    churn: None,
                    touch_count_30d: None,
                    days_since_last_change: None,
                    callgraph: None,
                    activity_risk: None,
                    risk_factors: None,
                    percentile: None,
                    driver: None,
                    driver_detail: None,
                    quadrant: None,
                    patterns: vec![],
                    pattern_details: None,
                    subsystem: None,
                    authors_90d: None,
                    directed_coupling: None,
                    jaccard_label_stability: None,
                    convention_bug_fix_count: None,
                    burst_score: None,
                    commit_count: None,
                    author_count: None,
                    author_entropy: None,
                    isolation_rate: None,
                    age_days: None,
                    last_touch_days: None,
                    newcomer_rate: None,
                    explanation: None,
                }],
            ),
        ];

        let velocities = compute_risk_velocities(&snapshots);
        assert_eq!(velocities.len(), 1);
        assert_eq!(velocities[0].function_id, "src/foo.ts::func");
        assert_eq!(velocities[0].velocity, 2.0); // (3.0 - 1.0) / (2 - 1) = 2.0
        assert_eq!(velocities[0].direction, VelocityDirection::Positive);
    }

    #[test]
    fn test_risk_velocity_flat() {
        let snapshots = vec![
            create_test_snapshot(
                "sha1",
                "sha0",
                vec![FunctionSnapshot {
                    function_id: "src/foo.ts::func".to_string(),
                    file: "src/foo.ts".to_string(),
                    line: 1,
                    language: crate::language::Language::TypeScript,
                    metrics: MetricsReport {
                        cc: 1,
                        nd: 0,
                        fo: 0,
                        ns: 0,
                        loc: 10,
                    },
                    lrs: 1.0,
                    band: crate::risk::RiskBand::Low,
                    suppression_reason: None,
                    churn: None,
                    touch_count_30d: None,
                    days_since_last_change: None,
                    callgraph: None,
                    activity_risk: None,
                    risk_factors: None,
                    percentile: None,
                    driver: None,
                    driver_detail: None,
                    quadrant: None,
                    patterns: vec![],
                    pattern_details: None,
                    subsystem: None,
                    authors_90d: None,
                    directed_coupling: None,
                    jaccard_label_stability: None,
                    convention_bug_fix_count: None,
                    burst_score: None,
                    commit_count: None,
                    author_count: None,
                    author_entropy: None,
                    isolation_rate: None,
                    age_days: None,
                    last_touch_days: None,
                    newcomer_rate: None,
                    explanation: None,
                }],
            ),
            create_test_snapshot(
                "sha2",
                "sha1",
                vec![FunctionSnapshot {
                    function_id: "src/foo.ts::func".to_string(),
                    file: "src/foo.ts".to_string(),
                    line: 1,
                    language: crate::language::Language::TypeScript,
                    metrics: MetricsReport {
                        cc: 1,
                        nd: 0,
                        fo: 0,
                        ns: 0,
                        loc: 10,
                    },
                    lrs: 1.0,
                    band: crate::risk::RiskBand::Low,
                    suppression_reason: None,
                    churn: None,
                    touch_count_30d: None,
                    days_since_last_change: None,
                    callgraph: None,
                    activity_risk: None,
                    risk_factors: None,
                    percentile: None,
                    driver: None,
                    driver_detail: None,
                    quadrant: None,
                    patterns: vec![],
                    pattern_details: None,
                    subsystem: None,
                    authors_90d: None,
                    directed_coupling: None,
                    jaccard_label_stability: None,
                    convention_bug_fix_count: None,
                    burst_score: None,
                    commit_count: None,
                    author_count: None,
                    author_entropy: None,
                    isolation_rate: None,
                    age_days: None,
                    last_touch_days: None,
                    newcomer_rate: None,
                    explanation: None,
                }],
            ),
        ];

        let velocities = compute_risk_velocities(&snapshots);
        assert_eq!(velocities.len(), 1);
        assert_eq!(velocities[0].direction, VelocityDirection::Flat);
    }

    #[test]
    fn test_hotspot_stability() {
        let snapshots = vec![
            create_test_snapshot(
                "sha1",
                "sha0",
                vec![
                    FunctionSnapshot {
                        function_id: "src/foo.ts::func1".to_string(),
                        file: "src/foo.ts".to_string(),
                        line: 1,
                        language: crate::language::Language::TypeScript,
                        metrics: MetricsReport {
                            cc: 10,
                            nd: 5,
                            fo: 3,
                            ns: 2,
                            loc: 20,
                        },
                        lrs: 15.0,
                        band: crate::risk::RiskBand::High,
                        suppression_reason: None,
                        churn: None,
                        touch_count_30d: None,
                        days_since_last_change: None,
                        callgraph: None,
                        activity_risk: None,
                        risk_factors: None,
                        percentile: None,
                        driver: None,
                        driver_detail: None,
                        quadrant: None,
                        patterns: vec![],
                        pattern_details: None,
                        subsystem: None,
                        authors_90d: None,
                        directed_coupling: None,
                        jaccard_label_stability: None,
                        convention_bug_fix_count: None,
                        burst_score: None,
                        commit_count: None,
                        author_count: None,
                        author_entropy: None,
                        isolation_rate: None,
                        age_days: None,
                        last_touch_days: None,
                        newcomer_rate: None,
                        explanation: None,
                    },
                    FunctionSnapshot {
                        function_id: "src/bar.ts::func2".to_string(),
                        file: "src/bar.ts".to_string(),
                        line: 1,
                        language: crate::language::Language::TypeScript,
                        metrics: MetricsReport {
                            cc: 5,
                            nd: 2,
                            fo: 1,
                            ns: 0,
                            loc: 10,
                        },
                        lrs: 5.0,
                        band: crate::risk::RiskBand::Moderate,
                        suppression_reason: None,
                        churn: None,
                        touch_count_30d: None,
                        days_since_last_change: None,
                        callgraph: None,
                        activity_risk: None,
                        risk_factors: None,
                        percentile: None,
                        driver: None,
                        driver_detail: None,
                        quadrant: None,
                        patterns: vec![],
                        pattern_details: None,
                        subsystem: None,
                        authors_90d: None,
                        directed_coupling: None,
                        jaccard_label_stability: None,
                        convention_bug_fix_count: None,
                        burst_score: None,
                        commit_count: None,
                        author_count: None,
                        author_entropy: None,
                        isolation_rate: None,
                        age_days: None,
                        last_touch_days: None,
                        newcomer_rate: None,
                        explanation: None,
                    },
                ],
            ),
            create_test_snapshot(
                "sha2",
                "sha1",
                vec![
                    FunctionSnapshot {
                        function_id: "src/foo.ts::func1".to_string(),
                        file: "src/foo.ts".to_string(),
                        line: 1,
                        language: crate::language::Language::TypeScript,
                        metrics: MetricsReport {
                            cc: 12,
                            nd: 6,
                            fo: 4,
                            ns: 2,
                            loc: 25,
                        },
                        lrs: 18.0,
                        band: crate::risk::RiskBand::High,
                        suppression_reason: None,
                        churn: None,
                        touch_count_30d: None,
                        days_since_last_change: None,
                        callgraph: None,
                        activity_risk: None,
                        risk_factors: None,
                        percentile: None,
                        driver: None,
                        driver_detail: None,
                        quadrant: None,
                        patterns: vec![],
                        pattern_details: None,
                        subsystem: None,
                        authors_90d: None,
                        directed_coupling: None,
                        jaccard_label_stability: None,
                        convention_bug_fix_count: None,
                        burst_score: None,
                        commit_count: None,
                        author_count: None,
                        author_entropy: None,
                        isolation_rate: None,
                        age_days: None,
                        last_touch_days: None,
                        newcomer_rate: None,
                        explanation: None,
                    },
                    FunctionSnapshot {
                        function_id: "src/bar.ts::func2".to_string(),
                        file: "src/bar.ts".to_string(),
                        line: 1,
                        language: crate::language::Language::TypeScript,
                        metrics: MetricsReport {
                            cc: 5,
                            nd: 2,
                            fo: 1,
                            ns: 0,
                            loc: 10,
                        },
                        lrs: 5.0,
                        band: crate::risk::RiskBand::Moderate,
                        suppression_reason: None,
                        churn: None,
                        touch_count_30d: None,
                        days_since_last_change: None,
                        callgraph: None,
                        activity_risk: None,
                        risk_factors: None,
                        percentile: None,
                        driver: None,
                        driver_detail: None,
                        quadrant: None,
                        patterns: vec![],
                        pattern_details: None,
                        subsystem: None,
                        authors_90d: None,
                        directed_coupling: None,
                        jaccard_label_stability: None,
                        convention_bug_fix_count: None,
                        burst_score: None,
                        commit_count: None,
                        author_count: None,
                        author_entropy: None,
                        isolation_rate: None,
                        age_days: None,
                        last_touch_days: None,
                        newcomer_rate: None,
                        explanation: None,
                    },
                ],
            ),
        ];

        let hotspots = compute_hotspot_stability(&snapshots, 1);
        assert_eq!(hotspots.len(), 1);
        assert_eq!(hotspots[0].function_id, "src/foo.ts::func1");
        assert_eq!(hotspots[0].stability, HotspotStability::Stable);
        assert_eq!(hotspots[0].overlap_ratio, 1.0);
    }

    /// Regression test for #229: with only a single snapshot, every function
    /// trivially has overlap_ratio 1.0 by formula, but labeling it "stable"
    /// is misleading — there's no history to be stable across yet. Mirrors
    /// `compute_risk_velocities`'s n<2 guard, which stays empty at n=1.
    #[test]
    fn test_hotspot_stability_empty_with_single_snapshot() {
        let snapshots = vec![create_test_snapshot(
            "sha1",
            "sha0",
            vec![FunctionSnapshot {
                function_id: "src/foo.ts::func1".to_string(),
                file: "src/foo.ts".to_string(),
                line: 1,
                language: crate::language::Language::TypeScript,
                metrics: MetricsReport {
                    cc: 12,
                    nd: 6,
                    fo: 4,
                    ns: 2,
                    loc: 25,
                },
                lrs: 18.0,
                band: crate::risk::RiskBand::High,
                suppression_reason: None,
                churn: None,
                touch_count_30d: None,
                days_since_last_change: None,
                callgraph: None,
                activity_risk: None,
                risk_factors: None,
                percentile: None,
                driver: None,
                driver_detail: None,
                quadrant: None,
                patterns: vec![],
                pattern_details: None,
                subsystem: None,
                authors_90d: None,
                directed_coupling: None,
                jaccard_label_stability: None,
                convention_bug_fix_count: None,
                burst_score: None,
                commit_count: None,
                author_count: None,
                author_entropy: None,
                isolation_rate: None,
                age_days: None,
                last_touch_days: None,
                newcomer_rate: None,
                explanation: None,
            }],
        )];

        let hotspots = compute_hotspot_stability(&snapshots, 1);
        assert!(
            hotspots.is_empty(),
            "a single snapshot must not produce 'stable' labels: {:?}",
            hotspots
        );
    }
}