Skip to main content

fallow_cli/health_types/
mod.rs

1//! Health / complexity analysis report types.
2//!
3//! Separated from the `health` command module so that report formatters
4//! (which are compiled as part of both the lib and bin targets) can
5//! reference these types without pulling in binary-only dependencies.
6
7mod coverage;
8mod coverage_intelligence;
9mod finding;
10mod grouped;
11mod runtime_coverage;
12mod scores;
13mod targets;
14mod trends;
15mod vital_signs;
16
17pub use coverage::*;
18pub use coverage_intelligence::*;
19pub use finding::*;
20pub use grouped::*;
21pub use runtime_coverage::*;
22pub use scores::*;
23pub use targets::*;
24pub use trends::*;
25pub use vital_signs::*;
26
27/// Detailed timing breakdown for the health pipeline.
28///
29/// Only populated when `--performance` is passed.
30#[derive(Debug, Clone, serde::Serialize)]
31pub struct HealthTimings {
32    pub config_ms: f64,
33    pub discover_ms: f64,
34    pub parse_ms: f64,
35    /// Summed wall-clock time of the actual AST parses across all rayon
36    /// workers (the parse stage's CPU cost). `parse_ms` is the stage's
37    /// wall-clock time. Observational and non-deterministic; do not assert
38    /// against it. `0.0` when `shared_parse` is true (parse was reused).
39    pub parse_cpu_ms: f64,
40    pub complexity_ms: f64,
41    pub file_scores_ms: f64,
42    pub git_churn_ms: f64,
43    pub git_churn_cache_hit: bool,
44    pub hotspots_ms: f64,
45    pub duplication_ms: f64,
46    pub targets_ms: f64,
47    pub total_ms: f64,
48    /// True when discover + parse were reused from the upstream dead-code
49    /// (check) pass in combined mode, so their timings are `0.0` here and
50    /// the cost is attributed to the `Pipeline Performance` table instead.
51    /// The renderer shows those two stages as `(measured above)`.
52    pub shared_parse: bool,
53}
54
55/// Auditable breadcrumb recording when health-finding `suppress-line`
56/// action hints were omitted from the report.
57///
58/// Set at construction time on [`HealthReport::actions_meta`] (and on
59/// each [`HealthGroup::actions_meta`](crate::health_types::HealthGroup)
60/// when grouped) by the report builder, derived from the active
61/// [`HealthActionContext`]. Lets consumers see "where did the
62/// suppress-line hints go?" without having to grep the config or CLI
63/// history.
64///
65/// Stable `reason` codes:
66/// - `baseline-active`: a baseline is active and inline ignores would
67///   become dead annotations once the baseline regenerates.
68/// - `config-disabled`: `health.suggestInlineSuppression` is `false`.
69/// - `unspecified`: the caller did not record a reason.
70#[derive(Debug, Clone, serde::Serialize)]
71#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
72pub struct HealthActionsMeta {
73    /// Always `true` when the breadcrumb is emitted. Absent from the wire
74    /// when no suppression occurred.
75    pub suppression_hints_omitted: bool,
76    /// Stable code describing why the suppression occurred.
77    pub reason: String,
78    /// Scope of the omission. Always `"health-findings"` today.
79    pub scope: String,
80}
81
82/// Result of complexity analysis for reporting.
83#[derive(Debug, Clone, serde::Serialize)]
84#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
85pub struct HealthReport {
86    /// Functions and synthetic template entries exceeding complexity
87    /// thresholds, sorted by the --sort criteria. Each entry wraps its
88    /// inner [`ComplexityViolation`] payload (flattened on the wire) with
89    /// the typed `actions` list and an optional audit-mode `introduced`
90    /// flag.
91    pub findings: Vec<HealthFinding>,
92    /// Summary statistics.
93    pub summary: HealthSummary,
94    /// Project-wide vital signs (always computed from available data).
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub vital_signs: Option<VitalSigns>,
97    /// Project-wide health score (only populated with `--score`).
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub health_score: Option<HealthScore>,
100    /// Per-file health scores. Only present when --file-scores is used. Sorted
101    /// by risk-aware triage concern, combining low maintainability and high
102    /// CRAP risk. Zero-function files (barrels) are excluded by default.
103    #[serde(default, skip_serializing_if = "Vec::is_empty")]
104    pub file_scores: Vec<FileHealthScore>,
105    /// Static coverage gaps.
106    ///
107    /// Populated when coverage gaps are explicitly requested, or when the
108    /// top-level `health` command allows config severity to surface them in the
109    /// default report.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub coverage_gaps: Option<CoverageGaps>,
112    /// Hotspot entries combining git churn with complexity. Only present when
113    /// --hotspots is used. Sorted by score descending (highest risk first).
114    /// Each entry wraps its inner [`HotspotEntry`] payload (flattened on the
115    /// wire) with a typed `actions` list.
116    #[serde(default, skip_serializing_if = "Vec::is_empty")]
117    pub hotspots: Vec<HotspotFinding>,
118    /// Hotspot analysis summary (only set with `--hotspots`).
119    #[serde(default, skip_serializing_if = "Option::is_none")]
120    pub hotspot_summary: Option<HotspotSummary>,
121    /// Runtime coverage findings from the paid sidecar (only populated with
122    /// `--runtime-coverage`).
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub runtime_coverage: Option<RuntimeCoverageReport>,
125    /// Combined coverage, runtime, complexity, and change-scope verdicts.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub coverage_intelligence: Option<CoverageIntelligenceReport>,
128    /// Functions exceeding 60 LOC (very high risk). Only present when unit size
129    /// very-high-risk bin >= 3%. Sorted by line count descending.
130    #[serde(default, skip_serializing_if = "Vec::is_empty")]
131    pub large_functions: Vec<LargeFunctionEntry>,
132    /// Ranked refactoring recommendations. Only present when --targets is used.
133    /// Sorted by efficiency (priority/effort) descending. Each entry wraps
134    /// its inner [`RefactoringTarget`] payload (flattened on the wire) with
135    /// a typed `actions` list.
136    #[serde(default, skip_serializing_if = "Vec::is_empty")]
137    pub targets: Vec<RefactoringTargetFinding>,
138    /// Adaptive thresholds used for target scoring (only set with `--targets`).
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub target_thresholds: Option<TargetThresholds>,
141    /// Health trend comparison against a previous snapshot (only set with `--trend`).
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub health_trend: Option<HealthTrend>,
144    /// Audit breadcrumb explaining systemic action-array adjustments. Present
145    /// only when at least one adjustment was made (e.g., health finding
146    /// suppression hints omitted because a baseline is active). When --group-by
147    /// is active, each entry of `groups` may carry its own `actions_meta`
148    /// describing the same omission so per-group consumers do not need to walk
149    /// back to the report root.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub actions_meta: Option<HealthActionsMeta>,
152}
153
154#[cfg(test)]
155#[expect(
156    clippy::derivable_impls,
157    reason = "test-only Default with custom HealthSummary thresholds (20/15)"
158)]
159impl Default for HealthReport {
160    fn default() -> Self {
161        Self {
162            findings: vec![],
163            summary: HealthSummary::default(),
164            vital_signs: None,
165            health_score: None,
166            file_scores: vec![],
167            coverage_gaps: None,
168            hotspots: vec![],
169            hotspot_summary: None,
170            runtime_coverage: None,
171            coverage_intelligence: None,
172            large_functions: vec![],
173            targets: vec![],
174            target_thresholds: None,
175            health_trend: None,
176            actions_meta: None,
177        }
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn health_report_skips_empty_collections() {
187        let report = HealthReport::default();
188        let json = serde_json::to_string(&report).unwrap();
189        // Empty vecs should be omitted due to skip_serializing_if
190        assert!(!json.contains("file_scores"));
191        assert!(!json.contains("hotspots"));
192        assert!(!json.contains("hotspot_summary"));
193        assert!(!json.contains("runtime_coverage"));
194        assert!(!json.contains("coverage_intelligence"));
195        assert!(!json.contains("large_functions"));
196        assert!(!json.contains("targets"));
197        assert!(!json.contains("vital_signs"));
198        assert!(!json.contains("health_score"));
199    }
200
201    #[test]
202    fn health_score_none_skipped_in_report() {
203        let report = HealthReport::default();
204        let json = serde_json::to_string(&report).unwrap();
205        assert!(!json.contains("health_score"));
206    }
207}