hotspots-core 1.35.5

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
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
//! Parent-relative delta computation
//!
//! Computes deterministic deltas between a snapshot and its parent.
//!
//! Global invariants enforced:
//! - Deltas are parent-relative (use parents[0] only)
//! - Missing parents produce baselines, not errors
//! - Function matching by function_id (file moves are delete + add)
//! - Status based on metrics/LRS/band changes, not file/line movements

use crate::policy::PolicyResults;
use crate::report::MetricsReport;
use crate::risk::RiskBand;
use crate::snapshot::{FunctionSnapshot, Snapshot};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

/// Schema version for deltas
const DELTA_SCHEMA_VERSION: u32 = 1;

/// Function change status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum FunctionStatus {
    New,
    Deleted,
    Modified,
    Unchanged,
}

/// Function state in delta (before or after)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct FunctionState {
    pub metrics: MetricsReport,
    pub lrs: f64,
    pub band: RiskBand,
}

/// Numeric delta for a function
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct FunctionDelta {
    pub cc: i64,
    pub nd: i64,
    pub fo: i64,
    pub ns: i64,
    pub lrs: f64,
}

/// Band transition information
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub struct BandTransition {
    pub from: String,
    pub to: String,
}

/// Single function delta entry
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct FunctionDeltaEntry {
    pub function_id: String,
    pub status: FunctionStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<FunctionState>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<FunctionState>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delta: Option<FunctionDelta>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub band_transition: Option<BandTransition>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suppression_reason: Option<String>,
    /// Fuzzy-matched new function_id when this Deleted entry is likely a rename/move.
    /// Set by second-pass heuristic; absent when exact match was found or no match possible.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rename_hint: Option<String>,
}

/// Commit info in delta
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct DeltaCommitInfo {
    pub sha: String,
    pub parent: String,
}

/// Complete delta between two snapshots
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct Delta {
    #[serde(rename = "schema_version")]
    pub schema_version: u32,
    pub commit: DeltaCommitInfo,
    pub baseline: bool,
    pub deltas: Vec<FunctionDeltaEntry>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy: Option<PolicyResults>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub aggregates: Option<crate::aggregates::DeltaAggregates>,
}

impl Delta {
    /// Create a delta between current and parent snapshots
    ///
    /// # Arguments
    ///
    /// * `current` - Current snapshot
    /// * `parent` - Parent snapshot (None if baseline)
    ///
    /// # Baseline Handling
    ///
    /// If `parent` is None, all functions in `current` are marked as `new`
    /// and `baseline` is set to `true`.
    pub fn new(current: &Snapshot, parent: Option<&Snapshot>) -> Result<Self> {
        validate_snapshot_versions(current, parent)?;
        // Get parent SHA (use parents[0] only for delta computation)
        let parent_sha = current.commit.parents.first().cloned().unwrap_or_default();
        if parent.is_none() {
            return Ok(build_baseline_delta(current, parent_sha));
        }
        let parent_snap = parent.unwrap();
        let parent_funcs: HashMap<&str, &FunctionSnapshot> = parent_snap
            .functions
            .iter()
            .map(|f| (f.function_id.as_str(), f))
            .collect();
        let current_funcs: HashMap<&str, &FunctionSnapshot> = current
            .functions
            .iter()
            .map(|f| (f.function_id.as_str(), f))
            .collect();
        // Collect all function_ids (union of parent and current), sorted deterministically
        let mut all_ids: Vec<&str> = parent_funcs
            .keys()
            .chain(current_funcs.keys())
            .copied()
            .collect::<std::collections::HashSet<_>>()
            .into_iter()
            .collect();
        all_ids.sort();
        let mut deltas = compute_function_deltas(&all_ids, &parent_funcs, &current_funcs);
        apply_rename_hints(&mut deltas, &parent_funcs, &current_funcs);
        Ok(Delta {
            schema_version: DELTA_SCHEMA_VERSION,
            commit: DeltaCommitInfo {
                sha: current.commit.sha.clone(),
                parent: parent_sha,
            },
            baseline: false,
            deltas,
            policy: None,
            aggregates: None,
        })
    }

    /// Serialize delta to JSON string (deterministic ordering)
    pub fn to_json(&self) -> Result<String> {
        serde_json::to_string_pretty(self).context("failed to serialize delta to JSON")
    }

    /// Serialize delta entries as newline-delimited JSON (one entry per line).
    pub fn to_jsonl(&self) -> Result<String> {
        let mut lines = Vec::with_capacity(self.deltas.len());
        for entry in &self.deltas {
            lines.push(
                serde_json::to_string(entry).context("failed to serialize delta entry to JSON")?,
            );
        }
        Ok(lines.join("\n"))
    }

    /// Deserialize delta from JSON string
    pub fn from_json(json: &str) -> Result<Self> {
        let delta: Delta =
            serde_json::from_str(json).context("failed to deserialize delta from JSON")?;

        // Validate schema version
        if delta.schema_version != DELTA_SCHEMA_VERSION {
            anyhow::bail!(
                "delta schema version mismatch: expected {}, got {}",
                DELTA_SCHEMA_VERSION,
                delta.schema_version
            );
        }

        Ok(delta)
    }
}

fn validate_snapshot_versions(current: &Snapshot, parent: Option<&Snapshot>) -> Result<()> {
    if current.schema_version != crate::snapshot::SNAPSHOT_SCHEMA_VERSION {
        anyhow::bail!(
            "current snapshot schema version mismatch: expected {}, got {}",
            crate::snapshot::SNAPSHOT_SCHEMA_VERSION,
            current.schema_version
        );
    }
    if let Some(p) = parent {
        if p.schema_version != crate::snapshot::SNAPSHOT_SCHEMA_VERSION {
            anyhow::bail!(
                "parent snapshot schema version mismatch: expected {}, got {}",
                crate::snapshot::SNAPSHOT_SCHEMA_VERSION,
                p.schema_version
            );
        }
    }
    Ok(())
}

fn build_baseline_delta(current: &Snapshot, parent_sha: String) -> Delta {
    let deltas = current
        .functions
        .iter()
        .map(|func| FunctionDeltaEntry {
            function_id: func.function_id.clone(),
            status: FunctionStatus::New,
            before: None,
            after: Some(FunctionState {
                metrics: func.metrics.clone(),
                lrs: func.lrs,
                band: func.band,
            }),
            delta: None,
            band_transition: None,
            suppression_reason: func.suppression_reason.clone(),
            rename_hint: None,
        })
        .collect();
    Delta {
        schema_version: DELTA_SCHEMA_VERSION,
        commit: DeltaCommitInfo {
            sha: current.commit.sha.clone(),
            parent: parent_sha,
        },
        baseline: true,
        deltas,
        policy: None,
        aggregates: None,
    }
}

fn compute_function_deltas(
    all_ids: &[&str],
    parent_funcs: &HashMap<&str, &FunctionSnapshot>,
    current_funcs: &HashMap<&str, &FunctionSnapshot>,
) -> Vec<FunctionDeltaEntry> {
    let mut deltas = Vec::new();
    for function_id in all_ids {
        let parent_func = parent_funcs.get(function_id);
        let current_func = current_funcs.get(function_id);
        match (parent_func, current_func) {
            (Some(parent), Some(current)) => {
                let status = if functions_differ(parent, current) {
                    FunctionStatus::Modified
                } else {
                    FunctionStatus::Unchanged
                };
                let delta = if status == FunctionStatus::Modified {
                    Some(compute_function_delta(parent, current))
                } else {
                    None
                };
                let band_transition = if parent.band != current.band {
                    Some(BandTransition {
                        from: parent.band.as_str().to_string(),
                        to: current.band.as_str().to_string(),
                    })
                } else {
                    None
                };
                deltas.push(FunctionDeltaEntry {
                    function_id: function_id.to_string(),
                    status,
                    before: Some(FunctionState {
                        metrics: parent.metrics.clone(),
                        lrs: parent.lrs,
                        band: parent.band,
                    }),
                    after: Some(FunctionState {
                        metrics: current.metrics.clone(),
                        lrs: current.lrs,
                        band: current.band,
                    }),
                    delta,
                    band_transition,
                    suppression_reason: current.suppression_reason.clone(),
                    rename_hint: None,
                });
            }
            (Some(parent), None) => {
                deltas.push(FunctionDeltaEntry {
                    function_id: function_id.to_string(),
                    status: FunctionStatus::Deleted,
                    before: Some(FunctionState {
                        metrics: parent.metrics.clone(),
                        lrs: parent.lrs,
                        band: parent.band,
                    }),
                    after: None,
                    delta: Some(compute_delete_delta(parent)),
                    band_transition: None,
                    suppression_reason: parent.suppression_reason.clone(),
                    rename_hint: None,
                });
            }
            (None, Some(current)) => {
                deltas.push(FunctionDeltaEntry {
                    function_id: function_id.to_string(),
                    status: FunctionStatus::New,
                    before: None,
                    after: Some(FunctionState {
                        metrics: current.metrics.clone(),
                        lrs: current.lrs,
                        band: current.band,
                    }),
                    delta: None,
                    band_transition: None,
                    suppression_reason: current.suppression_reason.clone(),
                    rename_hint: None,
                });
            }
            (None, None) => {
                unreachable!("function_id should exist in at least one snapshot");
            }
        }
    }
    deltas
}

/// Find the best rename match for a deleted function among new functions.
///
/// Returns the new function ID if a match is found (first match wins).
fn find_rename_match<'a>(
    del_id: &str,
    del_func: &FunctionSnapshot,
    new_ids: &'a [String],
    current_funcs: &HashMap<&str, &FunctionSnapshot>,
    matched_new: &std::collections::HashSet<String>,
) -> Option<&'a str> {
    let del_name = del_id
        .strip_prefix(&format!("{}::", del_func.file))
        .unwrap_or(del_id);
    for new_id in new_ids {
        if matched_new.contains(new_id) {
            continue;
        }
        let new_func = match current_funcs.get(new_id.as_str()) {
            Some(f) => f,
            None => continue,
        };
        let new_name = new_id
            .strip_prefix(&format!("{}::", new_func.file))
            .unwrap_or(new_id.as_str());
        if del_name == new_name && del_func.file != new_func.file {
            return Some(new_id.as_str());
        }
        if del_func.file == new_func.file && del_func.line.abs_diff(new_func.line) <= 10 {
            return Some(new_id.as_str());
        }
    }
    None
}

/// Write rename_hint onto each Deleted entry that was matched
fn apply_hints(deltas: &mut [FunctionDeltaEntry], hints: &[(String, String)]) {
    for (del_id, new_id) in hints {
        for entry in deltas.iter_mut() {
            if entry.function_id == *del_id {
                entry.rename_hint = Some(new_id.clone());
                break;
            }
        }
    }
}

/// Second pass: fuzzy match Deleted+New pairs as likely renames/moves.
///
/// Heuristics (applied in order, first match wins):
///   1. Same function name, different file → likely file rename
///   2. Same file, start line within ±10 → likely function move within file
///
/// Only sets `rename_hint` on the Deleted entry; does not change status.
fn apply_rename_hints(
    deltas: &mut [FunctionDeltaEntry],
    parent_funcs: &HashMap<&str, &FunctionSnapshot>,
    current_funcs: &HashMap<&str, &FunctionSnapshot>,
) {
    let deleted_ids: Vec<String> = deltas
        .iter()
        .filter(|e| e.status == FunctionStatus::Deleted)
        .map(|e| e.function_id.clone())
        .collect();
    let new_ids: Vec<String> = deltas
        .iter()
        .filter(|e| e.status == FunctionStatus::New)
        .map(|e| e.function_id.clone())
        .collect();
    if deleted_ids.is_empty() || new_ids.is_empty() {
        return;
    }
    let mut matched_new: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut hints: Vec<(String, String)> = Vec::new();
    for del_id in &deleted_ids {
        let del_func = match parent_funcs.get(del_id.as_str()) {
            Some(f) => f,
            None => continue,
        };
        if let Some(new_id) =
            find_rename_match(del_id, del_func, &new_ids, current_funcs, &matched_new)
        {
            hints.push((del_id.clone(), new_id.to_string()));
            matched_new.insert(new_id.to_string());
        }
    }
    apply_hints(deltas, &hints);
}

/// Check if two functions differ (based on metrics, LRS, or band)
///
/// Ignores file/line changes - only structural changes matter.
fn functions_differ(parent: &FunctionSnapshot, current: &FunctionSnapshot) -> bool {
    parent.metrics != current.metrics
        || (parent.lrs - current.lrs).abs() > f64::EPSILON
        || parent.band != current.band
}

/// Compute numeric delta between two functions
///
/// Returns deltas for metrics and LRS. Negative deltas are allowed
/// (valid for reverts, refactors).
fn compute_function_delta(parent: &FunctionSnapshot, current: &FunctionSnapshot) -> FunctionDelta {
    FunctionDelta {
        cc: current.metrics.cc as i64 - parent.metrics.cc as i64,
        nd: current.metrics.nd as i64 - parent.metrics.nd as i64,
        fo: current.metrics.fo as i64 - parent.metrics.fo as i64,
        ns: current.metrics.ns as i64 - parent.metrics.ns as i64,
        lrs: current.lrs - parent.lrs,
    }
}

/// Compute delta for a deleted function (all values negative)
fn compute_delete_delta(parent: &FunctionSnapshot) -> FunctionDelta {
    FunctionDelta {
        cc: -(parent.metrics.cc as i64),
        nd: -(parent.metrics.nd as i64),
        fo: -(parent.metrics.fo as i64),
        ns: -(parent.metrics.ns as i64),
        lrs: -parent.lrs,
    }
}

/// Load parent snapshot for delta computation
///
/// Loads the snapshot for `parent_sha` from the repository.
/// Returns None if the snapshot doesn't exist (baseline case).
///
/// # Arguments
///
/// * `repo_root` - Repository root path
/// * `parent_sha` - Parent commit SHA (from parents[0])
///
/// # Errors
///
/// Returns error if snapshot exists but cannot be read/parsed.
pub fn load_parent_snapshot(repo_root: &Path, parent_sha: &str) -> Result<Option<Snapshot>> {
    crate::snapshot::load_snapshot(repo_root, parent_sha)
}

/// Compute delta for a snapshot against its parent
///
/// Loads parent snapshot and computes delta. If parent is missing,
/// returns baseline delta (baseline=true).
///
/// A baseline delta always skips policy evaluation ([`crate::policy::evaluate_policies`])
/// since there is no prior state to compare against. That's expected and safe when the
/// current commit genuinely has no parent (a repo's root commit). It is a silent
/// false-confidence trap when the commit *does* have a parent but that parent's snapshot
/// simply isn't on disk (missing history, a cold cache, a fresh CI runner) — in that case
/// this prints a loud warning so a CI log makes clear that policy checks did not actually
/// run, rather than the run silently reporting "passed".
///
/// # Arguments
///
/// * `repo_root` - Repository root path
/// * `current` - Current snapshot
///
/// # Errors
///
/// Returns error if:
/// - Parent snapshot exists but cannot be loaded
/// - Parent snapshot has wrong schema version
/// - Delta computation fails
pub fn compute_delta(repo_root: &Path, current: &Snapshot) -> Result<Delta> {
    // Get parent SHA (use parents[0] only)
    let parent_sha = current.commit.parents.first();

    let parent = if let Some(sha) = parent_sha {
        let loaded = load_parent_snapshot(repo_root, sha)?;
        if loaded.is_none() {
            eprintln!(
                "warning: no snapshot found for parent commit {sha}; treating this analysis \
                 as a baseline and SKIPPING policy evaluation. If parent history is expected \
                 to be available (e.g. in CI), this may hide real policy violations — run \
                 `hotspots analyze` on the parent commit first, or restore its snapshot cache."
            );
        }
        loaded
    } else {
        None
    };

    Delta::new(current, parent.as_ref())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::git::GitContext;
    use crate::language::Language;
    use crate::report::{FunctionRiskReport, MetricsReport};
    use crate::risk::RiskBand;
    use crate::snapshot::Snapshot;

    fn create_test_snapshot(
        sha: &str,
        parent_sha: &str,
        cc: u32,
        lrs: f64,
        band: &str,
    ) -> 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 report = FunctionRiskReport {
            file: "src/foo.ts".to_string(),
            function: "handler".to_string(),
            line: 42,
            language: Language::TypeScript,
            metrics: MetricsReport {
                cc,
                nd: 2,
                fo: 3,
                ns: 1,
                loc: 10,
            },
            risk: crate::report::RiskReport {
                r_cc: 2.0,
                r_nd: 1.0,
                r_fo: 1.0,
                r_ns: 1.0,
            },
            lrs,
            band: RiskBand::parse(band).unwrap_or(RiskBand::Low),
            suppression_reason: None,
            patterns: vec![],
            pattern_details: None,
            callees: vec![],
            explanation: None,
        };

        Snapshot::new(git_context, vec![report])
    }

    #[test]
    fn test_baseline_delta() {
        let current = create_test_snapshot("abc123", "", 5, 4.8, "moderate");

        // No parent - should be baseline
        let delta = Delta::new(&current, None).expect("should create baseline delta");

        assert!(delta.baseline);
        assert_eq!(delta.deltas.len(), 1);
        assert_eq!(delta.deltas[0].status, FunctionStatus::New);
    }

    #[test]
    fn test_compute_delta_missing_parent_snapshot_is_still_baseline() {
        // Regression test for hotspots#141: a commit that HAS a parent SHA, but
        // whose parent snapshot simply isn't on disk (missing history, cold
        // cache, fresh CI runner), must still produce a baseline delta — the
        // fix here is a loud eprintln! warning (not asserted here, matching
        // this codebase's convention of not unit-testing warning text
        // elsewhere), not a change to the return value. This confirms the
        // `compute_delta` code path touched by that fix still behaves
        // identically for callers.
        let repo_root_dir = tempfile::tempdir().expect("failed to create temp dir");
        let repo_root = repo_root_dir.path();

        // parent123 has no snapshot persisted anywhere under repo_root.
        let current = create_test_snapshot("current123", "parent123", 5, 4.8, "moderate");

        let delta =
            compute_delta(repo_root, &current).expect("should compute baseline delta, not error");

        assert!(delta.baseline);
        assert_eq!(delta.commit.parent, "parent123");
        assert_eq!(delta.deltas.len(), 1);
        assert_eq!(delta.deltas[0].status, FunctionStatus::New);
    }

    #[test]
    fn test_compute_delta_true_root_commit_is_baseline() {
        // A genuine root commit (parent_shas is an EMPTY vec, not a vec
        // containing an empty string — create_test_snapshot always inserts
        // one entry, so it's built manually here) should also produce a
        // baseline delta, with no warning expected (distinct from the
        // missing-snapshot case above — this is the normal, expected
        // baseline path, since `current.commit.parents.first()` is None).
        let repo_root_dir = tempfile::tempdir().expect("failed to create temp dir");
        let repo_root = repo_root_dir.path();

        // create_test_snapshot always inserts one parent_shas entry, so the
        // genuinely-empty-parents case is built by clearing it after the fact.
        let mut current = create_test_snapshot("root123", "unused", 5, 4.8, "moderate");
        current.commit.parents.clear();

        assert!(current.commit.parents.is_empty());

        let delta = compute_delta(repo_root, &current).expect("should compute baseline delta");

        assert!(delta.baseline);
        assert_eq!(delta.deltas.len(), 1);
        assert_eq!(delta.deltas[0].status, FunctionStatus::New);
    }

    #[test]
    fn test_modified_delta() {
        let parent = create_test_snapshot("parent123", "grandparent", 4, 3.9, "moderate");
        let current = create_test_snapshot("current123", "parent123", 6, 6.2, "high");

        let delta = Delta::new(&current, Some(&parent)).expect("should create delta");

        assert!(!delta.baseline);
        assert_eq!(delta.deltas.len(), 1);
        assert_eq!(delta.deltas[0].status, FunctionStatus::Modified);

        let delta_values = delta.deltas[0].delta.as_ref().unwrap();
        assert_eq!(delta_values.cc, 2); // 6 - 4 = 2
        assert!((delta_values.lrs - 2.3).abs() < 0.01); // 6.2 - 3.9 ≈ 2.3

        // Check band transition
        let transition = delta.deltas[0].band_transition.as_ref().unwrap();
        assert_eq!(transition.from, "moderate");
        assert_eq!(transition.to, "high");
    }

    #[test]
    fn test_unchanged_delta() {
        let parent = create_test_snapshot("parent123", "grandparent", 5, 4.8, "moderate");
        let current = create_test_snapshot("current123", "parent123", 5, 4.8, "moderate");

        let delta = Delta::new(&current, Some(&parent)).expect("should create delta");

        assert_eq!(delta.deltas.len(), 1);
        assert_eq!(delta.deltas[0].status, FunctionStatus::Unchanged);
        assert!(delta.deltas[0].delta.is_none());
        assert!(delta.deltas[0].band_transition.is_none());
    }

    #[test]
    fn test_negative_deltas() {
        let parent = create_test_snapshot("parent123", "grandparent", 6, 6.2, "high");
        let current = create_test_snapshot("current123", "parent123", 4, 3.9, "moderate");

        let delta = Delta::new(&current, Some(&parent)).expect("should create delta");

        let delta_values = delta.deltas[0].delta.as_ref().unwrap();
        assert_eq!(delta_values.cc, -2); // 4 - 6 = -2 (negative allowed)
        assert!(delta_values.lrs < 0.0); // Negative LRS delta allowed
    }

    #[test]
    fn test_deleted_function() {
        let parent = create_test_snapshot("parent123", "grandparent", 5, 4.8, "moderate");

        // Current has no functions (empty)
        let git_context = GitContext {
            head_sha: "current123".to_string(),
            parent_shas: vec!["parent123".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 current = Snapshot::new(git_context, vec![]);

        let delta = Delta::new(&current, Some(&parent)).expect("should create delta");

        assert_eq!(delta.deltas.len(), 1);
        assert_eq!(delta.deltas[0].status, FunctionStatus::Deleted);
        assert!(delta.deltas[0].before.is_some());
        assert!(delta.deltas[0].after.is_none());
    }
}