Skip to main content

fallow_engine/
vital_signs.rs

1//! Vital signs computation and snapshot persistence.
2//!
3//! Vital signs are a fixed set of project-wide metrics computed from available
4//! health data. They are always shown as a summary in the health report and can
5//! be persisted to `.fallow/snapshots/` for Phase 2b trend tracking.
6
7use std::path::{Path, PathBuf};
8
9/// Fraction of the file population used for hotspot concentration.
10const HOTSPOT_TOP_FILE_FRACTION: f64 = 0.01;
11
12/// Maximum project health penalty for thresholded hotspots.
13const HOTSPOT_MAX_PENALTY: f64 = 10.0;
14
15use fallow_output::{
16    DEFAULT_CYCLOMATIC_CRITICAL, FileHealthScore, HEALTH_SCORE_FORMULA_VERSION,
17    HOTSPOT_SCORE_THRESHOLD, HealthScore, HealthScorePenalties, HealthTrend, HotspotEntry,
18    RiskProfile, SNAPSHOT_SCHEMA_VERSION, TrendCount, TrendDirection, TrendMetric, TrendPoint,
19    VitalSigns, VitalSignsCounts, VitalSignsSnapshot, letter_grade,
20};
21
22/// Data sources for computing vital signs.
23///
24/// Fields are `Option` because not all pipelines run in every health invocation.
25pub(crate) struct VitalSignsInput<'a> {
26    /// All parsed modules (always available).
27    pub(crate) modules: &'a [crate::source::ModuleInfo],
28    /// Optional file-id allowlist used to restrict per-module aggregates
29    /// (cyclomatic distribution, total LOC, unit profiles) to a subset.
30    /// Used by `--workspace` and `--group-by` to scope project-wide metrics
31    /// to a single workspace package without re-parsing.
32    /// `None` includes every module in `modules`.
33    pub(crate) module_filter: Option<&'a rustc_hash::FxHashSet<crate::discover::FileId>>,
34    /// File health scores (available when file_scores/hotspots/targets are computed).
35    pub(crate) file_scores: Option<&'a [FileHealthScore]>,
36    /// Hotspot entries (available when hotspots are computed).
37    pub(crate) hotspots: Option<&'a [HotspotEntry]>,
38    /// Total discovered files (already scoped to the workspace when `--workspace` is set).
39    pub(crate) total_files: usize,
40    /// Analysis results (available when file_scores pipeline ran). When a
41    /// `module_filter` is also set, callers should pass workspace-scoped
42    /// counts here so `dead_*_pct` denominators line up with the rest of the
43    /// metrics.
44    pub(crate) analysis_counts: Option<AnalysisCounts>,
45}
46
47impl<'a> VitalSignsInput<'a> {
48    /// Iterate the modules selected by `module_filter`.
49    fn selected_modules(&self) -> impl Iterator<Item = &'a crate::source::ModuleInfo> + '_ {
50        let filter = self.module_filter;
51        self.modules
52            .iter()
53            .filter(move |m| filter.is_none_or(|set| set.contains(&m.file_id)))
54    }
55}
56
57/// Aggregate counts from the analysis pipeline.
58#[derive(Clone, Copy)]
59pub struct AnalysisCounts {
60    pub(crate) total_exports: usize,
61    pub(crate) dead_files: usize,
62    pub(crate) dead_exports: usize,
63    pub(crate) unused_deps: usize,
64    pub(crate) circular_deps: usize,
65    pub(crate) total_deps: usize,
66}
67
68/// Every unit's cyclomatic score, sorted, feeding the average, the critical
69/// share, and p90. The synthetic module-scope unit is included: its decision
70/// points are real branching, and leaving them out is what let a file's average
71/// read low while its top level was a guard ladder.
72fn collect_sorted_cyclomatic(input: &VitalSignsInput<'_>) -> Vec<u16> {
73    let mut values: Vec<u16> = input
74        .selected_modules()
75        .flat_map(|m| m.complexity.iter().map(|c| c.cyclomatic))
76        .collect();
77    values.sort_unstable();
78    values
79}
80
81fn average_cyclomatic(all_cyclomatic: &[u16]) -> f64 {
82    if all_cyclomatic.is_empty() {
83        return 0.0;
84    }
85
86    let sum: u64 = all_cyclomatic.iter().map(|&c| u64::from(c)).sum();
87    (sum as f64 / all_cyclomatic.len() as f64 * 10.0).round() / 10.0
88}
89
90fn critical_complexity_pct(all_cyclomatic: &[u16]) -> Option<f64> {
91    if all_cyclomatic.is_empty() {
92        return None;
93    }
94
95    let critical_count = all_cyclomatic
96        .iter()
97        .filter(|&&c| c >= DEFAULT_CYCLOMATIC_CRITICAL)
98        .count();
99    Some((critical_count as f64 / all_cyclomatic.len() as f64 * 1000.0).round() / 10.0)
100}
101
102#[expect(
103    clippy::cast_sign_loss,
104    reason = "percentile indexes of non-negative counts; float-to-int casts saturate at zero"
105)]
106#[expect(
107    clippy::cast_possible_truncation,
108    reason = "percentile index is bounded by the cyclomatic collection length"
109)]
110fn p90_cyclomatic(all_cyclomatic: &[u16]) -> u32 {
111    if all_cyclomatic.is_empty() {
112        return 0;
113    }
114
115    let idx = (all_cyclomatic.len() as f64 * 0.9).ceil() as usize;
116    let idx = idx.min(all_cyclomatic.len()) - 1;
117    u32::from(all_cyclomatic[idx])
118}
119
120#[expect(
121    clippy::cast_possible_truncation,
122    reason = "analysis counts are bounded by project size and emitted as compact u32 metrics"
123)]
124fn analysis_count_vitals(
125    counts: Option<&AnalysisCounts>,
126    total_files: usize,
127) -> (Option<f64>, Option<f64>, Option<u32>, Option<u32>) {
128    let Some(counts) = counts else {
129        return (None, None, None, None);
130    };
131
132    let dead_file_pct = if total_files > 0 {
133        Some((counts.dead_files as f64 / total_files as f64 * 1000.0).round() / 10.0)
134    } else {
135        Some(0.0)
136    };
137    let dead_export_pct = if counts.total_exports > 0 {
138        Some((counts.dead_exports as f64 / counts.total_exports as f64 * 1000.0).round() / 10.0)
139    } else {
140        Some(0.0)
141    };
142
143    (
144        dead_file_pct,
145        dead_export_pct,
146        Some(counts.unused_deps as u32),
147        Some(counts.circular_deps as u32),
148    )
149}
150
151struct SelectedModuleMetrics {
152    total_loc: u64,
153    line_counts: Vec<u32>,
154    param_counts: Vec<u8>,
155    cyclomatic_population: fallow_output::CyclomaticPopulation,
156}
157
158fn selected_module_metrics(input: &VitalSignsInput<'_>) -> SelectedModuleMetrics {
159    let mut total_loc = 0;
160    let mut line_counts = Vec::new();
161    let mut param_counts = Vec::new();
162    let mut cyclomatic_population = fallow_output::CyclomaticPopulation::default();
163
164    for module in input.selected_modules() {
165        total_loc += module.line_offsets.len() as u64;
166        // The synthetic module-scope unit is excluded from both distributions.
167        // It has no parameter list, and its size is the distance between its
168        // first and last decision point rather than a body anyone can shorten,
169        // so it is not a refactoring signal in the unit-size profile.
170        for unit in &module.complexity {
171            let is_module = fallow_types::extract::is_synthetic_module_unit(&unit.name);
172            let population = if is_module {
173                &mut cyclomatic_population.modules
174            } else if fallow_types::extract::is_synthetic_template_unit(&unit.name) {
175                &mut cyclomatic_population.templates
176            } else {
177                &mut cyclomatic_population.functions
178            };
179            population.count += 1;
180            population.sum += u64::from(unit.cyclomatic);
181            population.max = Some(population.max.unwrap_or_default().max(unit.cyclomatic));
182            if is_module {
183                continue;
184            }
185            line_counts.push(unit.line_count);
186            param_counts.push(unit.param_count);
187        }
188    }
189
190    SelectedModuleMetrics {
191        total_loc,
192        line_counts,
193        param_counts,
194        cyclomatic_population,
195    }
196}
197
198fn vital_sign_counts(input: &VitalSignsInput<'_>, total_loc: u64) -> Option<VitalSignsCounts> {
199    input.analysis_counts.as_ref().map(|ac| VitalSignsCounts {
200        total_files: input.total_files,
201        total_exports: ac.total_exports,
202        dead_files: ac.dead_files,
203        dead_exports: ac.dead_exports,
204        duplicated_lines: None,
205        total_lines: Some(total_loc as usize),
206        files_scored: input.file_scores.map(<[_]>::len),
207        total_deps: ac.total_deps,
208    })
209}
210
211/// Compute vital signs from available health data.
212pub(crate) fn compute_vital_signs(input: &VitalSignsInput<'_>) -> VitalSigns {
213    let all_cyclomatic = collect_sorted_cyclomatic(input);
214    let avg_cyclomatic = average_cyclomatic(&all_cyclomatic);
215    let critical_complexity_pct = critical_complexity_pct(&all_cyclomatic);
216    let p90_cyclomatic = p90_cyclomatic(&all_cyclomatic);
217
218    let (dead_file_pct, dead_export_pct, unused_dep_count, circular_dep_count) =
219        analysis_count_vitals(input.analysis_counts.as_ref(), input.total_files);
220    let unused_deps_per_k_files =
221        unused_dep_count.map(|count| per_k_files(count, input.total_files));
222    let circular_deps_per_k_files =
223        circular_dep_count.map(|count| per_k_files(count, input.total_files));
224
225    let (maintainability_avg, maintainability_low_pct) = maintainability_vitals(input.file_scores);
226
227    let (hotspot_count, hotspot_top_pct_count) = hotspot_vitals(input.hotspots, input.total_files);
228
229    let module_metrics = selected_module_metrics(input);
230    let counts = vital_sign_counts(input, module_metrics.total_loc);
231    let functions_over_60_loc_per_k = functions_over_60_loc_per_k(&module_metrics.line_counts);
232    let unit_size_profile = unit_size_profile(&module_metrics.line_counts);
233
234    let unit_interfacing_profile =
235        unit_interfacing_profile(&module_metrics.param_counts, &all_cyclomatic);
236
237    let (p95_fan_in, coupling_high_pct) = if let Some(scores) = input.file_scores {
238        compute_coupling_concentration(scores)
239    } else {
240        (None, None)
241    };
242
243    VitalSigns {
244        dead_file_pct,
245        dead_export_pct,
246        avg_cyclomatic,
247        critical_complexity_pct,
248        p90_cyclomatic,
249        cyclomatic_population: Some(module_metrics.cyclomatic_population),
250        duplication_pct: None, // Lazy: only set if duplication pipeline was run
251        hotspot_count,
252        hotspot_top_pct_count,
253        maintainability_avg,
254        maintainability_low_pct,
255        unused_dep_count,
256        unused_deps_per_k_files,
257        circular_dep_count,
258        circular_deps_per_k_files,
259        counts,
260        unit_size_profile,
261        functions_over_60_loc_per_k,
262        unit_interfacing_profile,
263        p95_fan_in,
264        coupling_high_pct,
265        // Set post-construction from the whole-project analysis results (only
266        // when the opt-in prop-drilling rule is enabled); see health/mod.rs.
267        prop_drilling_chain_count: None,
268        prop_drilling_max_depth: None,
269        // Set post-construction from the whole-project render fan-in metric
270        // (whenever React is declared, the core metric carries the aggregates);
271        // see health/mod.rs.
272        p95_render_fan_in: None,
273        render_fan_in_high_pct: None,
274        max_render_fan_in: None,
275        top_render_fan_in: Vec::new(),
276        total_loc: module_metrics.total_loc,
277    }
278}
279
280fn per_k_files(count: u32, total_files: usize) -> f64 {
281    if total_files == 0 {
282        0.0
283    } else {
284        (f64::from(count) / total_files as f64 * 10_000.0).round() / 10.0
285    }
286}
287
288fn maintainability_vitals(scores: Option<&[FileHealthScore]>) -> (Option<f64>, Option<f64>) {
289    let Some(scores) = scores.filter(|scores| !scores.is_empty()) else {
290        return (None, None);
291    };
292    let sum: f64 = scores.iter().map(|s| s.maintainability_index).sum();
293    let low_count = scores
294        .iter()
295        .filter(|s| s.maintainability_index < 70.0)
296        .count();
297    (
298        Some((sum / scores.len() as f64 * 10.0).round() / 10.0),
299        Some((low_count as f64 / scores.len() as f64 * 1000.0).round() / 10.0),
300    )
301}
302
303#[expect(
304    clippy::cast_sign_loss,
305    reason = "percentile indexes of non-negative counts; float-to-int casts saturate at zero"
306)]
307fn hotspot_vitals(
308    hotspots: Option<&[HotspotEntry]>,
309    total_files: usize,
310) -> (Option<u32>, Option<u32>) {
311    let hotspot_count = hotspots.map(|entries| {
312        entries
313            .iter()
314            .filter(|e| e.score >= HOTSPOT_SCORE_THRESHOLD)
315            .count() as u32
316    });
317    let hotspot_top_pct_count = hotspots.map(|entries| {
318        if total_files == 0 || entries.is_empty() {
319            return 0;
320        }
321        let top_count = (total_files as f64 * HOTSPOT_TOP_FILE_FRACTION).ceil() as usize;
322        entries
323            .iter()
324            .take(top_count.max(1))
325            .filter(|entry| entry.score > 0.0)
326            .count() as u32
327    });
328    (hotspot_count, hotspot_top_pct_count)
329}
330
331fn functions_over_60_loc_per_k(line_counts: &[u32]) -> Option<f64> {
332    if line_counts.is_empty() {
333        return None;
334    }
335    let over_60 = line_counts
336        .iter()
337        .filter(|&&line_count| line_count > 60)
338        .count();
339    Some((over_60 as f64 / line_counts.len() as f64 * 10_000.0).round() / 10.0)
340}
341
342fn unit_size_profile(line_counts: &[u32]) -> Option<RiskProfile> {
343    (!line_counts.is_empty()).then(|| compute_size_risk_profile(line_counts))
344}
345
346fn unit_interfacing_profile(param_counts: &[u8], all_cyclomatic: &[u16]) -> Option<RiskProfile> {
347    if all_cyclomatic.is_empty() {
348        return None;
349    }
350    Some(compute_interfacing_risk_profile(param_counts))
351}
352
353/// Compute unit size risk profile from function line counts.
354///
355/// Bins: low risk (1-15 LOC), medium risk (16-30), high risk (31-60), very high risk (>60).
356fn compute_size_risk_profile(line_counts: &[u32]) -> RiskProfile {
357    if line_counts.is_empty() {
358        return RiskProfile {
359            low_risk: 0.0,
360            medium_risk: 0.0,
361            high_risk: 0.0,
362            very_high_risk: 0.0,
363        };
364    }
365    let total = line_counts.len() as f64;
366    let low = line_counts.iter().filter(|&&lc| lc <= 15).count() as f64;
367    let medium = line_counts
368        .iter()
369        .filter(|&&lc| (16..=30).contains(&lc))
370        .count() as f64;
371    let high = line_counts
372        .iter()
373        .filter(|&&lc| (31..=60).contains(&lc))
374        .count() as f64;
375    let very_high = line_counts.iter().filter(|&&lc| lc > 60).count() as f64;
376    RiskProfile {
377        low_risk: (low / total * 1000.0).round() / 10.0,
378        medium_risk: (medium / total * 1000.0).round() / 10.0,
379        high_risk: (high / total * 1000.0).round() / 10.0,
380        very_high_risk: (very_high / total * 1000.0).round() / 10.0,
381    }
382}
383
384/// Compute unit interfacing risk profile from function parameter counts.
385///
386/// Bins: low risk (0-2 params), medium risk (3-4), high risk (5-6), very high risk (>=7).
387fn compute_interfacing_risk_profile(param_counts: &[u8]) -> RiskProfile {
388    if param_counts.is_empty() {
389        return RiskProfile {
390            low_risk: 0.0,
391            medium_risk: 0.0,
392            high_risk: 0.0,
393            very_high_risk: 0.0,
394        };
395    }
396    let total = param_counts.len() as f64;
397    let low = param_counts.iter().filter(|&&pc| pc <= 2).count() as f64;
398    let medium = param_counts
399        .iter()
400        .filter(|&&pc| (3..=4).contains(&pc))
401        .count() as f64;
402    let high = param_counts
403        .iter()
404        .filter(|&&pc| (5..=6).contains(&pc))
405        .count() as f64;
406    let very_high = param_counts.iter().filter(|&&pc| pc >= 7).count() as f64;
407    RiskProfile {
408        low_risk: (low / total * 1000.0).round() / 10.0,
409        medium_risk: (medium / total * 1000.0).round() / 10.0,
410        high_risk: (high / total * 1000.0).round() / 10.0,
411        very_high_risk: (very_high / total * 1000.0).round() / 10.0,
412    }
413}
414
415/// Compute coupling concentration from file health scores.
416///
417/// Returns (p95_fan_in, coupling_high_pct) where coupling_high_pct is the
418/// percentage of files with fan-in above the effective threshold (max(p95_fan_in, 10)).
419///
420/// The component-graph analogue (render fan-in concentration:
421/// `p95_render_fan_in` / `render_fan_in_high_pct` / `max_render_fan_in`) is
422/// computed in the `analyze::render_fan_in` module of `fallow_core`, which has
423/// the resolved-module graph. It uses the same p95 and floor math over the
424/// per-component distinct-parents distribution; change both together. The
425/// result is assigned onto `VitalSigns` in
426/// `health/vital_data.rs::prepare_health_vital_data`.
427#[expect(
428    clippy::cast_sign_loss,
429    reason = "percentile indexes of non-negative counts; float-to-int casts saturate at zero"
430)]
431#[expect(
432    clippy::cast_possible_truncation,
433    reason = "fan-in values are bounded by project size"
434)]
435fn compute_coupling_concentration(scores: &[FileHealthScore]) -> (Option<u32>, Option<f64>) {
436    if scores.is_empty() {
437        return (None, None);
438    }
439    let mut fan_ins: Vec<usize> = scores.iter().map(|s| s.fan_in).collect();
440    fan_ins.sort_unstable();
441    let idx = (fan_ins.len() as f64 * 0.95).ceil() as usize;
442    let idx = idx.min(fan_ins.len()) - 1;
443    let p95 = fan_ins[idx] as u32;
444
445    let threshold = (p95 as usize).max(10);
446    let high_count = fan_ins.iter().filter(|&&fi| fi > threshold).count();
447    let high_pct = (high_count as f64 / fan_ins.len() as f64 * 1000.0).round() / 10.0;
448
449    (Some(p95), Some(high_pct))
450}
451
452/// Compute a project-level health score from vital signs.
453///
454/// The score starts at 100 and subtracts penalties for each metric.
455/// Missing metrics (from pipelines that didn't run) don't penalize.
456/// `total_files` is used to normalize the hotspot count penalty.
457pub(crate) fn compute_health_score(vs: &VitalSigns, total_files: usize) -> HealthScore {
458    let penalties = compute_health_score_penalties(vs, total_files);
459    let score = apply_health_score_penalties(&penalties);
460    let grade = letter_grade(score);
461
462    HealthScore {
463        formula_version: HEALTH_SCORE_FORMULA_VERSION,
464        score,
465        grade,
466        penalties,
467    }
468}
469
470fn compute_health_score_penalties(vs: &VitalSigns, total_files: usize) -> HealthScorePenalties {
471    HealthScorePenalties {
472        dead_files: vs.dead_file_pct.map(|pct| round1((pct * 0.2).min(15.0))),
473        dead_exports: vs.dead_export_pct.map(|pct| round1((pct * 0.2).min(15.0))),
474        complexity: complexity_penalty(vs),
475        p90_complexity: p90_complexity_penalty(vs),
476        maintainability: maintainability_penalty(vs),
477        hotspots: hotspot_penalty(vs, total_files),
478        unused_deps: dependency_count_penalty(
479            vs.unused_deps_per_k_files,
480            vs.unused_dep_count,
481            25.0,
482            10.0,
483        ),
484        circular_deps: dependency_count_penalty(
485            vs.circular_deps_per_k_files,
486            vs.circular_dep_count,
487            25.0,
488            10.0,
489        ),
490        unit_size: unit_size_penalty(vs),
491        coupling: coupling_penalty(vs),
492        duplication: vs
493            .duplication_pct
494            .map(|dp| round1((dp - 5.0).clamp(0.0, 10.0))),
495        prop_drilling: prop_drilling_penalty(vs),
496    }
497}
498
499fn apply_health_score_penalties(penalties: &HealthScorePenalties) -> f64 {
500    let mut score = 100.0_f64;
501
502    subtract_optional_penalty(&mut score, penalties.dead_files);
503    subtract_optional_penalty(&mut score, penalties.dead_exports);
504    score -= penalties.complexity;
505    score -= penalties.p90_complexity;
506    subtract_optional_penalty(&mut score, penalties.maintainability);
507    subtract_optional_penalty(&mut score, penalties.hotspots);
508    subtract_optional_penalty(&mut score, penalties.unused_deps);
509    subtract_optional_penalty(&mut score, penalties.circular_deps);
510    subtract_optional_penalty(&mut score, penalties.unit_size);
511    subtract_optional_penalty(&mut score, penalties.coupling);
512    subtract_optional_penalty(&mut score, penalties.duplication);
513    subtract_optional_penalty(&mut score, penalties.prop_drilling);
514
515    round1(score).clamp(0.0, 100.0)
516}
517
518/// Small capped penalty for prop-drilling chains, sized like the coupling
519/// penalty (~5pt cap). Each located chain costs 1pt up to the cap; a deeper
520/// chain does not cost more (depth is descriptive, not a tunable threshold).
521/// `None` (no penalty) unless the opt-in `prop-drilling` rule populated the
522/// count, so the score is unchanged by default.
523fn prop_drilling_penalty(vs: &VitalSigns) -> Option<f64> {
524    vs.prop_drilling_chain_count
525        .map(|count| round1((f64::from(count) * 1.0).min(5.0)))
526}
527
528fn round1(value: f64) -> f64 {
529    (value * 10.0).round() / 10.0
530}
531
532fn subtract_optional_penalty(score: &mut f64, penalty: Option<f64>) {
533    if let Some(penalty) = penalty {
534        *score -= penalty;
535    }
536}
537
538fn complexity_penalty(vs: &VitalSigns) -> f64 {
539    if let Some(critical_pct) = vs.critical_complexity_pct {
540        round1((critical_pct * 4.0).min(20.0))
541    } else {
542        round1(((vs.avg_cyclomatic - 1.5).max(0.0) * 5.0).min(20.0))
543    }
544}
545
546fn p90_complexity_penalty(vs: &VitalSigns) -> f64 {
547    if vs.critical_complexity_pct.is_some() {
548        0.0
549    } else {
550        round1((f64::from(vs.p90_cyclomatic) - 10.0).clamp(0.0, 10.0))
551    }
552}
553
554fn maintainability_penalty(vs: &VitalSigns) -> Option<f64> {
555    if let Some(low_pct) = vs.maintainability_low_pct {
556        Some(round1((low_pct * 1.5).min(15.0)))
557    } else {
558        vs.maintainability_avg
559            .map(|mi| round1(((70.0 - mi).max(0.0) * 0.5).min(15.0)))
560    }
561}
562
563fn hotspot_penalty(vs: &VitalSigns, total_files: usize) -> Option<f64> {
564    vs.hotspot_count.map(|count| {
565        if total_files == 0 {
566            return 0.0;
567        }
568        let top_pct_bucket = (total_files as f64 * HOTSPOT_TOP_FILE_FRACTION)
569            .ceil()
570            .max(1.0);
571        round1((f64::from(count) / top_pct_bucket * HOTSPOT_MAX_PENALTY).min(HOTSPOT_MAX_PENALTY))
572    })
573}
574
575fn dependency_count_penalty(
576    per_k: Option<f64>,
577    count: Option<u32>,
578    per_k_cap: f64,
579    count_cap: f64,
580) -> Option<f64> {
581    if let Some(per_k) = per_k {
582        Some(round1((per_k * 0.5).min(per_k_cap)))
583    } else {
584        count.map(|count| round1(f64::from(count).min(count_cap)))
585    }
586}
587
588fn unit_size_penalty(vs: &VitalSigns) -> Option<f64> {
589    if let Some(per_k) = vs.functions_over_60_loc_per_k {
590        Some(round1((per_k * 0.5).min(10.0)))
591    } else {
592        vs.unit_size_profile
593            .as_ref()
594            .map(|profile| round1(((profile.very_high_risk - 5.0).max(0.0) * 0.5).min(10.0)))
595    }
596}
597
598fn coupling_penalty(vs: &VitalSigns) -> Option<f64> {
599    if let Some(high_pct) = vs.coupling_high_pct {
600        Some(round1((high_pct * 0.5).min(5.0)))
601    } else {
602        vs.p95_fan_in
603            .map(|p95| round1(((f64::from(p95) - 30.0).max(0.0) * 0.25).min(5.0)))
604    }
605}
606
607/// Build the raw counts for a snapshot.
608pub(crate) fn build_counts(input: &VitalSignsInput<'_>) -> VitalSignsCounts {
609    let (total_exports, dead_files, dead_exports, total_deps) = input
610        .analysis_counts
611        .as_ref()
612        .map_or((0, 0, 0, 0), |counts| {
613            (
614                counts.total_exports,
615                counts.dead_files,
616                counts.dead_exports,
617                counts.total_deps,
618            )
619        });
620
621    let total_lines: usize = input.selected_modules().map(|m| m.line_offsets.len()).sum();
622
623    VitalSignsCounts {
624        total_files: input.total_files,
625        total_exports,
626        dead_files,
627        dead_exports,
628        duplicated_lines: None,
629        total_lines: Some(total_lines),
630        files_scored: input.file_scores.map(<[_]>::len),
631        total_deps,
632    }
633}
634
635/// Get the current git branch name.
636fn git_branch(root: &Path) -> Option<String> {
637    let mut command = crate::git_env::git_command(root);
638    command.args(["rev-parse", "--abbrev-ref", "HEAD"]);
639    command
640        .output()
641        .ok()
642        .filter(|o| o.status.success())
643        .and_then(|o| {
644            let name = String::from_utf8_lossy(&o.stdout).trim().to_string();
645            if name == "HEAD" { None } else { Some(name) }
646        })
647}
648
649/// Build a snapshot from vital signs and input data.
650#[expect(
651    clippy::too_many_arguments,
652    reason = "snapshot construction keeps every persisted compatibility input explicit"
653)]
654pub(crate) fn build_snapshot(
655    vital_signs: VitalSigns,
656    counts: VitalSignsCounts,
657    root: &Path,
658    shallow_clone: bool,
659    health_score: Option<&HealthScore>,
660    coverage_model: Option<fallow_output::CoverageModel>,
661    analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
662) -> VitalSignsSnapshot {
663    let now = chrono_timestamp();
664
665    VitalSignsSnapshot {
666        snapshot_schema_version: SNAPSHOT_SCHEMA_VERSION,
667        version: env!("CARGO_PKG_VERSION").to_string(),
668        timestamp: now,
669        git_sha: crate::repo_refs::short_head_sha(root),
670        git_branch: git_branch(root),
671        shallow_clone,
672        vital_signs,
673        counts,
674        score: health_score.map(|s| s.score),
675        grade: health_score.map(|s| s.grade.to_string()),
676        score_formula_version: health_score.map(|s| s.formula_version),
677        coverage_model,
678        analysis_identity,
679        groups: None,
680    }
681}
682
683/// Save a snapshot to disk.
684///
685/// If `path` is `None`, writes to `.fallow/snapshots/{timestamp}.json`, with a
686/// numeric suffix when a snapshot of the same second exists.
687/// Creates parent directories as needed.
688pub(crate) fn save_snapshot(
689    snapshot: &VitalSignsSnapshot,
690    root: &Path,
691    explicit_path: Option<&Path>,
692) -> Result<PathBuf, String> {
693    let path = if let Some(path) = explicit_path {
694        path.to_path_buf()
695    } else {
696        let path = free_snapshot_path(
697            &root.join(".fallow").join("snapshots"),
698            &snapshot.timestamp.replace(':', "-"),
699        );
700        fallow_types::path_guard::ensure_no_outside_link(root, &path)
701            .map_err(|e| format!("failed to write snapshot: {e}"))?;
702        path
703    };
704    let json =
705        serde_json::to_string_pretty(snapshot).map_err(|e| format!("failed to serialize: {e}"))?;
706    crate::write_guard::write_file(
707        &path,
708        json.as_bytes(),
709        crate::write_guard::WriteTarget::Path,
710    )
711    .map_err(|e| {
712        if e.is_directory() {
713            format!("failed to create snapshot directory: {e}")
714        } else {
715            format!("failed to write snapshot: {e}")
716        }
717    })?;
718
719    Ok(path)
720}
721
722/// Load all snapshots from the default snapshot directory, sorted by timestamp ascending.
723///
724/// Corrupt or unreadable files are skipped with a warning to stderr.
725/// Returns an empty vec if the directory does not exist.
726#[cfg(test)]
727fn load_snapshots(root: &Path) -> Vec<VitalSignsSnapshot> {
728    load_snapshots_with_paths(root)
729        .into_iter()
730        .map(|(_, snapshot)| snapshot)
731        .collect()
732}
733
734/// Load all snapshots from the default snapshot directory with their file
735/// paths, sorted by timestamp ascending. Corrupt or unreadable files are
736/// skipped with a warning to stderr.
737#[expect(
738    clippy::print_stderr,
739    reason = "corrupt-snapshot warnings to stderr, preserved verbatim from the CLI health path"
740)]
741fn load_snapshots_with_paths(root: &Path) -> Vec<(PathBuf, VitalSignsSnapshot)> {
742    let dir = root.join(".fallow").join("snapshots");
743    let Ok(entries) = crate::saved_file::read_saved_dir(root, &dir) else {
744        return Vec::new();
745    };
746    let mut snapshots = Vec::new();
747    for entry in entries {
748        let Ok(entry) = entry else { continue };
749        let path = entry.path();
750        if path.extension().is_some_and(|ext| ext == "json") {
751            match crate::saved_file::read_saved_file(root, &path) {
752                Ok(content) => match serde_json::from_str::<VitalSignsSnapshot>(&content) {
753                    Ok(snap) => snapshots.push((path, snap)),
754                    Err(error) => {
755                        let e = crate::saved_file::json_error_position(&error);
756                        eprintln!("warning: skipping corrupt snapshot {}: {e}", path.display());
757                        record_unreadable_snapshot(root, &path, &e);
758                    }
759                },
760                Err(e) => {
761                    eprintln!("warning: could not read snapshot {}: {e}", path.display());
762                    record_unreadable_snapshot(root, &path, &e.to_string());
763                }
764            }
765        }
766    }
767
768    snapshots.sort_by(|a, b| {
769        a.1.timestamp
770            .cmp(&b.1.timestamp)
771            .then_with(|| save_order(&a.0).cmp(&save_order(&b.0)))
772            .then_with(|| a.0.cmp(&b.0))
773    });
774    snapshots
775}
776
777/// The snapshot a trend compares against, with where it came from.
778#[derive(Debug, Clone)]
779pub(crate) struct TrendBaseline {
780    /// The baseline snapshot.
781    pub(crate) snapshot: VitalSignsSnapshot,
782    /// The file the snapshot was read from.
783    pub(crate) path: PathBuf,
784    /// Number of snapshots the trend source held: the snapshot directory
785    /// count, or `1` for an explicit `--trend-from` file.
786    pub(crate) snapshots_loaded: usize,
787}
788
789impl TrendBaseline {
790    /// The baseline snapshot without its group data.
791    ///
792    /// Each group trend copies this snapshot, so the group data is removed
793    /// once here and not copied again for every group.
794    pub(crate) fn without_groups(&self) -> VitalSignsSnapshot {
795        let mut snapshot = self.snapshot.clone();
796        snapshot.groups = None;
797        snapshot
798    }
799}
800
801/// Load the trend baseline for the project trend and the group trend.
802///
803/// With `explicit`, read exactly that file. It must exist and parse, because
804/// the user named it. Without it, use the newest snapshot of
805/// `.fallow/snapshots/`, and return `Ok(None)` when there is none.
806///
807/// # Errors
808///
809/// Returns a message when the explicit file cannot be read or parsed.
810pub(crate) fn load_trend_baseline(
811    root: &Path,
812    explicit: Option<&Path>,
813) -> Result<Option<TrendBaseline>, String> {
814    if let Some(path) = explicit {
815        let content = crate::saved_file::read_saved_file(root, path).map_err(|e| {
816            format!(
817                "failed to read --trend-from snapshot {}: {e}",
818                path.display()
819            )
820        })?;
821        // Report only the position. The serde message can quote values from
822        // the file, and MCP `trend_from` returns this text to the caller.
823        let snapshot = serde_json::from_str::<VitalSignsSnapshot>(&content).map_err(|e| {
824            format!(
825                "--trend-from file {} is not a fallow health snapshot (parse error at line {}, column {})",
826                path.display(),
827                e.line(),
828                e.column()
829            )
830        })?;
831        return Ok(Some(TrendBaseline {
832            snapshot,
833            path: path.to_path_buf(),
834            snapshots_loaded: 1,
835        }));
836    }
837    let mut snapshots = load_snapshots_with_paths(root);
838    let snapshots_loaded = snapshots.len();
839    Ok(snapshots.pop().map(|(path, snapshot)| TrendBaseline {
840        snapshot,
841        path,
842        snapshots_loaded,
843    }))
844}
845
846/// Record a snapshot this run could not use, so the thinner trend is visible to
847/// a consumer that never sees the warning above (issue #2689).
848fn record_unreadable_snapshot(root: &Path, path: &Path, error: &str) {
849    crate::health::diagnostics::record_health_diagnostic(
850        root,
851        Some(path),
852        fallow_types::workspace::WorkspaceDiagnosticKind::TrendSnapshotUnreadable {
853            error: error.to_owned(),
854        },
855    );
856}
857
858/// Tolerance for treating a metric delta as "stable" rather than improving/declining.
859const TREND_TOLERANCE: f64 = 0.5;
860
861fn trend_point_from_snapshot(prev: &VitalSignsSnapshot) -> TrendPoint {
862    TrendPoint {
863        timestamp: prev.timestamp.clone(),
864        git_sha: prev.git_sha.clone(),
865        score: prev.score,
866        grade: prev.grade.clone(),
867        score_formula_version: prev.score_formula_version,
868        coverage_model: prev.coverage_model.clone(),
869        snapshot_schema_version: Some(prev.snapshot_schema_version),
870    }
871}
872
873fn overall_trend_direction(metrics: &[TrendMetric]) -> TrendDirection {
874    let (improving, declining) = metrics.iter().fold((0usize, 0usize), |(imp, dec), metric| {
875        match metric.direction {
876            TrendDirection::Improving => (imp + 1, dec),
877            TrendDirection::Declining => (imp, dec + 1),
878            TrendDirection::Stable => (imp, dec),
879        }
880    });
881
882    match improving.cmp(&declining) {
883        std::cmp::Ordering::Greater => TrendDirection::Improving,
884        std::cmp::Ordering::Less => TrendDirection::Declining,
885        std::cmp::Ordering::Equal => TrendDirection::Stable,
886    }
887}
888
889/// Compute a trend comparison between the current run and the most recent snapshot.
890///
891/// Uses the stored `score` field from the snapshot (never re-derives it).
892/// Returns `None` if no snapshots are available.
893#[cfg(test)]
894pub(crate) fn compute_trend(
895    current_vs: &VitalSigns,
896    current_counts: &VitalSignsCounts,
897    current_score: Option<f64>,
898    snapshots: &[VitalSignsSnapshot],
899) -> Option<HealthTrend> {
900    let prev = snapshots.last()?;
901    let current_score = current_score.map(|score| HealthScore {
902        score,
903        ..compute_health_score(current_vs, current_counts.total_files)
904    });
905    Some(compute_trend_against(
906        prev,
907        snapshots.len(),
908        current_vs,
909        current_counts,
910        current_score.as_ref(),
911    ))
912}
913
914/// Compare the current metrics against one baseline snapshot.
915///
916/// Uses the stored `score` of the snapshot (never re-derives it).
917pub(crate) fn compute_trend_against(
918    prev: &VitalSignsSnapshot,
919    snapshots_loaded: usize,
920    current_vs: &VitalSigns,
921    current_counts: &VitalSignsCounts,
922    current_score: Option<&HealthScore>,
923) -> HealthTrend {
924    let compared_to = trend_point_from_snapshot(prev);
925
926    let metrics = TrendBuilder::new(prev, current_vs, current_counts, current_score).build();
927
928    let overall_direction = overall_trend_direction(&metrics);
929
930    HealthTrend {
931        compared_to,
932        metrics,
933        snapshots_loaded,
934        overall_direction,
935    }
936}
937
938/// Compare the current metrics of one group against the same group in the
939/// baseline snapshot.
940///
941/// `compared_to` names the baseline snapshot (timestamp, commit), with the
942/// stored score and grade of the group. `base` is the baseline snapshot
943/// without its `groups`, built once for all groups by
944/// [`TrendBaseline::without_groups`].
945pub(crate) fn compute_group_trend(
946    base: &VitalSignsSnapshot,
947    snapshots_loaded: usize,
948    previous: &fallow_output::GroupSnapshot,
949    current_vs: &VitalSigns,
950    current_counts: &VitalSignsCounts,
951    current_score: Option<&HealthScore>,
952) -> HealthTrend {
953    let prev = VitalSignsSnapshot {
954        vital_signs: previous.vital_signs.clone(),
955        counts: previous.counts.clone(),
956        score: previous.score,
957        grade: previous.grade.clone(),
958        ..base.clone()
959    };
960    compute_trend_against(
961        &prev,
962        snapshots_loaded,
963        current_vs,
964        current_counts,
965        current_score,
966    )
967}
968
969struct TrendBuilder<'a> {
970    prev: &'a VitalSignsSnapshot,
971    current_vs: &'a VitalSigns,
972    current_counts: &'a VitalSignsCounts,
973    current_score: Option<&'a HealthScore>,
974    metrics: Vec<TrendMetric>,
975}
976
977impl TrendBuilder<'_> {
978    fn new<'a>(
979        prev: &'a VitalSignsSnapshot,
980        current_vs: &'a VitalSigns,
981        current_counts: &'a VitalSignsCounts,
982        current_score: Option<&'a HealthScore>,
983    ) -> TrendBuilder<'a> {
984        TrendBuilder {
985            prev,
986            current_vs,
987            current_counts,
988            current_score,
989            metrics: Vec::new(),
990        }
991    }
992
993    fn build(mut self) -> Vec<TrendMetric> {
994        self.add_score_metric();
995        self.add_dead_code_metrics();
996        self.add_complexity_metrics();
997        self.add_dependency_metrics();
998        self.add_structure_metrics();
999        self.metrics
1000    }
1001
1002    fn push(&mut self, input: TrendMetricInput) {
1003        self.metrics.push(make_metric(input));
1004    }
1005
1006    fn add_score_metric(&mut self) {
1007        let Some(current) = self.current_score else {
1008            return;
1009        };
1010        if self.prev.score_formula_version != Some(current.formula_version) {
1011            return;
1012        }
1013        if let Some(prev_score) = self.prev.score {
1014            self.push(TrendMetricInput {
1015                name: "score",
1016                label: "Health Score",
1017                previous: prev_score,
1018                current: current.score,
1019                unit: "",
1020                higher_is_better: true,
1021                previous_count: None,
1022                current_count: None,
1023            });
1024        }
1025    }
1026
1027    fn add_dead_code_metrics(&mut self) {
1028        if let (Some(prev_val), Some(cur_val)) = (
1029            self.prev.vital_signs.dead_file_pct,
1030            self.current_vs.dead_file_pct,
1031        ) {
1032            self.push(TrendMetricInput {
1033                name: "dead_file_pct",
1034                label: "Dead Files",
1035                previous: prev_val,
1036                current: cur_val,
1037                unit: "%",
1038                higher_is_better: false,
1039                previous_count: Some(TrendCount {
1040                    value: self.prev.counts.dead_files,
1041                    total: self.prev.counts.total_files,
1042                }),
1043                current_count: Some(TrendCount {
1044                    value: self.current_counts.dead_files,
1045                    total: self.current_counts.total_files,
1046                }),
1047            });
1048        }
1049
1050        if let (Some(prev_val), Some(cur_val)) = (
1051            self.prev.vital_signs.dead_export_pct,
1052            self.current_vs.dead_export_pct,
1053        ) {
1054            self.push(TrendMetricInput {
1055                name: "dead_export_pct",
1056                label: "Dead Exports",
1057                previous: prev_val,
1058                current: cur_val,
1059                unit: "%",
1060                higher_is_better: false,
1061                previous_count: Some(TrendCount {
1062                    value: self.prev.counts.dead_exports,
1063                    total: self.prev.counts.total_exports,
1064                }),
1065                current_count: Some(TrendCount {
1066                    value: self.current_counts.dead_exports,
1067                    total: self.current_counts.total_exports,
1068                }),
1069            });
1070        }
1071    }
1072
1073    fn add_complexity_metrics(&mut self) {
1074        self.push(TrendMetricInput {
1075            name: "avg_cyclomatic",
1076            label: "Avg Cyclomatic",
1077            previous: self.prev.vital_signs.avg_cyclomatic,
1078            current: self.current_vs.avg_cyclomatic,
1079            unit: "",
1080            higher_is_better: false,
1081            previous_count: None,
1082            current_count: None,
1083        });
1084
1085        if let (Some(prev_val), Some(cur_val)) = (
1086            self.prev.vital_signs.maintainability_avg,
1087            self.current_vs.maintainability_avg,
1088        ) {
1089            self.push(TrendMetricInput {
1090                name: "maintainability_avg",
1091                label: "Maintainability",
1092                previous: prev_val,
1093                current: cur_val,
1094                unit: "",
1095                higher_is_better: true,
1096                previous_count: None,
1097                current_count: None,
1098            });
1099        }
1100
1101        if let (Some(prev_profile), Some(cur_profile)) = (
1102            &self.prev.vital_signs.unit_size_profile,
1103            &self.current_vs.unit_size_profile,
1104        ) {
1105            self.push(TrendMetricInput {
1106                name: "unit_size_very_high_pct",
1107                label: "Oversized Fns",
1108                previous: prev_profile.very_high_risk,
1109                current: cur_profile.very_high_risk,
1110                unit: "%",
1111                higher_is_better: false,
1112                previous_count: None,
1113                current_count: None,
1114            });
1115        }
1116
1117        self.add_duplication_metric();
1118    }
1119
1120    fn add_duplication_metric(&mut self) {
1121        if let (Some(prev_val), Some(cur_val)) = (
1122            self.prev.vital_signs.duplication_pct,
1123            self.current_vs.duplication_pct,
1124        ) {
1125            self.push(TrendMetricInput {
1126                name: "duplication_pct",
1127                label: "Duplication",
1128                previous: prev_val,
1129                current: cur_val,
1130                unit: "%",
1131                higher_is_better: false,
1132                previous_count: self
1133                    .prev
1134                    .counts
1135                    .duplicated_lines
1136                    .zip(self.prev.counts.total_lines)
1137                    .map(|(d, t)| TrendCount { value: d, total: t }),
1138                current_count: self
1139                    .current_counts
1140                    .duplicated_lines
1141                    .zip(self.current_counts.total_lines)
1142                    .map(|(d, t)| TrendCount { value: d, total: t }),
1143            });
1144        }
1145    }
1146
1147    fn add_dependency_metrics(&mut self) {
1148        if let (Some(prev_val), Some(cur_val)) = (
1149            self.prev.vital_signs.unused_dep_count,
1150            self.current_vs.unused_dep_count,
1151        ) {
1152            self.push(TrendMetricInput {
1153                name: "unused_dep_count",
1154                label: "Unused Deps",
1155                previous: f64::from(prev_val),
1156                current: f64::from(cur_val),
1157                unit: "",
1158                higher_is_better: false,
1159                previous_count: None,
1160                current_count: None,
1161            });
1162        }
1163    }
1164
1165    fn add_structure_metrics(&mut self) {
1166        if let (Some(prev_val), Some(cur_val)) = (
1167            self.prev.vital_signs.circular_dep_count,
1168            self.current_vs.circular_dep_count,
1169        ) {
1170            self.push(TrendMetricInput {
1171                name: "circular_dep_count",
1172                label: "Circular Deps",
1173                previous: f64::from(prev_val),
1174                current: f64::from(cur_val),
1175                unit: "",
1176                higher_is_better: false,
1177                previous_count: None,
1178                current_count: None,
1179            });
1180        }
1181
1182        if let (Some(prev_val), Some(cur_val)) = (
1183            self.prev.vital_signs.hotspot_count,
1184            self.current_vs.hotspot_count,
1185        ) {
1186            self.push(TrendMetricInput {
1187                name: "hotspot_count",
1188                label: "Hotspots",
1189                previous: f64::from(prev_val),
1190                current: f64::from(cur_val),
1191                unit: "",
1192                higher_is_better: false,
1193                previous_count: None,
1194                current_count: None,
1195            });
1196        }
1197
1198        if let (Some(prev_val), Some(cur_val)) =
1199            (self.prev.vital_signs.p95_fan_in, self.current_vs.p95_fan_in)
1200        {
1201            self.push(TrendMetricInput {
1202                name: "p95_fan_in",
1203                label: "P95 Fan-in",
1204                previous: f64::from(prev_val),
1205                current: f64::from(cur_val),
1206                unit: "",
1207                higher_is_better: false,
1208                previous_count: None,
1209                current_count: None,
1210            });
1211        }
1212    }
1213}
1214
1215/// Build a single trend metric.
1216struct TrendMetricInput {
1217    name: &'static str,
1218    label: &'static str,
1219    previous: f64,
1220    current: f64,
1221    unit: &'static str,
1222    higher_is_better: bool,
1223    previous_count: Option<TrendCount>,
1224    current_count: Option<TrendCount>,
1225}
1226
1227fn make_metric(input: TrendMetricInput) -> TrendMetric {
1228    let TrendMetricInput {
1229        name,
1230        label,
1231        previous,
1232        current,
1233        unit,
1234        higher_is_better,
1235        previous_count,
1236        current_count,
1237    } = input;
1238    let delta = (current - previous).round_to(1);
1239    let direction = if delta.abs() < TREND_TOLERANCE {
1240        TrendDirection::Stable
1241    } else if (higher_is_better && delta > 0.0) || (!higher_is_better && delta < 0.0) {
1242        TrendDirection::Improving
1243    } else {
1244        TrendDirection::Declining
1245    };
1246
1247    TrendMetric {
1248        name,
1249        label,
1250        previous,
1251        current,
1252        delta,
1253        direction,
1254        unit,
1255        previous_count,
1256        current_count,
1257    }
1258}
1259
1260/// Extension trait for rounding floats to N decimal places.
1261trait RoundTo {
1262    fn round_to(self, decimals: u32) -> Self;
1263}
1264
1265impl RoundTo for f64 {
1266    fn round_to(self, decimals: u32) -> Self {
1267        let factor = 10_f64.powi(i32::try_from(decimals).unwrap_or(i32::MAX));
1268        (self * factor).round() / factor
1269    }
1270}
1271
1272#[path = "vital_signs_snapshot_names.rs"]
1273mod snapshot_names;
1274pub use snapshot_names::chrono_timestamp;
1275#[cfg(test)]
1276use snapshot_names::days_to_ymd;
1277use snapshot_names::{free_snapshot_path, save_order};
1278
1279#[cfg(test)]
1280#[path = "vital_signs_snapshot_tests.rs"]
1281mod snapshot_tests;
1282
1283#[cfg(test)]
1284mod tests {
1285    use super::*;
1286
1287    fn make_module(id: u32, cyclomatic: u16) -> crate::source::ModuleInfo {
1288        crate::source::ModuleInfo {
1289            complexity: vec![fallow_types::extract::FunctionComplexity {
1290                name: format!("fn_{id}"),
1291                is_private_member: false,
1292                context_named: None,
1293                line: id + 1,
1294                col: 0,
1295                cyclomatic,
1296                cognitive: 0,
1297                line_count: 10,
1298                param_count: 0,
1299                react_hook_count: 0,
1300                react_jsx_max_depth: 0,
1301                react_prop_count: 0,
1302                source_hash: None,
1303                contributions: Vec::new(),
1304            }],
1305            ..crate::source::ModuleInfo::empty(crate::discover::FileId(id))
1306        }
1307    }
1308
1309    #[expect(
1310        clippy::cast_possible_truncation,
1311        reason = "test values are trivially small"
1312    )]
1313    fn make_modules() -> Vec<crate::source::ModuleInfo> {
1314        (0..10)
1315            .map(|i| make_module(i, (i as u16 + 1) * 2))
1316            .collect()
1317    }
1318
1319    fn assert_close(actual: f64, expected: f64) {
1320        assert!(
1321            (actual - expected).abs() < f64::EPSILON,
1322            "expected {expected}, got {actual}"
1323        );
1324    }
1325
1326    fn assert_some_close(actual: Option<f64>, expected: f64) {
1327        assert_close(actual.expect("expected metric to be present"), expected);
1328    }
1329
1330    #[test]
1331    fn compute_cyclomatic_stats() {
1332        let modules = make_modules();
1333        let input = VitalSignsInput {
1334            modules: &modules,
1335            module_filter: None,
1336            file_scores: None,
1337            hotspots: None,
1338            total_files: 10,
1339            analysis_counts: None,
1340        };
1341        let vs = compute_vital_signs(&input);
1342        assert!((vs.avg_cyclomatic - 11.0).abs() < f64::EPSILON);
1343        assert_eq!(vs.p90_cyclomatic, 18);
1344    }
1345
1346    #[test]
1347    fn cyclomatic_population_partitions_units_and_respects_module_filter() {
1348        let mut mixed = make_module(0, 1);
1349        let mut module_unit = mixed.complexity[0].clone();
1350        module_unit.name = "<module>".into();
1351        module_unit.cyclomatic = 31;
1352        let mut template_unit = module_unit.clone();
1353        template_unit.name = "<template>".into();
1354        template_unit.cyclomatic = 4;
1355        mixed.complexity.extend([module_unit, template_unit]);
1356        let modules = [mixed, make_module(1, 100)];
1357        let filter = rustc_hash::FxHashSet::from_iter([crate::discover::FileId(0)]);
1358        let input = VitalSignsInput {
1359            modules: &modules,
1360            module_filter: Some(&filter),
1361            file_scores: None,
1362            hotspots: None,
1363            total_files: 1,
1364            analysis_counts: None,
1365        };
1366        let vs = compute_vital_signs(&input);
1367        let population = vs.cyclomatic_population.unwrap();
1368        assert_eq!(population.functions.count, 1);
1369        assert_eq!(population.modules.count, 1);
1370        assert_eq!(population.templates.count, 1);
1371        assert_eq!(population.functions.sum, 1);
1372        assert_eq!(population.modules.sum, 31);
1373        assert_eq!(population.templates.sum, 4);
1374        assert_close(vs.avg_cyclomatic, 12.0);
1375        assert_eq!(vs.p90_cyclomatic, 31);
1376    }
1377
1378    #[test]
1379    fn compute_with_analysis_counts() {
1380        let modules = make_modules();
1381        let input = VitalSignsInput {
1382            modules: &modules,
1383            module_filter: None,
1384            file_scores: None,
1385            hotspots: None,
1386            total_files: 100,
1387            analysis_counts: Some(AnalysisCounts {
1388                total_exports: 500,
1389                dead_files: 5,
1390                dead_exports: 50,
1391                unused_deps: 3,
1392                circular_deps: 2,
1393                total_deps: 40,
1394            }),
1395        };
1396        let vs = compute_vital_signs(&input);
1397        assert_eq!(vs.dead_file_pct, Some(5.0)); // 5/100 * 100
1398        assert_eq!(vs.dead_export_pct, Some(10.0)); // 50/500 * 100
1399        assert_eq!(vs.unused_dep_count, Some(3));
1400        assert_eq!(vs.circular_dep_count, Some(2));
1401    }
1402
1403    #[test]
1404    fn compute_hotspot_count_with_threshold() {
1405        let hotspots = vec![
1406            HotspotEntry {
1407                path: PathBuf::from("a.ts"),
1408                score: 80.0,
1409                commits: 10,
1410                weighted_commits: 8.0,
1411                lines_added: 100,
1412                lines_deleted: 50,
1413                complexity_density: 0.5,
1414                fan_in: 5,
1415                trend: crate::churn::ChurnTrend::Stable,
1416                median_files_per_commit: None,
1417                median_lines_per_commit: None,
1418                ownership: None,
1419                is_test_path: false,
1420            },
1421            HotspotEntry {
1422                path: PathBuf::from("b.ts"),
1423                score: 30.0, // Below threshold
1424                commits: 5,
1425                weighted_commits: 3.0,
1426                lines_added: 40,
1427                lines_deleted: 20,
1428                complexity_density: 0.2,
1429                fan_in: 2,
1430                trend: crate::churn::ChurnTrend::Cooling,
1431                median_files_per_commit: None,
1432                median_lines_per_commit: None,
1433                ownership: None,
1434                is_test_path: false,
1435            },
1436            HotspotEntry {
1437                path: PathBuf::from("c.ts"),
1438                score: 50.0, // At threshold
1439                commits: 8,
1440                weighted_commits: 6.0,
1441                lines_added: 80,
1442                lines_deleted: 30,
1443                complexity_density: 0.4,
1444                fan_in: 3,
1445                trend: crate::churn::ChurnTrend::Accelerating,
1446                median_files_per_commit: None,
1447                median_lines_per_commit: None,
1448                ownership: None,
1449                is_test_path: false,
1450            },
1451        ];
1452        let modules = Vec::new();
1453        let input = VitalSignsInput {
1454            modules: &modules,
1455            module_filter: None,
1456            file_scores: None,
1457            hotspots: Some(&hotspots),
1458            total_files: 10,
1459            analysis_counts: None,
1460        };
1461        let vs = compute_vital_signs(&input);
1462        assert_eq!(vs.hotspot_count, Some(2)); // 80.0 and 50.0 meet threshold
1463        assert_eq!(vs.hotspot_top_pct_count, Some(1)); // top 1% bucket rounds up to one file
1464    }
1465
1466    #[test]
1467    fn hotspot_penalty_ignores_subthreshold_ranked_entries() {
1468        let hotspots: Vec<HotspotEntry> = [49.9, 0.1]
1469            .into_iter()
1470            .enumerate()
1471            .map(|(index, score)| HotspotEntry {
1472                path: PathBuf::from(format!("src/active-{index}.ts")),
1473                score,
1474                commits: 3,
1475                weighted_commits: 3.0,
1476                lines_added: 10,
1477                lines_deleted: 5,
1478                complexity_density: 0.1,
1479                fan_in: 0,
1480                trend: crate::churn::ChurnTrend::Stable,
1481                median_files_per_commit: None,
1482                median_lines_per_commit: None,
1483                ownership: None,
1484                is_test_path: false,
1485            })
1486            .collect();
1487        let input = VitalSignsInput {
1488            modules: &[],
1489            module_filter: None,
1490            file_scores: None,
1491            hotspots: Some(&hotspots),
1492            total_files: 200,
1493            analysis_counts: None,
1494        };
1495
1496        let vitals = compute_vital_signs(&input);
1497        let health = compute_health_score(&vitals, input.total_files);
1498
1499        assert_eq!(vitals.hotspot_count, Some(0));
1500        assert_eq!(vitals.hotspot_top_pct_count, Some(2));
1501        assert_some_close(health.penalties.hotspots, 0.0);
1502    }
1503
1504    #[test]
1505    fn empty_cyclomatic_population_is_measured_not_unknown() {
1506        let vs = compute_vital_signs(&VitalSignsInput {
1507            modules: &[],
1508            module_filter: None,
1509            file_scores: None,
1510            hotspots: None,
1511            total_files: 0,
1512            analysis_counts: None,
1513        });
1514        let population = vs.cyclomatic_population.unwrap();
1515        for group in [
1516            population.functions,
1517            population.modules,
1518            population.templates,
1519        ] {
1520            assert_eq!(group.count, 0);
1521            assert_eq!(group.sum, 0);
1522            assert_eq!(group.max, None);
1523        }
1524        assert_close(vs.avg_cyclomatic, 0.0);
1525        assert_eq!(vs.p90_cyclomatic, 0);
1526        assert_eq!(vs.critical_complexity_pct, None);
1527    }
1528
1529    #[test]
1530    fn compute_without_hotspots_gives_none() {
1531        let modules = Vec::new();
1532        let input = VitalSignsInput {
1533            modules: &modules,
1534            module_filter: None,
1535            file_scores: None,
1536            hotspots: None,
1537            total_files: 0,
1538            analysis_counts: None,
1539        };
1540        let vs = compute_vital_signs(&input);
1541        assert!(vs.hotspot_count.is_none());
1542    }
1543
1544    #[test]
1545    fn snapshot_save_and_load() {
1546        let dir = tempfile::tempdir().unwrap();
1547        let root = dir.path();
1548        let vs = VitalSigns {
1549            dead_file_pct: Some(3.2),
1550            dead_export_pct: Some(8.1),
1551            avg_cyclomatic: 4.7,
1552            p90_cyclomatic: 12,
1553            hotspot_count: Some(5),
1554            maintainability_avg: Some(72.4),
1555            unused_dep_count: Some(4),
1556            circular_dep_count: Some(2),
1557            ..Default::default()
1558        };
1559        let counts = VitalSignsCounts {
1560            total_files: 1200,
1561            total_exports: 5400,
1562            dead_files: 38,
1563            dead_exports: 437,
1564            files_scored: Some(1150),
1565            total_deps: 42,
1566            ..Default::default()
1567        };
1568        let health_score = compute_health_score(&vs, 1200);
1569        let snapshot = build_snapshot(
1570            vs,
1571            counts,
1572            root,
1573            false,
1574            Some(&health_score),
1575            None,
1576            fallow_types::semantic::SemanticAnalysisIdentity::default(),
1577        );
1578        let saved_path = save_snapshot(&snapshot, root, None).unwrap();
1579
1580        assert!(saved_path.exists());
1581        assert!(saved_path.starts_with(root.join(".fallow/snapshots")));
1582
1583        let content = std::fs::read_to_string(&saved_path).unwrap();
1584        let loaded: VitalSignsSnapshot = serde_json::from_str(&content).unwrap();
1585        assert_eq!(loaded.snapshot_schema_version, SNAPSHOT_SCHEMA_VERSION);
1586        assert!((loaded.vital_signs.avg_cyclomatic - 4.7).abs() < f64::EPSILON);
1587        assert_eq!(loaded.counts.total_files, 1200);
1588        assert!(loaded.score.is_some());
1589        assert!(loaded.grade.is_some());
1590    }
1591
1592    #[test]
1593    fn snapshot_save_explicit_path() {
1594        let dir = tempfile::tempdir().unwrap();
1595        let root = dir.path();
1596        let explicit = root.join("my-snapshot.json");
1597        let vs = VitalSigns {
1598            avg_cyclomatic: 1.0,
1599            p90_cyclomatic: 2,
1600            ..Default::default()
1601        };
1602        let counts = VitalSignsCounts::default();
1603        let snapshot = build_snapshot(
1604            vs,
1605            counts,
1606            root,
1607            false,
1608            None,
1609            None,
1610            fallow_types::semantic::SemanticAnalysisIdentity::default(),
1611        );
1612        let saved = save_snapshot(&snapshot, root, Some(&explicit)).unwrap();
1613        assert_eq!(saved, explicit);
1614        assert!(explicit.exists());
1615    }
1616
1617    #[test]
1618    fn snapshot_save_creates_nested_dirs() {
1619        let dir = tempfile::tempdir().unwrap();
1620        let root = dir.path();
1621        let nested = root.join("a/b/c/snapshot.json");
1622        let vs = VitalSigns {
1623            avg_cyclomatic: 1.0,
1624            p90_cyclomatic: 2,
1625            ..Default::default()
1626        };
1627        let counts = VitalSignsCounts::default();
1628        let snapshot = build_snapshot(
1629            vs,
1630            counts,
1631            root,
1632            false,
1633            None,
1634            None,
1635            fallow_types::semantic::SemanticAnalysisIdentity::default(),
1636        );
1637        let saved = save_snapshot(&snapshot, root, Some(&nested)).unwrap();
1638        assert_eq!(saved, nested);
1639        assert!(nested.exists());
1640    }
1641
1642    #[test]
1643    fn days_to_ymd_epoch() {
1644        assert_eq!(days_to_ymd(0), (1970, 1, 1));
1645    }
1646
1647    #[test]
1648    fn days_to_ymd_known_date() {
1649        assert_eq!(days_to_ymd(20_537), (2026, 3, 25));
1650    }
1651
1652    #[test]
1653    fn health_score_perfect() {
1654        let vs = VitalSigns {
1655            dead_file_pct: Some(0.0),
1656            dead_export_pct: Some(0.0),
1657            avg_cyclomatic: 1.0,
1658            p90_cyclomatic: 2,
1659            hotspot_count: Some(0),
1660            maintainability_avg: Some(90.0),
1661            unused_dep_count: Some(0),
1662            circular_dep_count: Some(0),
1663            ..Default::default()
1664        };
1665        let score = compute_health_score(&vs, 100);
1666        assert!((score.score - 100.0).abs() < f64::EPSILON);
1667        assert_eq!(score.grade, "A");
1668    }
1669
1670    #[test]
1671    fn health_score_no_optional_metrics() {
1672        let vs = VitalSigns {
1673            avg_cyclomatic: 1.0,
1674            p90_cyclomatic: 2,
1675            ..Default::default()
1676        };
1677        let score = compute_health_score(&vs, 0);
1678        assert!((score.score - 100.0).abs() < f64::EPSILON);
1679        assert_eq!(score.grade, "A");
1680        assert!(score.penalties.dead_files.is_none());
1681        assert!(score.penalties.unused_deps.is_none());
1682        assert!(score.penalties.duplication.is_none());
1683    }
1684
1685    #[test]
1686    fn health_score_dead_code_penalty() {
1687        let vs = VitalSigns {
1688            dead_file_pct: Some(50.0),
1689            dead_export_pct: Some(30.0),
1690            avg_cyclomatic: 1.0,
1691            p90_cyclomatic: 2,
1692            ..Default::default()
1693        };
1694        let score = compute_health_score(&vs, 100);
1695        assert!((score.score - 84.0).abs() < 0.1);
1696        assert_eq!(score.grade, "B");
1697    }
1698
1699    #[test]
1700    fn health_score_complexity_penalty() {
1701        let vs = VitalSigns {
1702            avg_cyclomatic: 5.5,
1703            p90_cyclomatic: 15,
1704            ..Default::default()
1705        };
1706        let score = compute_health_score(&vs, 100);
1707        assert!((score.score - 75.0).abs() < 0.1);
1708        assert_eq!(score.grade, "B");
1709    }
1710
1711    #[test]
1712    fn health_score_prop_drilling_penalty_opt_in() {
1713        let base = || VitalSigns {
1714            avg_cyclomatic: 1.0,
1715            p90_cyclomatic: 2,
1716            ..Default::default()
1717        };
1718        let base_score = compute_health_score(&base(), 100).score;
1719
1720        // Each located chain costs 1pt (depth is descriptive, not a multiplier).
1721        let three = VitalSigns {
1722            prop_drilling_chain_count: Some(3),
1723            prop_drilling_max_depth: Some(5),
1724            ..base()
1725        };
1726        assert!((base_score - compute_health_score(&three, 100).score - 3.0).abs() < 0.1);
1727
1728        // Capped at 5pt regardless of chain count.
1729        let many = VitalSigns {
1730            prop_drilling_chain_count: Some(20),
1731            ..base()
1732        };
1733        assert!((base_score - compute_health_score(&many, 100).score - 5.0).abs() < 0.1);
1734
1735        // Dormant by default: the opt-in rule is off, so the count is `None` and
1736        // the score is unchanged.
1737        let off = VitalSigns {
1738            prop_drilling_chain_count: None,
1739            ..base()
1740        };
1741        assert!((base_score - compute_health_score(&off, 100).score).abs() < f64::EPSILON);
1742    }
1743
1744    #[test]
1745    fn health_score_clamped_at_zero() {
1746        let vs = VitalSigns {
1747            dead_file_pct: Some(100.0),
1748            dead_export_pct: Some(100.0),
1749            avg_cyclomatic: 10.0,
1750            p90_cyclomatic: 30,
1751            hotspot_count: Some(50),
1752            maintainability_avg: Some(20.0),
1753            unused_dep_count: Some(100),
1754            circular_dep_count: Some(50),
1755            ..Default::default()
1756        };
1757        let score = compute_health_score(&vs, 100);
1758        assert!((score.score).abs() < f64::EPSILON);
1759        assert_eq!(score.grade, "F");
1760    }
1761
1762    #[test]
1763    fn health_score_hotspot_normalized_by_files() {
1764        let vs = VitalSigns {
1765            avg_cyclomatic: 1.0,
1766            p90_cyclomatic: 2,
1767            hotspot_count: Some(5),
1768            ..Default::default()
1769        };
1770        let score_100 = compute_health_score(&vs, 100);
1771        let score_1000 = compute_health_score(&vs, 1000);
1772        assert!(score_1000.score > score_100.score);
1773    }
1774
1775    #[test]
1776    fn health_score_thresholded_hotspots_can_use_full_budget() {
1777        let vs = VitalSigns {
1778            avg_cyclomatic: 1.0,
1779            p90_cyclomatic: 2,
1780            hotspot_count: Some(250),
1781            hotspot_top_pct_count: Some(250),
1782            ..Default::default()
1783        };
1784
1785        let score = compute_health_score(&vs, 25_000);
1786
1787        assert_some_close(score.penalties.hotspots, 10.0);
1788        assert_close(score.score, 90.0);
1789    }
1790
1791    #[test]
1792    fn health_score_duplication_penalty() {
1793        let vs = VitalSigns {
1794            cyclomatic_population: None,
1795            dead_file_pct: None,
1796            dead_export_pct: None,
1797            avg_cyclomatic: 1.0,
1798            critical_complexity_pct: None,
1799            p90_cyclomatic: 2,
1800            duplication_pct: Some(10.0), // 10% - 5% = 5 points
1801            hotspot_count: None,
1802            hotspot_top_pct_count: None,
1803            maintainability_avg: None,
1804            maintainability_low_pct: None,
1805            unused_dep_count: None,
1806            unused_deps_per_k_files: None,
1807            circular_dep_count: None,
1808            circular_deps_per_k_files: None,
1809            counts: None,
1810            unit_size_profile: None,
1811            functions_over_60_loc_per_k: None,
1812            unit_interfacing_profile: None,
1813            p95_fan_in: None,
1814            coupling_high_pct: None,
1815            prop_drilling_chain_count: None,
1816            prop_drilling_max_depth: None,
1817            p95_render_fan_in: None,
1818            render_fan_in_high_pct: None,
1819            max_render_fan_in: None,
1820            top_render_fan_in: Vec::new(),
1821            total_loc: 0,
1822        };
1823        let score = compute_health_score(&vs, 100);
1824        assert_eq!(score.penalties.duplication, Some(5.0));
1825
1826        let vs_low = VitalSigns {
1827            duplication_pct: Some(4.0),
1828            ..vs.clone()
1829        };
1830        let score_low = compute_health_score(&vs_low, 100);
1831        assert_eq!(score_low.penalties.duplication, Some(0.0));
1832
1833        let vs_high = VitalSigns {
1834            duplication_pct: Some(20.0),
1835            ..vs
1836        };
1837        let score_high = compute_health_score(&vs_high, 100);
1838        assert_eq!(score_high.penalties.duplication, Some(10.0));
1839    }
1840
1841    #[test]
1842    fn health_score_uses_scale_invariant_monorepo_signals() {
1843        let vs = VitalSigns {
1844            dead_file_pct: Some(4.0),
1845            dead_export_pct: Some(9.0),
1846            avg_cyclomatic: 2.3,
1847            critical_complexity_pct: Some(2.3),
1848            p90_cyclomatic: 4,
1849            duplication_pct: Some(6.0),
1850            hotspot_count: Some(250),
1851            hotspot_top_pct_count: Some(250),
1852            maintainability_avg: Some(91.0),
1853            maintainability_low_pct: Some(8.0),
1854            unused_dep_count: Some(180),
1855            unused_deps_per_k_files: Some(7.2),
1856            circular_dep_count: Some(450),
1857            circular_deps_per_k_files: Some(18.0),
1858            unit_size_profile: Some(RiskProfile {
1859                low_risk: 80.0,
1860                medium_risk: 12.7,
1861                high_risk: 5.0,
1862                very_high_risk: 2.3,
1863            }),
1864            functions_over_60_loc_per_k: Some(23.0),
1865            p95_fan_in: Some(7),
1866            coupling_high_pct: Some(4.0),
1867            ..Default::default()
1868        };
1869        let score = compute_health_score(&vs, 25_000);
1870        let penalties = &score.penalties;
1871
1872        assert_some_close(penalties.dead_files, 0.8);
1873        assert_some_close(penalties.dead_exports, 1.8);
1874        assert_close(penalties.complexity, 9.2);
1875        assert!((penalties.p90_complexity).abs() < f64::EPSILON);
1876        assert_some_close(penalties.maintainability, 12.0);
1877        assert_some_close(penalties.hotspots, 10.0);
1878        assert_some_close(penalties.unused_deps, 3.6);
1879        assert_some_close(penalties.circular_deps, 9.0);
1880        assert_some_close(penalties.unit_size, 10.0);
1881        assert_some_close(penalties.coupling, 2.0);
1882        assert_some_close(penalties.duplication, 1.0);
1883        assert_close(score.score, 40.6);
1884        assert_eq!(score.grade, "D");
1885    }
1886
1887    #[test]
1888    fn load_snapshots_empty_dir() {
1889        let dir = tempfile::tempdir().unwrap();
1890        let snaps = load_snapshots(dir.path());
1891        assert!(snaps.is_empty());
1892    }
1893
1894    #[test]
1895    fn load_snapshots_returns_sorted() {
1896        let dir = tempfile::tempdir().unwrap();
1897        let root = dir.path();
1898        let snap_dir = root.join(".fallow/snapshots");
1899        std::fs::create_dir_all(&snap_dir).unwrap();
1900
1901        let older = make_test_snapshot("2026-01-01T00:00:00Z", Some(72.0));
1902        let newer = make_test_snapshot("2026-03-01T00:00:00Z", Some(78.0));
1903
1904        std::fs::write(
1905            snap_dir.join("2026-03-01T00-00-00Z.json"),
1906            serde_json::to_string(&newer).unwrap(),
1907        )
1908        .unwrap();
1909        std::fs::write(
1910            snap_dir.join("2026-01-01T00-00-00Z.json"),
1911            serde_json::to_string(&older).unwrap(),
1912        )
1913        .unwrap();
1914
1915        let loaded = load_snapshots(root);
1916        assert_eq!(loaded.len(), 2);
1917        assert_eq!(loaded[0].timestamp, "2026-01-01T00:00:00Z");
1918        assert_eq!(loaded[1].timestamp, "2026-03-01T00:00:00Z");
1919    }
1920
1921    #[test]
1922    fn load_snapshots_skips_corrupt_files() {
1923        let dir = tempfile::tempdir().unwrap();
1924        let root = dir.path();
1925        let snap_dir = root.join(".fallow/snapshots");
1926        std::fs::create_dir_all(&snap_dir).unwrap();
1927
1928        std::fs::write(snap_dir.join("corrupt.json"), "not valid json").unwrap();
1929        let good = make_test_snapshot("2026-02-01T00:00:00Z", Some(80.0));
1930        std::fs::write(
1931            snap_dir.join("good.json"),
1932            serde_json::to_string(&good).unwrap(),
1933        )
1934        .unwrap();
1935
1936        let loaded = load_snapshots(root);
1937        assert_eq!(loaded.len(), 1);
1938        assert_eq!(loaded[0].timestamp, "2026-02-01T00:00:00Z");
1939    }
1940
1941    #[test]
1942    fn load_snapshots_ignores_non_json() {
1943        let dir = tempfile::tempdir().unwrap();
1944        let root = dir.path();
1945        let snap_dir = root.join(".fallow/snapshots");
1946        std::fs::create_dir_all(&snap_dir).unwrap();
1947
1948        std::fs::write(snap_dir.join("readme.txt"), "not a snapshot").unwrap();
1949
1950        let loaded = load_snapshots(root);
1951        assert!(loaded.is_empty());
1952    }
1953
1954    #[test]
1955    fn hotspot_penalty_respects_score_threshold_and_scoped_population() {
1956        for (scores, total_files, expected) in [
1957            (vec![49.9, 0.1], 563, 0.0),
1958            (vec![50.0, 49.9, 0.1], 563, 1.7),
1959            (vec![50.0; 6], 563, 10.0),
1960            (vec![50.0; 7], 563, 10.0),
1961            (vec![50.0], 1, 10.0),
1962            (vec![50.0], 101, 5.0),
1963            (vec![50.0], 0, 0.0),
1964            (vec![], 563, 0.0),
1965        ] {
1966            let hotspots: Vec<HotspotEntry> = scores
1967                .into_iter()
1968                .enumerate()
1969                .map(|(index, score)| HotspotEntry {
1970                    path: PathBuf::from(format!("src/scoped-{index}.ts")),
1971                    score,
1972                    commits: 3,
1973                    weighted_commits: 3.0,
1974                    lines_added: 10,
1975                    lines_deleted: 5,
1976                    complexity_density: 0.1,
1977                    fan_in: 0,
1978                    trend: crate::churn::ChurnTrend::Stable,
1979                    median_files_per_commit: None,
1980                    median_lines_per_commit: None,
1981                    ownership: None,
1982                    is_test_path: false,
1983                })
1984                .collect();
1985            let input = VitalSignsInput {
1986                modules: &[],
1987                module_filter: None,
1988                file_scores: None,
1989                hotspots: Some(&hotspots),
1990                total_files,
1991                analysis_counts: None,
1992            };
1993            let vitals = compute_vital_signs(&input);
1994            let score = compute_health_score(&vitals, total_files);
1995            assert_some_close(score.penalties.hotspots, expected);
1996            assert_eq!(score.formula_version, HEALTH_SCORE_FORMULA_VERSION);
1997        }
1998    }
1999
2000    #[test]
2001    fn hotspot_penalty_requires_thresholded_measurement_and_ignores_rank_diagnostic() {
2002        let mut vitals = VitalSigns {
2003            hotspot_top_pct_count: Some(6),
2004            ..Default::default()
2005        };
2006        assert!(
2007            compute_health_score(&vitals, 563)
2008                .penalties
2009                .hotspots
2010                .is_none()
2011        );
2012
2013        vitals.hotspot_count = Some(1);
2014        for diagnostic in [None, Some(0), Some(6)] {
2015            vitals.hotspot_top_pct_count = diagnostic;
2016            assert_some_close(compute_health_score(&vitals, 563).penalties.hotspots, 1.7);
2017        }
2018    }
2019
2020    #[test]
2021    fn snapshot_persists_the_computed_score_formula() {
2022        let dir = tempfile::tempdir().unwrap();
2023        let vitals = make_test_vital_signs();
2024        let counts = make_test_counts();
2025        let mut health = compute_health_score(&vitals, counts.total_files);
2026        health.formula_version = HEALTH_SCORE_FORMULA_VERSION + 1;
2027        let snapshot = build_snapshot(
2028            vitals,
2029            counts,
2030            dir.path(),
2031            false,
2032            Some(&health),
2033            None,
2034            fallow_types::semantic::SemanticAnalysisIdentity::default(),
2035        );
2036        assert_eq!(snapshot.score_formula_version, Some(health.formula_version));
2037        assert_eq!(snapshot.score, Some(health.score));
2038        assert_eq!(snapshot.grade.as_deref(), Some(health.grade));
2039
2040        let unscored = build_snapshot(
2041            snapshot.vital_signs,
2042            snapshot.counts,
2043            dir.path(),
2044            false,
2045            None,
2046            None,
2047            fallow_types::semantic::SemanticAnalysisIdentity::default(),
2048        );
2049        assert!(unscored.score_formula_version.is_none());
2050    }
2051
2052    #[test]
2053    fn trend_requires_both_scores_even_with_matching_formula_identity() {
2054        let current_vs = make_test_vital_signs();
2055        let counts = make_test_counts();
2056        let health = compute_health_score(&current_vs, counts.total_files);
2057        for (previous_score, current_score) in [(None, Some(&health)), (Some(72.0), None)] {
2058            let mut previous = make_test_snapshot("2026-01-01T00:00:00Z", previous_score);
2059            previous.score_formula_version = Some(health.formula_version);
2060            let trend = compute_trend_against(&previous, 1, &current_vs, &counts, current_score);
2061            assert!(!trend.metrics.iter().any(|metric| metric.name == "score"));
2062            assert!(
2063                trend
2064                    .metrics
2065                    .iter()
2066                    .any(|metric| metric.name == "avg_cyclomatic")
2067            );
2068            assert!(
2069                fallow_output::health_score_comparison_note(
2070                    previous.score_formula_version,
2071                    Some(health.formula_version),
2072                )
2073                .is_none()
2074            );
2075        }
2076    }
2077
2078    #[test]
2079    fn trend_compares_only_known_matching_score_formulas() {
2080        let current_vs = make_test_vital_signs();
2081        let counts = make_test_counts();
2082        let current_score = compute_health_score(&current_vs, counts.total_files);
2083        for previous_formula in [
2084            None,
2085            Some(HEALTH_SCORE_FORMULA_VERSION - 1),
2086            Some(HEALTH_SCORE_FORMULA_VERSION),
2087            Some(HEALTH_SCORE_FORMULA_VERSION + 1),
2088        ] {
2089            let mut previous = make_test_snapshot("2026-01-01T00:00:00Z", Some(72.0));
2090            previous.score_formula_version = previous_formula;
2091            let trend =
2092                compute_trend_against(&previous, 1, &current_vs, &counts, Some(&current_score));
2093            assert_eq!(
2094                trend.metrics.iter().any(|metric| metric.name == "score"),
2095                previous_formula == Some(current_score.formula_version),
2096                "previous formula: {previous_formula:?}"
2097            );
2098            assert!(
2099                trend
2100                    .metrics
2101                    .iter()
2102                    .any(|metric| metric.name == "avg_cyclomatic")
2103            );
2104            assert_eq!(trend.compared_to.score, previous.score);
2105            assert_eq!(trend.compared_to.grade, previous.grade);
2106            assert_eq!(trend.compared_to.score_formula_version, previous_formula);
2107        }
2108    }
2109
2110    #[test]
2111    fn trend_uses_actual_current_formula_and_keeps_raw_direction_on_mismatch() {
2112        let current_vs = make_test_vital_signs();
2113        let counts = make_test_counts();
2114        let mut current_score = compute_health_score(&current_vs, counts.total_files);
2115        current_score.formula_version = HEALTH_SCORE_FORMULA_VERSION + 1;
2116        current_score.score = 90.0;
2117        let mut previous = make_test_snapshot("2026-01-01T00:00:00Z", Some(70.0));
2118        previous.vital_signs = current_vs.clone();
2119        previous.counts = counts.clone();
2120        previous.vital_signs.avg_cyclomatic = current_vs.avg_cyclomatic - 2.0;
2121
2122        let incompatible =
2123            compute_trend_against(&previous, 1, &current_vs, &counts, Some(&current_score));
2124        assert!(
2125            !incompatible
2126                .metrics
2127                .iter()
2128                .any(|metric| metric.name == "score")
2129        );
2130        assert_eq!(incompatible.overall_direction, TrendDirection::Declining);
2131
2132        previous.score_formula_version = Some(current_score.formula_version);
2133        let compatible =
2134            compute_trend_against(&previous, 1, &current_vs, &counts, Some(&current_score));
2135        assert!(
2136            compatible
2137                .metrics
2138                .iter()
2139                .any(|metric| metric.name == "score")
2140        );
2141    }
2142
2143    #[test]
2144    fn legacy_snapshot_retains_unknown_formula_without_tool_version_inference() {
2145        let mut value =
2146            serde_json::to_value(make_test_snapshot("2026-01-01T00:00:00Z", Some(70.0))).unwrap();
2147        value["snapshot_schema_version"] = serde_json::json!(11);
2148        value["version"] = serde_json::json!(env!("CARGO_PKG_VERSION"));
2149        value
2150            .as_object_mut()
2151            .unwrap()
2152            .remove("score_formula_version");
2153        let previous: VitalSignsSnapshot = serde_json::from_value(value).unwrap();
2154        assert!(previous.score_formula_version.is_none());
2155        let current_vs = make_test_vital_signs();
2156        let counts = make_test_counts();
2157        let health = compute_health_score(&current_vs, counts.total_files);
2158        let trend = compute_trend_against(&previous, 1, &current_vs, &counts, Some(&health));
2159        assert!(!trend.metrics.iter().any(|metric| metric.name == "score"));
2160        assert!(!trend.metrics.is_empty());
2161    }
2162
2163    #[test]
2164    fn group_trend_uses_snapshot_level_formula_identity() {
2165        let current_vs = make_test_vital_signs();
2166        let counts = make_test_counts();
2167        let health = compute_health_score(&current_vs, counts.total_files);
2168        let group = group_snapshot("@team/a", 70.0);
2169        for formula in [
2170            None,
2171            Some(HEALTH_SCORE_FORMULA_VERSION - 1),
2172            Some(health.formula_version),
2173        ] {
2174            let mut previous = make_test_snapshot("2026-01-01T00:00:00Z", Some(70.0));
2175            previous.score_formula_version = formula;
2176            let trend =
2177                compute_group_trend(&previous, 1, &group, &current_vs, &counts, Some(&health));
2178            assert_eq!(
2179                trend.metrics.iter().any(|metric| metric.name == "score"),
2180                formula == Some(health.formula_version),
2181            );
2182            assert_eq!(trend.compared_to.score, group.score);
2183            assert_eq!(trend.compared_to.grade, group.grade);
2184            assert_eq!(trend.compared_to.score_formula_version, formula);
2185            assert!(!trend.metrics.is_empty());
2186        }
2187    }
2188
2189    #[test]
2190    fn compute_trend_no_snapshots() {
2191        let vs = make_test_vital_signs();
2192        let counts = make_test_counts();
2193        assert!(compute_trend(&vs, &counts, Some(78.0), &[]).is_none());
2194    }
2195
2196    #[test]
2197    fn compute_trend_improving() {
2198        let prev = make_test_snapshot("2026-01-01T00:00:00Z", Some(72.0));
2199        let vs = VitalSigns {
2200            dead_file_pct: Some(2.8),
2201            dead_export_pct: Some(7.5),
2202            avg_cyclomatic: 4.1,
2203            p90_cyclomatic: 12,
2204            hotspot_count: Some(3),
2205            maintainability_avg: Some(75.0),
2206            unused_dep_count: Some(3),
2207            circular_dep_count: Some(1),
2208            ..Default::default()
2209        };
2210        let counts = VitalSignsCounts {
2211            total_files: 100,
2212            total_exports: 500,
2213            dead_files: 3,
2214            dead_exports: 38,
2215            files_scored: Some(95),
2216            total_deps: 40,
2217            ..Default::default()
2218        };
2219
2220        let trend = compute_trend(&vs, &counts, Some(78.0), &[prev]).unwrap();
2221        assert_eq!(trend.compared_to.timestamp, "2026-01-01T00:00:00Z");
2222        assert_eq!(trend.snapshots_loaded, 1);
2223        assert_eq!(trend.overall_direction, TrendDirection::Improving);
2224
2225        let score_metric = trend.metrics.iter().find(|m| m.name == "score").unwrap();
2226        assert_eq!(score_metric.direction, TrendDirection::Improving);
2227        assert!((score_metric.delta - 6.0).abs() < f64::EPSILON);
2228    }
2229
2230    #[test]
2231    fn compute_trend_stable_within_tolerance() {
2232        let prev = make_test_snapshot("2026-01-01T00:00:00Z", Some(78.0));
2233        let vs = make_test_vital_signs();
2234        let counts = make_test_counts();
2235
2236        let trend = compute_trend(&vs, &counts, Some(78.3), &[prev]).unwrap();
2237        let score_metric = trend.metrics.iter().find(|m| m.name == "score").unwrap();
2238        assert_eq!(score_metric.direction, TrendDirection::Stable);
2239    }
2240
2241    #[test]
2242    fn compute_trend_uses_most_recent_snapshot() {
2243        let older = make_test_snapshot("2026-01-01T00:00:00Z", Some(60.0));
2244        let vs = make_test_vital_signs();
2245        let counts = make_test_counts();
2246
2247        for newest_formula in [
2248            None,
2249            Some(HEALTH_SCORE_FORMULA_VERSION - 1),
2250            Some(HEALTH_SCORE_FORMULA_VERSION),
2251        ] {
2252            let mut newer = make_test_snapshot("2026-03-01T00:00:00Z", Some(72.0));
2253            newer.score_formula_version = newest_formula;
2254            let trend = compute_trend(&vs, &counts, Some(78.0), &[older.clone(), newer]).unwrap();
2255            assert_eq!(trend.compared_to.score, Some(72.0));
2256            assert_eq!(trend.snapshots_loaded, 2);
2257            assert_eq!(
2258                trend.metrics.iter().any(|metric| metric.name == "score"),
2259                newest_formula == Some(HEALTH_SCORE_FORMULA_VERSION)
2260            );
2261        }
2262    }
2263
2264    #[test]
2265    fn compute_trend_includes_raw_counts() {
2266        let prev = make_test_snapshot("2026-01-01T00:00:00Z", Some(72.0));
2267        let vs = make_test_vital_signs();
2268        let counts = make_test_counts();
2269
2270        let trend = compute_trend(&vs, &counts, Some(78.0), &[prev]).unwrap();
2271        let dead_files = trend
2272            .metrics
2273            .iter()
2274            .find(|m| m.name == "dead_file_pct")
2275            .unwrap();
2276        assert!(dead_files.previous_count.is_some());
2277        assert!(dead_files.current_count.is_some());
2278    }
2279
2280    fn make_test_vital_signs() -> VitalSigns {
2281        VitalSigns {
2282            dead_file_pct: Some(3.2),
2283            dead_export_pct: Some(8.1),
2284            avg_cyclomatic: 4.2,
2285            p90_cyclomatic: 12,
2286            hotspot_count: Some(5),
2287            maintainability_avg: Some(72.4),
2288            unused_dep_count: Some(4),
2289            circular_dep_count: Some(2),
2290            ..Default::default()
2291        }
2292    }
2293
2294    fn make_test_counts() -> VitalSignsCounts {
2295        VitalSignsCounts {
2296            total_files: 100,
2297            total_exports: 500,
2298            dead_files: 3,
2299            dead_exports: 40,
2300            files_scored: Some(95),
2301            total_deps: 42,
2302            ..Default::default()
2303        }
2304    }
2305
2306    pub(super) fn make_test_snapshot(timestamp: &str, score: Option<f64>) -> VitalSignsSnapshot {
2307        VitalSignsSnapshot {
2308            groups: None,
2309            snapshot_schema_version: SNAPSHOT_SCHEMA_VERSION,
2310            version: "2.5.5".into(),
2311            timestamp: timestamp.into(),
2312            git_sha: Some("abc1234".into()),
2313            git_branch: Some("main".into()),
2314            shallow_clone: false,
2315            vital_signs: VitalSigns {
2316                dead_file_pct: Some(3.2),
2317                dead_export_pct: Some(8.1),
2318                avg_cyclomatic: 4.7,
2319                p90_cyclomatic: 12,
2320                hotspot_count: Some(5),
2321                maintainability_avg: Some(72.4),
2322                unused_dep_count: Some(4),
2323                circular_dep_count: Some(2),
2324                ..Default::default()
2325            },
2326            counts: VitalSignsCounts {
2327                total_files: 100,
2328                total_exports: 500,
2329                dead_files: 3,
2330                dead_exports: 40,
2331                files_scored: Some(95),
2332                total_deps: 42,
2333                ..Default::default()
2334            },
2335            score,
2336            grade: score.map(|s| letter_grade(s).to_string()),
2337            score_formula_version: score.map(|_| HEALTH_SCORE_FORMULA_VERSION),
2338            coverage_model: None,
2339            analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
2340        }
2341    }
2342
2343    fn group_snapshot(key: &str, score: f64) -> fallow_output::GroupSnapshot {
2344        fallow_output::GroupSnapshot {
2345            key: key.to_owned(),
2346            files_analyzed: 10,
2347            vital_signs: VitalSigns {
2348                avg_cyclomatic: 3.0,
2349                p90_cyclomatic: 8,
2350                ..Default::default()
2351            },
2352            counts: VitalSignsCounts {
2353                total_files: 10,
2354                ..Default::default()
2355            },
2356            score: Some(score),
2357            grade: Some(letter_grade(score).to_string()),
2358            severity_critical_count: 2,
2359            hotspot_count: 1,
2360        }
2361    }
2362
2363    #[test]
2364    fn v10_snapshot_without_groups_still_deserializes() {
2365        let mut value =
2366            serde_json::to_value(make_test_snapshot("2026-01-01T00:00:00Z", Some(70.0))).unwrap();
2367        value["snapshot_schema_version"] = serde_json::json!(10);
2368        value.as_object_mut().unwrap().remove("groups");
2369        let snapshot: VitalSignsSnapshot = serde_json::from_value(value).unwrap();
2370        assert_eq!(snapshot.snapshot_schema_version, 10);
2371        assert!(snapshot.groups.is_none());
2372    }
2373
2374    #[test]
2375    fn v11_snapshot_round_trips_group_data() {
2376        let mut snapshot = make_test_snapshot("2026-01-01T00:00:00Z", Some(70.0));
2377        snapshot.groups = Some(fallow_output::SnapshotGrouping {
2378            grouped_by: "owner".to_owned(),
2379            group_filter: Some(vec!["@team/*".to_owned()]),
2380            groups: vec![group_snapshot("@team/a", 81.5)],
2381        });
2382        let json = serde_json::to_string(&snapshot).unwrap();
2383        let loaded: VitalSignsSnapshot = serde_json::from_str(&json).unwrap();
2384        let groups = loaded.groups.expect("groups survive the round trip");
2385        assert_eq!(groups.grouped_by, "owner");
2386        assert_eq!(groups.group_filter, Some(vec!["@team/*".to_owned()]));
2387        assert_eq!(groups.groups[0].key, "@team/a");
2388        assert_eq!(groups.groups[0].score, Some(81.5));
2389        assert_eq!(groups.groups[0].severity_critical_count, 2);
2390        let ungrouped =
2391            serde_json::to_value(make_test_snapshot("2026-01-01T00:00:00Z", None)).unwrap();
2392        assert!(
2393            ungrouped.get("groups").is_none(),
2394            "ungrouped snapshot omits groups"
2395        );
2396    }
2397
2398    #[test]
2399    fn explicit_trend_baseline_reads_that_file_only() {
2400        let dir = tempfile::tempdir().unwrap();
2401        let root = dir.path();
2402        let snap_dir = root.join(".fallow/snapshots");
2403        std::fs::create_dir_all(&snap_dir).unwrap();
2404        std::fs::write(
2405            snap_dir.join("newer.json"),
2406            serde_json::to_string(&make_test_snapshot("2026-09-01T00:00:00Z", Some(90.0))).unwrap(),
2407        )
2408        .unwrap();
2409        let explicit = root.join("restored.json");
2410        std::fs::write(
2411            &explicit,
2412            serde_json::to_string(&make_test_snapshot("2026-01-01T00:00:00Z", Some(60.0))).unwrap(),
2413        )
2414        .unwrap();
2415
2416        let baseline = load_trend_baseline(root, Some(&explicit))
2417            .unwrap()
2418            .expect("explicit baseline");
2419        assert_eq!(baseline.snapshot.timestamp, "2026-01-01T00:00:00Z");
2420        assert_eq!(baseline.snapshots_loaded, 1);
2421        assert_eq!(baseline.path, explicit);
2422
2423        let directory = load_trend_baseline(root, None).unwrap().expect("newest");
2424        assert_eq!(directory.snapshot.timestamp, "2026-09-01T00:00:00Z");
2425        assert_eq!(directory.snapshots_loaded, 1);
2426    }
2427
2428    #[test]
2429    fn explicit_trend_baseline_fails_on_missing_or_invalid_file() {
2430        let dir = tempfile::tempdir().unwrap();
2431        let root = dir.path();
2432        let missing = load_trend_baseline(root, Some(&root.join("absent.json"))).unwrap_err();
2433        assert!(
2434            missing.contains("failed to read --trend-from snapshot"),
2435            "{missing}"
2436        );
2437        let invalid_path = root.join("invalid.json");
2438        std::fs::write(&invalid_path, "{\"not\": \"a snapshot\"}").unwrap();
2439        let invalid = load_trend_baseline(root, Some(&invalid_path)).unwrap_err();
2440        assert!(
2441            invalid.contains("is not a fallow health snapshot"),
2442            "{invalid}"
2443        );
2444        assert!(load_trend_baseline(root, None).unwrap().is_none());
2445    }
2446
2447    #[test]
2448    fn explicit_trend_baseline_error_does_not_echo_file_content() {
2449        let dir = tempfile::tempdir().unwrap();
2450        let root = dir.path();
2451        for (index, content) in [r#"{"timestamp": "private-value"}"#, r#"["private-value"]"#]
2452            .into_iter()
2453            .enumerate()
2454        {
2455            let path = root.join(format!("leak-{index}.json"));
2456            std::fs::write(&path, content).unwrap();
2457            let error = load_trend_baseline(root, Some(&path)).unwrap_err();
2458            assert!(error.contains("is not a fallow health snapshot"), "{error}");
2459            assert!(error.contains("line 1, column"), "{error}");
2460            assert!(!error.contains("private-value"), "{error}");
2461        }
2462    }
2463
2464    #[test]
2465    fn group_trend_compares_against_the_stored_group() {
2466        let baseline = TrendBaseline {
2467            snapshot: make_test_snapshot("2026-01-01T00:00:00Z", Some(70.0)),
2468            path: PathBuf::from("baseline.json"),
2469            snapshots_loaded: 1,
2470        };
2471        let current = VitalSigns {
2472            avg_cyclomatic: 3.0,
2473            p90_cyclomatic: 8,
2474            ..Default::default()
2475        };
2476        let counts = VitalSignsCounts {
2477            total_files: 10,
2478            ..Default::default()
2479        };
2480        let current_score = HealthScore {
2481            score: 84.0,
2482            ..compute_health_score(&current, counts.total_files)
2483        };
2484        let trend = compute_group_trend(
2485            &baseline.without_groups(),
2486            baseline.snapshots_loaded,
2487            &group_snapshot("@team/a", 80.0),
2488            &current,
2489            &counts,
2490            Some(&current_score),
2491        );
2492        let score = trend
2493            .metrics
2494            .iter()
2495            .find(|metric| metric.name == "score")
2496            .expect("score metric");
2497        assert!((score.previous - 80.0).abs() < f64::EPSILON);
2498        assert!((score.delta - 4.0).abs() < 1e-9);
2499        assert_eq!(score.direction, TrendDirection::Improving);
2500        assert_eq!(trend.compared_to.timestamp, "2026-01-01T00:00:00Z");
2501        assert_eq!(trend.compared_to.score, Some(80.0));
2502    }
2503}