Skip to main content

fallow_output/
health_scores.rs

1//! Score types, grade boundaries, file health metrics, and findings.
2
3use crate::{CoverageInputFormat, CoverageModel};
4
5/// Minimum churn-times-complexity hotspot score for an entry to count toward
6/// the vital-signs `hotspot_count`; lower-scoring entries still appear in the
7/// hotspot list but do not feed the health-score hotspot penalty.
8pub const HOTSPOT_SCORE_THRESHOLD: f64 = 50.0;
9
10/// Cognitive complexity at or above which a function is flagged as an
11/// extraction candidate in refactor targets and cited as a contributing
12/// factor on file health scores.
13pub const COGNITIVE_EXTRACTION_THRESHOLD: u16 = 30;
14
15/// Default cognitive complexity threshold for "high" finding severity;
16/// crossing it upgrades a complexity finding from moderate to high.
17pub const DEFAULT_COGNITIVE_HIGH: u16 = 25;
18
19/// Default cognitive complexity threshold for "critical" finding severity.
20pub const DEFAULT_COGNITIVE_CRITICAL: u16 = 40;
21
22/// Default cyclomatic complexity threshold for "high" finding severity;
23/// crossing it upgrades a complexity finding from moderate to high.
24pub const DEFAULT_CYCLOMATIC_HIGH: u16 = 30;
25
26/// Default cyclomatic complexity threshold for "critical" finding severity.
27/// Also the cutoff for the v2 health score's critical-complexity density
28/// penalty (share of functions at or above this value).
29pub const DEFAULT_CYCLOMATIC_CRITICAL: u16 = 50;
30
31/// Minimum lines of code for full complexity density weight in the MI formula.
32pub const MI_DENSITY_MIN_LINES: f64 = 50.0;
33
34/// Formula version for the overall health score, serialized as
35/// [`HealthScore::formula_version`] so consumers can distinguish a score shift
36/// caused by a formula change from one caused by an actual codebase change.
37/// v2 replaced the size-dependent aggregators (average and p90 cyclomatic,
38/// raw hotspot and dependency counts) with scale-invariant densities
39/// (critical-complexity share, per-thousand-file dependency rates, top-1%
40/// hotspot share) so scores are comparable across repository sizes; older
41/// snapshots that lack the density fields fall back to the v1 aggregators.
42/// v3 counts only hotspots meeting [`HOTSPOT_SCORE_THRESHOLD`] against the
43/// top-1% file population, rather than penalizing every positive ranked entry.
44/// See `engine::vital_signs` for the full penalty formula.
45pub const HEALTH_SCORE_FORMULA_VERSION: u32 = 3;
46
47/// Formula version for the styling-health score (the CSS / design-system axis).
48/// Bumped independently of [`HEALTH_SCORE_FORMULA_VERSION`] whenever the styling
49/// penalty rubric is recalibrated, so consumers can distinguish a score shift
50/// caused by a weight change from one caused by an actual codebase change. v2
51/// recalibrated `dead_surface` (size-stable declaration-share denominator) and
52/// `token_erosion` (gently saturating arbitrary-value term) from real-project
53/// evidence. v3 re-weighted the duplication family toward value DRIFT: it
54/// down-weighted the exact-block `duplication` scale (exact CSS duplication is the
55/// least-harmful pattern) and added a hardcoded-value-sprawl drift sub-term to
56/// `token_erosion` (distinct un-tokenized `box-shadow`/`border-radius`/`line-height`
57/// values). See `engine::health::styling_score` for the full rubric + calibration.
58pub const STYLING_HEALTH_FORMULA_VERSION: u32 = 3;
59
60/// `skip_serializing_if` predicate: drop a `u16` field from JSON when zero, so
61/// the React descriptive counts never bloat non-React complexity findings.
62#[expect(
63    clippy::trivially_copy_pass_by_ref,
64    reason = "serde skip_serializing_if requires a by-reference predicate"
65)]
66fn is_zero_u16(value: &u16) -> bool {
67    *value == 0
68}
69
70/// `skip_serializing_if` predicate: drop a `usize` field from JSON when zero,
71/// so default-configuration file-score rows stay byte-identical.
72#[expect(
73    clippy::trivially_copy_pass_by_ref,
74    reason = "serde skip_serializing_if requires a by-reference predicate"
75)]
76fn is_zero_usize(value: &usize) -> bool {
77    *value == 0
78}
79
80/// Overall project health score: 100 minus capped per-category penalties.
81#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
82#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
83pub struct HealthScore {
84    /// Score formula version; see [`HEALTH_SCORE_FORMULA_VERSION`].
85    pub formula_version: u32,
86    /// Health score in `[0, 100]`; higher is healthier.
87    pub score: f64,
88    /// Letter grade from [`letter_grade`] (A>=85, B>=70, C>=55, D>=40, F<40).
89    #[serde(deserialize_with = "crate::static_str::deserialize")]
90    pub grade: crate::static_str::StaticStr,
91    /// Per-component penalty breakdown.
92    pub penalties: HealthScorePenalties,
93}
94
95/// Per-component penalty breakdown for the health score.
96#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
97#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
98pub struct HealthScorePenalties {
99    /// Points subtracted for unreachable files; absent when dead-code data
100    /// was not available.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub dead_files: Option<f64>,
103    /// Points subtracted for unused exports; absent when dead-code data was
104    /// not available.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub dead_exports: Option<f64>,
107    /// Points subtracted for overall complexity load.
108    pub complexity: f64,
109    /// Points subtracted for the complexity tail (v1: p90 cyclomatic; v2:
110    /// critical-complexity density).
111    pub p90_complexity: f64,
112    /// Points subtracted for low maintainability-index files; absent when
113    /// file scores were not computed.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub maintainability: Option<f64>,
116    /// Points subtracted for churn-times-complexity hotspots; absent without
117    /// git history.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub hotspots: Option<f64>,
120    /// Points subtracted for unused dependencies; absent when dead-code data
121    /// was not available.
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub unused_deps: Option<f64>,
124    /// Points subtracted for circular dependency chains; absent when
125    /// dead-code data was not available.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub circular_deps: Option<f64>,
128    /// Penalty for oversized functions, computed against fixed calibration
129    /// (very-high-risk bin edge at 60 LOC). Deliberately independent of
130    /// `health.maxUnitSize`, which filters the large-functions findings list
131    /// only; raising that threshold empties the list without moving this
132    /// penalty. `health.ignore` removes files from the score entirely.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub unit_size: Option<f64>,
135    /// Points subtracted for fan-in coupling concentration; absent when the
136    /// module graph was not available.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub coupling: Option<f64>,
139    /// Points subtracted for duplicated code; absent when the duplication
140    /// pipeline did not run.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub duplication: Option<f64>,
143    /// Small capped penalty for prop-drilling chains. `None` unless the opt-in
144    /// `prop-drilling` rule is enabled; sized like the coupling penalty (~5pt cap).
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub prop_drilling: Option<f64>,
147}
148
149/// Project-level styling-health score: a SECOND health axis computed purely from
150/// the structural CSS analytics (`CssAnalyticsReport`), orthogonal to the JS/TS
151/// code-health [`HealthScore`]. Surfaced only alongside the `--css` analytics, so
152/// a plain `fallow health` run is byte-unchanged. The code score and grade stay
153/// untouched: styling health is additive, never folded into the code score.
154///
155/// Like [`HealthScore`], the score starts at 100 and subtracts capped per-category
156/// penalties; the grade reuses the shared [`letter_grade`] thresholds verbatim
157/// (A>=85, B>=70, C>=55, D>=40, F<40), so the two axes are read on one scale.
158#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
159#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
160pub struct StylingHealth {
161    /// Styling formula version; see [`STYLING_HEALTH_FORMULA_VERSION`].
162    pub formula_version: u32,
163    /// Styling-health score in `[0, 100]`; higher is healthier.
164    pub score: f64,
165    /// Letter grade from the shared [`letter_grade`] thresholds.
166    #[serde(deserialize_with = "crate::static_str::deserialize")]
167    pub grade: crate::static_str::StaticStr,
168    /// Per-category penalty breakdown.
169    pub penalties: StylingHealthPenalties,
170    /// How much to trust the grade. `Low` in either of two cases, `High`
171    /// otherwise (see `confidence_reason` for which): (1) the analyzed CSS surface
172    /// is too thin for the declaration-normalized penalty rubric to be reliable
173    /// (the gradeable, non-atomic declaration count is below 50); or (2) the
174    /// project's CSS is predominantly flat compile-time-atomic CSS-in-JS
175    /// (StyleX/Panda), whose structure is not assessable, so the grade reflects
176    /// token hygiene only regardless of declaration count. This is descriptive
177    /// metadata that NEVER feeds the score: `score`/`grade`/`penalties` are
178    /// byte-identical whether confidence is high or low. Gate on this `confidence`
179    /// flag, which is the complete signal; do NOT reconstruct it from
180    /// `total_declarations`, since that summary count includes atomic declarations
181    /// the grade excludes (a large all-atomic project is `Low` despite a high
182    /// `total_declarations`).
183    pub confidence: StylingHealthConfidence,
184    /// Human-readable reason the grade is low-confidence: either the declaration
185    /// and stylesheet counts a thin grade was computed from, or that structure is
186    /// not assessable for compile-time-atomic CSS-in-JS. `None` when confidence is
187    /// `High`. Prose, not a stable machine field: gate on `confidence`, not on
188    /// this string.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub confidence_reason: Option<String>,
191}
192
193/// Trust level for a [`StylingHealth`] grade. TWO variants (not the three-tier
194/// `high`/`medium`/`low` of [`crate::Confidence`] / `FeatureFlagConfidence`) ON
195/// PURPOSE: styling confidence is binary (the grade is either reliable for the
196/// analyzed surface or it is not), not three distinct evidence tiers, so a
197/// never-emitted `Medium` would be dead surface. Serializes lowercase (`"high"` /
198/// `"low"`), matching the sibling confidence enums' vocabulary.
199#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
200#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
201#[serde(rename_all = "lowercase")]
202pub enum StylingHealthConfidence {
203    /// The analyzed CSS surface is large enough, and structurally assessable
204    /// enough, for the grade to be reliable.
205    High,
206    /// The grade is indicative rather than authoritative, for one of two reasons
207    /// (named in `confidence_reason`): a thin authored-CSS surface (little to
208    /// measure), or predominantly flat compile-time-atomic CSS-in-JS
209    /// (StyleX/Panda) whose structure is not assessable. NOT a signal that
210    /// fallow's analysis failed.
211    Low,
212}
213
214/// Per-category penalty breakdown for the styling-health score. Each field is the
215/// number of points subtracted from a starting 100 for one CSS signal family,
216/// already capped at its category ceiling. A `0.0` field means "the signal was
217/// evaluated and clean"; the whole struct is only ever built when CSS analytics
218/// were produced, so there is no "missing pipeline" ambiguity to model with
219/// `Option` here (the parent `StylingHealth` is itself `Option` on the report).
220#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
221#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
222pub struct StylingHealthPenalties {
223    /// Copy-paste declaration blocks (`duplicate_declaration_blocks`), scaled by
224    /// total removable declarations. Capped at 20pt.
225    pub duplication: f64,
226    /// Dead styling surface, two independently-normalized terms summed and capped
227    /// at 20pt: (a) unused `@theme` tokens as a share of the total `@theme` token
228    /// population (size-independent, so a declaration-sparse Tailwind project is
229    /// not penalized for a few dead tokens); plus (b) the other dead entities
230    /// (unreferenced classes, unused `@property`/`@layer` at-rules, dead
231    /// `@font-face` families) as a share of `total_declarations`.
232    pub dead_surface: f64,
233    /// Broken references: markup classes one edit from a defined class
234    /// (`unresolved_class_references`) and animations referencing a `@keyframes`
235    /// defined nowhere (`undefined_keyframes`). Capped at 15pt.
236    pub broken_references: f64,
237    /// Design-token erosion: mixed `font-size` units (`font_size_unit_mix`),
238    /// Tailwind arbitrary-value bypasses (`tailwind_arbitrary_values`), and
239    /// distinct HARDCODED `box-shadow`/`border-radius`/`line-height` values above
240    /// per-axis baselines (the v3 value-sprawl drift sub-term; `var(--*)`-
241    /// referenced values are not counted). Capped at 10pt.
242    pub token_erosion: f64,
243    /// Structural smells from the summary aggregates: `!important` density and
244    /// deep style-rule nesting. Capped at 10pt.
245    pub structural: f64,
246}
247
248/// Map a numeric score (0-100) to a letter grade.
249#[must_use]
250#[expect(
251    clippy::cast_possible_truncation,
252    clippy::cast_sign_loss,
253    reason = "score is 0-100, fits in u32"
254)]
255pub const fn letter_grade(score: f64) -> &'static str {
256    let s = score as u32;
257    if s >= 85 {
258        "A"
259    } else if s >= 70 {
260        "B"
261    } else if s >= 55 {
262        "C"
263    } else if s >= 40 {
264        "D"
265    } else {
266        "F"
267    }
268}
269
270/// Coverage tier classification for CRAP findings.
271#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
272#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
273#[serde(rename_all = "snake_case")]
274pub enum CoverageTier {
275    /// No test coverage.
276    None,
277    /// Some coverage below the high watermark.
278    Partial,
279    /// Coverage at or above the high watermark (70%).
280    High,
281}
282
283/// Coverage percentage at or above which a function is classified as `High`.
284const HIGH_COVERAGE_WATERMARK: f64 = 70.0;
285
286impl CoverageTier {
287    /// Bucket a numeric coverage percentage `[0, 100]` into a tier.
288    #[must_use]
289    pub fn from_pct(pct: f64) -> Self {
290        if pct <= 0.0 {
291            Self::None
292        } else if pct >= HIGH_COVERAGE_WATERMARK {
293            Self::High
294        } else {
295            Self::Partial
296        }
297    }
298}
299
300/// Provenance of a CRAP finding's coverage signal.
301#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
302#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
303#[serde(rename_all = "snake_case")]
304pub enum CoverageSource {
305    /// Measured from a coverage map: Istanbul JSON, or raw V8 coverage that
306    /// fallow converts to the same model. `summary.coverage_input_format`
307    /// names which one.
308    Istanbul,
309    /// Estimated from static test reachability.
310    Estimated,
311    /// Estimated coverage inherited from the enclosing component.
312    EstimatedComponentInherited,
313}
314
315/// Whether CRAP findings in the report used one coverage-source kind or a mix.
316#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
317#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
318#[serde(rename_all = "snake_case")]
319pub enum CoverageSourceConsistency {
320    /// Every CRAP finding used the same coverage source.
321    Uniform,
322    /// CRAP findings mix coverage sources.
323    Mixed,
324}
325
326/// Summarise the coverage-source provenance attached to CRAP findings.
327#[must_use]
328pub fn summarize_coverage_source_consistency(
329    sources: impl IntoIterator<Item = CoverageSource>,
330) -> Option<CoverageSourceConsistency> {
331    let mut first = None;
332    for source in sources {
333        match first {
334            None => first = Some(source),
335            Some(existing) if existing != source => {
336                return Some(CoverageSourceConsistency::Mixed);
337            }
338            Some(_) => {}
339        }
340    }
341    first.map(|_| CoverageSourceConsistency::Uniform)
342}
343
344/// Per-component React hook profile derived from the cached `hook_uses` IR at
345/// the health layer. Descriptive context that refines the bare
346/// [`ComplexityViolation::react_hook_count`] headline with a per-kind breakdown
347/// and the maximum `useEffect` dependency-array arity.
348///
349/// Attached only when at least one component-scope hook was attributed to the
350/// function, so non-React findings stay byte-identical on the wire. The
351/// per-kind counts cover hooks recorded by the React visitor (calls inside an
352/// identified component); a `use*` call inside a plain helper function is
353/// counted in `react_hook_count` but NOT here, so the breakdown can sum to LESS
354/// than `react_hook_count`. `react_hook_count` remains the headline total; this
355/// is an additive refinement.
356#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
357#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
358pub struct ReactHookProfile {
359    /// `useState` call count attributed to this component.
360    pub state: u16,
361    /// `useEffect` call count attributed to this component.
362    pub effect: u16,
363    /// `useMemo` call count attributed to this component.
364    pub memo: u16,
365    /// `useCallback` call count attributed to this component.
366    pub callback: u16,
367    /// Custom `use*` hook call count attributed to this component.
368    pub custom: u16,
369    /// Largest `useEffect` dependency-array arity over the attributed effects
370    /// that carry a literal deps array. `None` when no attributed `useEffect`
371    /// had a literal array (absent or non-literal deps; ADR-001 syntactic-only,
372    /// so absence does NOT mean "no coupling").
373    #[serde(default, skip_serializing_if = "Option::is_none")]
374    pub max_effect_dep_arity: Option<u32>,
375}
376
377impl ReactHookProfile {
378    /// Total component-scope hooks attributed (state + effect + memo + callback
379    /// + custom). Used to gate whether the profile is surfaced at all.
380    #[must_use]
381    pub fn total(&self) -> u16 {
382        self.state
383            .saturating_add(self.effect)
384            .saturating_add(self.memo)
385            .saturating_add(self.callback)
386            .saturating_add(self.custom)
387    }
388
389    /// `true` when no hook was attributed, so the profile carries no signal.
390    #[must_use]
391    pub fn is_empty(&self) -> bool {
392        self.total() == 0
393    }
394}
395
396/// Inner complexity-violation payload.
397#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
398#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
399pub struct ComplexityViolation {
400    /// File path relative to the project root.
401    #[serde(serialize_with = "fallow_types::serde_path::serialize")]
402    pub path: std::path::PathBuf,
403    /// Function name, or a synthesized name for anonymous functions.
404    pub name: String,
405    /// 1-based line the function starts on.
406    pub line: u32,
407    /// 1-based column the function starts on.
408    pub col: u32,
409    /// Cyclomatic complexity of the function.
410    pub cyclomatic: u16,
411    /// Cognitive complexity of the function.
412    pub cognitive: u16,
413    /// Lines of code in the function body.
414    pub line_count: u32,
415    /// Number of declared parameters.
416    pub param_count: u8,
417    /// Number of React hook calls in this function's body (`useState` /
418    /// `useEffect` / `useMemo` / `useCallback` / custom `use*`). Descriptive
419    /// hotspot context for React components; omitted when zero (non-React).
420    #[serde(default, skip_serializing_if = "is_zero_u16")]
421    pub react_hook_count: u16,
422    /// Deepest JSX element nesting reached in this function's body. Descriptive
423    /// hotspot context; omitted when zero (renders no JSX).
424    #[serde(default, skip_serializing_if = "is_zero_u16")]
425    pub react_jsx_max_depth: u16,
426    /// Number of props destructured from this component's first parameter.
427    /// Descriptive hotspot context; omitted when zero.
428    #[serde(default, skip_serializing_if = "is_zero_u16")]
429    pub react_prop_count: u16,
430    /// Per-kind React hook breakdown (state/effect/memo/callback/custom) plus
431    /// the max `useEffect` dependency-array arity, derived from the cached
432    /// `hook_uses` IR at the health layer. Descriptive refinement of
433    /// `react_hook_count`; present only when at least one component-scope hook
434    /// was attributed, so non-React findings stay byte-identical.
435    #[serde(default, skip_serializing_if = "Option::is_none")]
436    pub react_hook_profile: Option<ReactHookProfile>,
437    /// Which metric crossed its threshold.
438    pub exceeded: ExceededThreshold,
439    /// Finding severity derived from how far thresholds were crossed.
440    pub severity: FindingSeverity,
441    /// Gate severity after the `complexity-*` rules and their
442    /// `overrides[].rules` entries: `error` fails the run, `warn` does not.
443    /// The most severe rule of the kinds in `exceeded` wins. It is separate
444    /// from the band in `severity`, which ranks the finding and does not gate
445    /// it. Absent in reports from older versions.
446    #[serde(default, skip_serializing_if = "Option::is_none")]
447    pub effective_severity: Option<fallow_types::output_dead_code::EffectiveSeverity>,
448    /// CRAP score (change risk anti-pattern), when coverage data exists.
449    #[serde(default, skip_serializing_if = "Option::is_none")]
450    pub crap: Option<f64>,
451    /// Mutation evidence of the function from a saved `fallow mutation`
452    /// report (`fallow health --mutation-report`). A separate value: it never
453    /// changes `crap` or the health score. Absent without the flag, and when
454    /// no function result of the report matches the finding.
455    #[serde(default, skip_serializing_if = "Option::is_none")]
456    pub mutation: Option<crate::HealthFindingMutation>,
457    /// Test coverage percentage (0-100) backing the CRAP score.
458    #[serde(default, skip_serializing_if = "Option::is_none")]
459    pub coverage_pct: Option<f64>,
460    /// Coverage tier bucket.
461    ///
462    /// Derived from `coverage_pct` when coverage was measured. When
463    /// `coverage_source` is estimated, `coverage_pct` is absent and the tier
464    /// describes the static estimate behind the CRAP score rather than an
465    /// observation, so read the two fields together.
466    #[serde(default, skip_serializing_if = "Option::is_none")]
467    pub coverage_tier: Option<CoverageTier>,
468    /// Provenance of the coverage signal.
469    #[serde(default, skip_serializing_if = "Option::is_none")]
470    pub coverage_source: Option<CoverageSource>,
471    /// Component file the inherited coverage estimate came from, for
472    /// component-inherited coverage.
473    #[serde(
474        default,
475        serialize_with = "fallow_types::serde_path::serialize_option",
476        skip_serializing_if = "Option::is_none"
477    )]
478    pub inherited_from: Option<std::path::PathBuf>,
479    /// Aggregate of the enclosing component's findings, when rolled up.
480    #[serde(default, skip_serializing_if = "Option::is_none")]
481    pub component_rollup: Option<ComponentRollup>,
482    /// Per-decision-point complexity breakdown explaining WHICH constructs drove
483    /// the cyclomatic and cognitive scores. Populated only when the caller opts
484    /// in via `health --complexity-breakdown`; empty (and omitted from JSON)
485    /// otherwise so default and CI output stay lean.
486    #[serde(default, skip_serializing_if = "Vec::is_empty")]
487    pub contributions: Vec<fallow_types::extract::ComplexityContribution>,
488    /// Resolved thresholds used for this finding when a config override changed
489    /// at least one ceiling. Omitted for findings using global thresholds.
490    #[serde(default, skip_serializing_if = "Option::is_none")]
491    pub effective_thresholds: Option<HealthEffectiveThresholds>,
492    /// Source of the effective thresholds. Omitted when thresholds are global.
493    #[serde(default, skip_serializing_if = "Option::is_none")]
494    pub threshold_source: Option<ThresholdSource>,
495}
496
497impl ComplexityViolation {
498    /// Whether the finding fails the run.
499    ///
500    /// A `warn` gate severity does not block. A finding without the field, for
501    /// example from an older saved report, blocks as before.
502    #[must_use]
503    pub fn blocks(&self) -> bool {
504        self.effective_severity != Some(fallow_types::output_dead_code::EffectiveSeverity::Warn)
505    }
506
507    /// Ceilings this finding was actually evaluated against: the per-file
508    /// `thresholdOverrides` result when an override matched, otherwise the
509    /// run's global summary ceilings.
510    ///
511    /// Every renderer that prints or compares a threshold must go through this
512    /// so a finding is never described against a ceiling it was not measured
513    /// with.
514    #[must_use]
515    pub fn resolved_thresholds(&self, summary: &HealthSummary) -> HealthEffectiveThresholds {
516        self.effective_thresholds
517            .unwrap_or(HealthEffectiveThresholds {
518                max_cyclomatic: summary.max_cyclomatic_threshold,
519                max_cognitive: summary.max_cognitive_threshold,
520                max_crap: summary.max_crap_threshold,
521                max_unit_size: summary.max_unit_size_threshold,
522            })
523    }
524}
525
526/// Default unit-size ceiling (`health.maxUnitSize`): functions over 60 lines of
527/// code are reported as oversized. Mirrors the config crate's default so
528/// renderers can fill an effective-thresholds fallback without a config handle.
529pub const DEFAULT_MAX_UNIT_SIZE: u32 = 60;
530
531/// Resolved thresholds used to evaluate a health finding.
532#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
533#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
534#[allow(
535    clippy::struct_field_names,
536    reason = "target-dependent clippy lint; wire fields mirror max_* config keys"
537)]
538pub struct HealthEffectiveThresholds {
539    /// Effective cyclomatic-complexity ceiling for the matched file.
540    pub max_cyclomatic: u16,
541    /// Effective cognitive-complexity ceiling for the matched file.
542    pub max_cognitive: u16,
543    /// Effective CRAP-score ceiling for the matched file.
544    pub max_crap: f64,
545    /// Effective unit-size ceiling (maximum function length in lines) for the
546    /// matched file, after applying any `thresholdOverrides` on top of the
547    /// global `health.maxUnitSize` default.
548    pub max_unit_size: u32,
549}
550
551/// Threshold values configured by a single override entry.
552#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
553#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
554#[allow(
555    clippy::struct_field_names,
556    reason = "target-dependent clippy lint; wire fields mirror max_* config keys"
557)]
558pub struct HealthConfiguredThresholds {
559    /// Cyclomatic ceiling set by the override, when it sets one.
560    #[serde(default, skip_serializing_if = "Option::is_none")]
561    pub max_cyclomatic: Option<u16>,
562    /// Cognitive ceiling set by the override, when it sets one.
563    #[serde(default, skip_serializing_if = "Option::is_none")]
564    pub max_cognitive: Option<u16>,
565    /// CRAP ceiling set by the override, when it sets one.
566    #[serde(default, skip_serializing_if = "Option::is_none")]
567    pub max_crap: Option<f64>,
568    /// Unit-size ceiling set by the override, when it sets one.
569    #[serde(default, skip_serializing_if = "Option::is_none")]
570    pub max_unit_size: Option<u32>,
571}
572
573/// Source for a finding's effective thresholds.
574#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
575#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
576#[serde(rename_all = "snake_case")]
577pub enum ThresholdSource {
578    /// A `thresholdOverrides` config entry changed at least one ceiling.
579    Override,
580}
581
582/// Lifecycle state for a configured threshold override.
583#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
584#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
585#[serde(rename_all = "snake_case")]
586pub enum ThresholdOverrideStatus {
587    /// The override matches a finding that still needs the raised ceiling.
588    Active,
589    /// The override is not what keeps the matched unit quiet, so it can go:
590    /// either the unit passes the global thresholds on its own, or an inline
591    /// suppression already covers it.
592    Stale,
593    /// The override raises the ceiling for this dimension but the matched code
594    /// still exceeds the raised value, so the finding survives the override.
595    /// Without this state the row was dropped entirely and a user saw no
596    /// feedback at all on an override that was in force (issue #2163).
597    Insufficient,
598    /// The override matches no analyzed file or function.
599    NoMatch,
600}
601
602/// Which threshold dimension a `thresholdOverrides` state row describes.
603///
604/// One configured override produces one row per dimension it participates in,
605/// because the complexity ceilings and the CRAP ceiling are evaluated
606/// independently: raising `maxCyclomatic` says nothing about whether the unit
607/// still breaches `maxCrap`.
608#[derive(
609    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
610)]
611#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
612#[serde(rename_all = "snake_case")]
613pub enum ThresholdOverrideDimension {
614    /// The structural ceilings: `maxCyclomatic`, `maxCognitive` and
615    /// `maxUnitSize`.
616    Complexity,
617    /// The `maxCrap` ceiling, and only that ceiling.
618    Crap,
619}
620
621/// Current complexity metrics for a matched threshold override entry.
622#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
623#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
624pub struct ThresholdOverrideMetrics {
625    /// Current cyclomatic complexity of the matched function.
626    pub cyclomatic: u16,
627    /// Current cognitive complexity of the matched function.
628    pub cognitive: u16,
629    /// Current CRAP score, when coverage data exists.
630    #[serde(default, skip_serializing_if = "Option::is_none")]
631    pub crap: Option<f64>,
632    /// Measured line count of the matched unit. Present on complexity rows,
633    /// where `maxUnitSize` participates in the dimension; absent on CRAP rows
634    /// and `<component>` rollup rows, which are never scored on unit size.
635    #[serde(default, skip_serializing_if = "Option::is_none")]
636    pub line_count: Option<u32>,
637}
638
639/// Report entry describing whether a threshold override is active, stale, or
640/// no longer matching any analyzed file or function.
641#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
642#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
643pub struct ThresholdOverrideState {
644    /// Lifecycle state of the override.
645    pub status: ThresholdOverrideStatus,
646    /// Index of the entry in the configured `thresholdOverrides` array.
647    /// Several rows can share one index when the override participates in more
648    /// than one dimension; group on this to count configured overrides.
649    pub override_index: usize,
650    /// Threshold dimension this row describes.
651    pub dimension: ThresholdOverrideDimension,
652    /// Dimensions the matched unit still breaches despite this override,
653    /// whether or not this override configures their ceilings. Non-empty means
654    /// raising the ceiling did not settle the matter: a complexity or CRAP
655    /// finding survived, or the unit is still longer than the resolved
656    /// `maxUnitSize`, which keeps it in the large-function list without
657    /// emitting a finding of its own.
658    #[serde(default, skip_serializing_if = "Vec::is_empty")]
659    pub outstanding: Vec<ThresholdOverrideDimension>,
660    /// Matched file path, when the override matched one.
661    #[serde(
662        default,
663        serialize_with = "fallow_types::serde_path::serialize_option",
664        skip_serializing_if = "Option::is_none"
665    )]
666    pub path: Option<std::path::PathBuf>,
667    /// Matched function name, for function-scoped overrides.
668    #[serde(default, skip_serializing_if = "Option::is_none")]
669    pub function: Option<String>,
670    /// 1-based line of the matched unit. Absent on `no_match` rows, which
671    /// describe an entry that matched nothing. Name alone is not an identity:
672    /// one file can hold several units sharing a name, so this pairs with
673    /// `col` to keep their rows distinct (issue #2163).
674    #[serde(default, skip_serializing_if = "Option::is_none")]
675    pub line: Option<u32>,
676    /// 0-based byte column of the matched unit. Absent on `no_match` rows.
677    #[serde(default, skip_serializing_if = "Option::is_none")]
678    pub col: Option<u32>,
679    /// Ceilings the override entry configures.
680    pub configured_thresholds: HealthConfiguredThresholds,
681    /// Ceilings in effect after applying the override to the defaults.
682    pub effective_thresholds: HealthEffectiveThresholds,
683    /// Current complexity metrics of the matched code, when matched.
684    #[serde(default, skip_serializing_if = "Option::is_none")]
685    pub metrics: Option<ThresholdOverrideMetrics>,
686    /// Human-readable explanation of the status.
687    #[serde(default, skip_serializing_if = "Option::is_none")]
688    pub reason: Option<String>,
689}
690
691impl ThresholdOverrideState {
692    /// Render the matched unit as `path:line:function`, given the path already
693    /// formatted for the target surface.
694    ///
695    /// Every renderer must go through this: two units sharing a name in one
696    /// file produce two rows, and without the position they print as the same
697    /// line (issue #2163).
698    #[must_use]
699    pub fn target_label(&self, display: &str) -> String {
700        let Some(name) = self.function.as_deref() else {
701            return display.to_owned();
702        };
703        self.line.map_or_else(
704            || format!("{display}:{name}"),
705            |line| format!("{display}:{line}:{name}"),
706        )
707    }
708}
709
710/// Component-level aggregate attached to a template complexity finding,
711/// pairing the template's scores with the worst class-side function.
712#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
713#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
714pub struct ComponentRollup {
715    /// Component name.
716    pub component: String,
717    /// Name of the worst-scoring function in the component class.
718    pub class_worst_function: String,
719    /// Cyclomatic complexity of that worst class function.
720    pub class_cyclomatic: u16,
721    /// Cognitive complexity of that worst class function.
722    pub class_cognitive: u16,
723    /// Template file path relative to the project root.
724    #[serde(serialize_with = "fallow_types::serde_path::serialize")]
725    pub template_path: std::path::PathBuf,
726    /// Cyclomatic complexity of the template.
727    pub template_cyclomatic: u16,
728    /// Cognitive complexity of the template.
729    pub template_cognitive: u16,
730}
731
732/// Which complexity threshold was exceeded.
733#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
734#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
735#[serde(rename_all = "snake_case")]
736pub enum ExceededThreshold {
737    /// Only cyclomatic exceeded.
738    Cyclomatic,
739    /// Only cognitive exceeded.
740    Cognitive,
741    /// Both cyclomatic and cognitive exceeded (may or may not also exceed CRAP).
742    Both,
743    /// Only CRAP exceeded (cyclomatic and cognitive are under threshold).
744    Crap,
745    /// Cyclomatic and CRAP exceeded.
746    CyclomaticCrap,
747    /// Cognitive and CRAP exceeded.
748    CognitiveCrap,
749    /// Cyclomatic, cognitive, and CRAP all exceeded.
750    All,
751}
752
753impl ExceededThreshold {
754    /// Classify a finding from which individual thresholds were exceeded.
755    ///
756    /// Panics if all three bools are false; callers are expected to only
757    /// construct an `ExceededThreshold` for findings that exceeded at least
758    /// one threshold.
759    #[must_use]
760    pub fn from_bools(cyclomatic: bool, cognitive: bool, crap: bool) -> Self {
761        match (cyclomatic, cognitive, crap) {
762            (true, true, true) => Self::All,
763            (true, true, false) => Self::Both,
764            (true, false, true) => Self::CyclomaticCrap,
765            (false, true, true) => Self::CognitiveCrap,
766            (true, false, false) => Self::Cyclomatic,
767            (false, true, false) => Self::Cognitive,
768            (false, false, true) => Self::Crap,
769            (false, false, false) => {
770                unreachable!("ExceededThreshold requires at least one threshold exceeded")
771            }
772        }
773    }
774
775    /// True when the cyclomatic threshold contributed to the finding.
776    #[must_use]
777    pub const fn includes_cyclomatic(self) -> bool {
778        matches!(
779            self,
780            Self::Cyclomatic | Self::Both | Self::CyclomaticCrap | Self::All
781        )
782    }
783
784    /// True when the cognitive threshold contributed to the finding.
785    #[must_use]
786    pub const fn includes_cognitive(self) -> bool {
787        matches!(
788            self,
789            Self::Cognitive | Self::Both | Self::CognitiveCrap | Self::All
790        )
791    }
792
793    /// True when the CRAP threshold contributed to the finding.
794    #[must_use]
795    pub const fn includes_crap(self) -> bool {
796        matches!(
797            self,
798            Self::Crap | Self::CyclomaticCrap | Self::CognitiveCrap | Self::All
799        )
800    }
801}
802
803/// Severity tier indicating how far a function exceeds complexity thresholds.
804///
805/// Determined by the highest tier reached across both cognitive and cyclomatic
806/// scores. Default thresholds: cognitive 25/40, cyclomatic 30/50.
807#[derive(
808    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
809)]
810#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
811#[serde(rename_all = "snake_case")]
812pub enum FindingSeverity {
813    /// Above threshold but manageable (cognitive < 25 or cyclomatic < 30).
814    Moderate,
815    /// Recommended for extraction (cognitive 25-39 or cyclomatic 30-49).
816    High,
817    /// Immediate extraction candidate (cognitive >= 40 or cyclomatic >= 50).
818    Critical,
819}
820
821/// CRAP score threshold for "high" severity. CC=7 untested -> 56, CC=10 -> 110.
822pub const DEFAULT_CRAP_HIGH: f64 = 50.0;
823
824/// CRAP score threshold for "critical" severity. CC=10 untested gives 110,
825/// CC=12 untested gives 156; 100 lands between the two and flags genuinely
826/// dangerous combinations of high complexity and low coverage.
827pub const DEFAULT_CRAP_CRITICAL: f64 = 100.0;
828
829/// Compute the severity tier for a complexity finding.
830///
831/// Uses the highest tier reached across cognitive, cyclomatic, and CRAP
832/// scores. Pass `None` for `crap` to skip the CRAP contribution (used when
833/// the finding was triggered by complexity thresholds only).
834#[expect(
835    clippy::too_many_arguments,
836    reason = "public library API for napi/embedders; the metric values and their high/critical threshold pairs are a stable positional contract that bundling would break"
837)]
838pub fn compute_finding_severity(
839    cognitive: u16,
840    cyclomatic: u16,
841    crap: Option<f64>,
842    cognitive_high: u16,
843    cognitive_critical: u16,
844    cyclomatic_high: u16,
845    cyclomatic_critical: u16,
846) -> FindingSeverity {
847    let cog = if cognitive >= cognitive_critical {
848        FindingSeverity::Critical
849    } else if cognitive >= cognitive_high {
850        FindingSeverity::High
851    } else {
852        FindingSeverity::Moderate
853    };
854
855    let cyc = if cyclomatic >= cyclomatic_critical {
856        FindingSeverity::Critical
857    } else if cyclomatic >= cyclomatic_high {
858        FindingSeverity::High
859    } else {
860        FindingSeverity::Moderate
861    };
862
863    let crap_sev = crap.map_or(FindingSeverity::Moderate, |c| {
864        if c >= DEFAULT_CRAP_CRITICAL {
865            FindingSeverity::Critical
866        } else if c >= DEFAULT_CRAP_HIGH {
867            FindingSeverity::High
868        } else {
869            FindingSeverity::Moderate
870        }
871    });
872
873    cog.max(cyc).max(crap_sev)
874}
875
876/// A function exceeding the very-high-risk size threshold (>60 LOC).
877#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
878#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
879pub struct LargeFunctionEntry {
880    /// File path relative to the project root.
881    #[serde(serialize_with = "fallow_types::serde_path::serialize")]
882    pub path: std::path::PathBuf,
883    /// Function name, or a synthesized name for anonymous functions.
884    pub name: String,
885    /// 1-based line the function starts on.
886    pub line: u32,
887    /// Lines of code in the function body.
888    pub line_count: u32,
889}
890
891/// Summary statistics for the health report.
892#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
893#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
894pub struct HealthSummary {
895    /// Files included in the health analysis.
896    pub files_analyzed: usize,
897    /// Functions and template units checked for threshold findings across the
898    /// analyzed files. Synthetic module-scope units are excluded. Cyclomatic
899    /// aggregates include module units too; `vital_signs.cyclomatic_population`
900    /// reports the disjoint authored-function, module, and template populations
901    /// behind those aggregates.
902    pub functions_analyzed: usize,
903    /// Functions exceeding at least one complexity or CRAP threshold.
904    pub functions_above_threshold: usize,
905    /// Global cyclomatic-complexity ceiling for this run.
906    pub max_cyclomatic_threshold: u16,
907    /// Global cognitive-complexity ceiling for this run.
908    pub max_cognitive_threshold: u16,
909    /// Global CRAP-score ceiling for this run.
910    pub max_crap_threshold: f64,
911    /// Effective global unit-size ceiling (`health.maxUnitSize`, maximum
912    /// function length in lines) for this run. Sits alongside the other three
913    /// `max_*_threshold` siblings so a consumer reading the summary sees every
914    /// configured threshold. Per-file `thresholdOverrides` are not reflected
915    /// here; this is the global default.
916    pub max_unit_size_threshold: u32,
917    /// Files with a computed maintainability score; absent when file scoring
918    /// did not run.
919    #[serde(default, skip_serializing_if = "Option::is_none")]
920    pub files_scored: Option<usize>,
921    /// Mean maintainability index over scored files (0-100).
922    #[serde(default, skip_serializing_if = "Option::is_none")]
923    pub average_maintainability: Option<f64>,
924    /// Coverage model behind the CRAP scores, when coverage was used.
925    #[serde(default, skip_serializing_if = "Option::is_none")]
926    pub coverage_model: Option<CoverageModel>,
927    /// Input format of the measured coverage (`istanbul` or `v8`). Present
928    /// only with `coverage_model: "istanbul"`.
929    #[serde(default, skip_serializing_if = "Option::is_none")]
930    pub coverage_input_format: Option<CoverageInputFormat>,
931    /// Whether CRAP findings mix coverage sources.
932    #[serde(default, skip_serializing_if = "Option::is_none")]
933    pub coverage_source_consistency: Option<CoverageSourceConsistency>,
934    /// Functions matched against the Istanbul coverage file, in Istanbul mode.
935    #[serde(default, skip_serializing_if = "Option::is_none")]
936    pub istanbul_matched: Option<usize>,
937    /// Functions in the Istanbul coverage file, in Istanbul mode.
938    #[serde(default, skip_serializing_if = "Option::is_none")]
939    pub istanbul_total: Option<usize>,
940    /// Analyzed files the Istanbul coverage file carried an entry for.
941    /// Read against `istanbul_files_total`, this separates a coverage file
942    /// that did not join from code the coverage file says nothing ran in.
943    #[serde(default, skip_serializing_if = "Option::is_none")]
944    pub istanbul_files_matched: Option<usize>,
945    /// Files described by the Istanbul coverage file, joined or not.
946    #[serde(default, skip_serializing_if = "Option::is_none")]
947    pub istanbul_files_total: Option<usize>,
948    /// Findings with critical severity.
949    pub severity_critical_count: usize,
950    /// Findings with high severity.
951    pub severity_high_count: usize,
952    /// Findings with moderate severity.
953    pub severity_moderate_count: usize,
954    /// Baseline staleness data, present only when a baseline was loaded.
955    #[serde(default, skip_serializing_if = "Option::is_none")]
956    pub baseline_staleness: Option<crate::BaselineStaleness>,
957}
958
959impl Default for HealthSummary {
960    fn default() -> Self {
961        Self {
962            files_analyzed: 0,
963            functions_analyzed: 0,
964            functions_above_threshold: 0,
965            max_cyclomatic_threshold: 20,
966            max_cognitive_threshold: 15,
967            max_crap_threshold: 30.0,
968            max_unit_size_threshold: DEFAULT_MAX_UNIT_SIZE,
969            files_scored: None,
970            average_maintainability: None,
971            coverage_model: None,
972            coverage_input_format: None,
973            coverage_source_consistency: None,
974            istanbul_matched: None,
975            istanbul_total: None,
976            istanbul_files_matched: None,
977            istanbul_files_total: None,
978            severity_critical_count: 0,
979            severity_high_count: 0,
980            severity_moderate_count: 0,
981            baseline_staleness: None,
982        }
983    }
984}
985
986/// Per-file health score combining complexity, coupling, and dead code metrics.
987#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
988#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
989pub struct FileHealthScore {
990    /// File path relative to the project root.
991    #[serde(serialize_with = "fallow_types::serde_path::serialize")]
992    pub path: std::path::PathBuf,
993    /// Modules importing this file.
994    pub fan_in: usize,
995    /// Modules this file imports.
996    pub fan_out: usize,
997    /// Unused exports as a fraction of the file's exports, in `[0, 1]`.
998    pub dead_code_ratio: f64,
999    /// Total cyclomatic complexity per line of code.
1000    pub complexity_density: f64,
1001    /// Maintainability index (0-100); higher is healthier.
1002    pub maintainability_index: f64,
1003    /// Summed cyclomatic complexity over all units, including module and template scope.
1004    pub total_cyclomatic: u32,
1005    /// Summed cognitive complexity over all units, including module and template scope.
1006    pub total_cognitive: u32,
1007    /// Complexity units in the file, including synthetic module and template units.
1008    pub function_count: usize,
1009    /// Lines of code in the file.
1010    pub lines: u32,
1011    /// Highest CRAP score among the file's functions. Always the raw measured
1012    /// value; threshold overrides and suppressions never rewrite it.
1013    pub crap_max: f64,
1014    /// Unsuppressed functions whose rounded CRAP score meets or exceeds their effective
1015    /// ceiling, resolved from `health.thresholdOverrides` over the global
1016    /// `maxCrap` / `--max-crap` value. Zero when CRAP enforcement is disabled
1017    /// (global ceiling `0`).
1018    pub crap_above_threshold: usize,
1019    /// Functions whose rounded CRAP score is at or above the canonical 30.0
1020    /// baseline but below their effective ceiling: the count the configuration
1021    /// let through. Stays `0` when the effective ceiling is stricter than 30.
1022    /// When CRAP enforcement is disabled (global ceiling `0`), counts every
1023    /// function at or above the canonical baseline. Omitted when zero.
1024    #[serde(default, skip_serializing_if = "is_zero_usize")]
1025    #[cfg_attr(feature = "schema", schemars(default))]
1026    pub crap_exempted: usize,
1027    /// Concrete scored functions accepted by a complexity suppression, including
1028    /// subthreshold functions and disabled-enforcement runs. Omitted when zero.
1029    /// May overlap with configured exemptions; the counts are not a partition.
1030    #[serde(default, skip_serializing_if = "is_zero_usize")]
1031    #[cfg_attr(feature = "schema", schemars(default))]
1032    pub crap_suppressed: usize,
1033    /// Highest rounded CRAP among unsuppressed scored functions, including
1034    /// subthreshold and configured-exempt functions. Present with the paired
1035    /// unsuppressed threshold whenever a scored suppression exists. Explicitly
1036    /// zero when every scored function is suppressed; raw crap_max is unchanged.
1037    #[serde(default, skip_serializing_if = "Option::is_none")]
1038    pub crap_unsuppressed_max: Option<f64>,
1039    /// Lowest effective ceiling among unsuppressed scored functions, or the run
1040    /// global when none remain. Emitted with crap_unsuppressed_max. Consumers
1041    /// receiving an absent or partial pair fall back to the complete legacy pair:
1042    /// crap_max and crap_effective_threshold (or the run global when absent).
1043    #[serde(default, skip_serializing_if = "Option::is_none")]
1044    pub crap_unsuppressed_effective_threshold: Option<f64>,
1045    /// Lowest effective CRAP ceiling among the file's functions, present only
1046    /// when it differs from the run global (`summary.max_crap_threshold`).
1047    /// Consumers fall back to `summary.max_crap_threshold` when absent.
1048    #[serde(default, skip_serializing_if = "Option::is_none")]
1049    pub crap_effective_threshold: Option<f64>,
1050}
1051
1052/// A hotspot: a file that is both complex and frequently changing.
1053#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1054#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1055pub struct HotspotEntry {
1056    /// File path relative to the project root.
1057    #[serde(serialize_with = "fallow_types::serde_path::serialize")]
1058    pub path: std::path::PathBuf,
1059    /// Churn-times-complexity hotspot score; higher is riskier.
1060    pub score: f64,
1061    /// Commits touching the file in the analysis window.
1062    pub commits: u32,
1063    /// Recency-weighted commit count.
1064    pub weighted_commits: f64,
1065    /// Lines added to the file in the analysis window.
1066    pub lines_added: u32,
1067    /// Lines deleted from the file in the analysis window.
1068    pub lines_deleted: u32,
1069    /// Total cyclomatic complexity per line of code.
1070    pub complexity_density: f64,
1071    /// Modules importing this file.
1072    pub fan_in: usize,
1073    /// Whether churn is rising, falling, or steady over the window.
1074    pub trend: fallow_types::churn::ChurnTrend,
1075    /// Change dispersion: the median number of analyzed files in the commits
1076    /// that changed this file, over the change coupling history window. Bulk
1077    /// commits above the coupling file cap are not counted. Absent when the
1078    /// history has no commit ids (for example imported churn without them).
1079    #[serde(default, skip_serializing_if = "Option::is_none")]
1080    pub median_files_per_commit: Option<f64>,
1081    /// Change dispersion: the median number of changed lines (added plus
1082    /// deleted, analyzed files only) in the commits that changed this file.
1083    /// Same window and rules as `median_files_per_commit`.
1084    #[serde(default, skip_serializing_if = "Option::is_none")]
1085    pub median_lines_per_commit: Option<f64>,
1086    /// Ownership metrics, when ownership analysis ran.
1087    #[serde(default, skip_serializing_if = "Option::is_none")]
1088    pub ownership: Option<OwnershipMetrics>,
1089    /// True for files matched by test-path patterns; omitted when false.
1090    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1091    #[cfg_attr(feature = "schema", schemars(default))]
1092    pub is_test_path: bool,
1093}
1094
1095/// One contributor row in ownership metrics.
1096#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1097#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1098pub struct ContributorEntry {
1099    /// Contributor identifier, encoded per `format`.
1100    pub identifier: String,
1101    /// How `identifier` is encoded (raw, handle, anonymized, or hash).
1102    pub format: ContributorIdentifierFormat,
1103    /// Contributor's share of the file's commits, in `[0, 1]`.
1104    pub share: f64,
1105    /// Days since the contributor's last commit to the file.
1106    pub stale_days: u64,
1107    /// Contributor's commits touching the file in the window.
1108    pub commits: u32,
1109}
1110
1111/// Encoding applied to a [`ContributorEntry::identifier`].
1112#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1113#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1114#[serde(rename_all = "kebab-case")]
1115pub enum ContributorIdentifierFormat {
1116    /// Raw git author identity.
1117    Raw,
1118    /// Platform handle, e.g. a GitHub username.
1119    Handle,
1120    /// Anonymized label that stays stable within the report.
1121    Anonymized,
1122    /// One-way hash of the identity.
1123    Hash,
1124}
1125
1126/// Ownership lifecycle state of a file.
1127#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1128#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1129#[serde(rename_all = "snake_case")]
1130pub enum OwnershipState {
1131    /// A declared or de-facto owner is still actively contributing.
1132    Active,
1133    /// No owner could be resolved.
1134    Unowned,
1135    /// The declared owner has stopped contributing.
1136    DeclaredInactive,
1137    /// Recent contributions come from outside the declared ownership.
1138    Drifting,
1139}
1140
1141/// Ownership metrics for a hotspot file, derived from git history and
1142/// CODEOWNERS declarations.
1143#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1144#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1145pub struct OwnershipMetrics {
1146    /// Minimum contributors covering half the file's commits.
1147    pub bus_factor: u32,
1148
1149    /// Distinct contributors touching the file in the window.
1150    pub contributor_count: u32,
1151
1152    /// Contributor with the largest commit share.
1153    pub top_contributor: ContributorEntry,
1154
1155    /// Contributors active in the recent window; omitted when empty.
1156    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1157    #[cfg_attr(feature = "schema", schemars(default))]
1158    pub recent_contributors: Vec<ContributorEntry>,
1159
1160    /// Contributors best positioned to review changes; omitted when empty.
1161    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1162    #[cfg_attr(feature = "schema", schemars(default))]
1163    pub suggested_reviewers: Vec<ContributorEntry>,
1164
1165    /// Owner declared in CODEOWNERS, when one matches the file.
1166    #[serde(default, skip_serializing_if = "Option::is_none")]
1167    pub declared_owner: Option<String>,
1168
1169    /// Whether no owner could be resolved; `null` when ownership resolution
1170    /// did not run.
1171    pub unowned: Option<bool>,
1172
1173    /// Ownership lifecycle state.
1174    pub ownership_state: OwnershipState,
1175
1176    /// True when recent contributions drift away from the declared ownership.
1177    pub drift: bool,
1178
1179    /// Human-readable explanation of the drift, when drifting.
1180    #[serde(default, skip_serializing_if = "Option::is_none")]
1181    pub drift_reason: Option<String>,
1182}
1183
1184/// Where the run's reference epoch came from.
1185///
1186/// Churn recency weighting and ownership staleness are measured against one
1187/// instant. `head_commit` and `environment` resolve to the same value on every
1188/// run over the same commit; `wall_clock` does not.
1189#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1190#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1191#[serde(rename_all = "snake_case")]
1192pub enum ClockSource {
1193    /// Pinned by the `FALLOW_CLOCK_EPOCH` environment variable.
1194    Environment,
1195    /// HEAD's committer timestamp.
1196    HeadCommit,
1197    /// The system wall clock, because no commit timestamp was readable.
1198    WallClock,
1199}
1200
1201/// The instant a run measured commit ages and staleness against.
1202///
1203/// A consumer reading `weighted_commits`, `stale_days`, or anything derived
1204/// from them needs to know whether re-running over the same commit yields the
1205/// same number. The human report says so in a warning that `--quiet` removes,
1206/// which left the JSON consumer, who cannot see stderr at all, with no way to
1207/// find out.
1208#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1209#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1210pub struct ClockProvenance {
1211    /// Which of the three sources supplied the epoch.
1212    pub source: ClockSource,
1213    /// The reference epoch itself, in unix seconds. Pass it back as
1214    /// `FALLOW_CLOCK_EPOCH` to reproduce this run's churn-derived numbers.
1215    pub epoch_secs: u64,
1216    /// False only for `wall_clock`, where the numbers drift between runs.
1217    pub reproducible: bool,
1218}
1219
1220/// Scope metadata for the hotspot analysis.
1221#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1222#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1223pub struct HotspotSummary {
1224    /// Start of the churn window, as passed to `git log --since`.
1225    pub since: String,
1226    /// Minimum commit count for a file to qualify as a hotspot.
1227    pub min_commits: u32,
1228    /// Files with churn data in the window.
1229    pub files_analyzed: usize,
1230    /// Files excluded by test-path and ignore filters.
1231    pub files_excluded: usize,
1232    /// True when the repository is a shallow clone, so churn counts are
1233    /// truncated.
1234    pub shallow_clone: bool,
1235    /// Provenance of the instant every churn and staleness number was measured
1236    /// against. Absent only when a caller assembled a summary without one.
1237    #[serde(default, skip_serializing_if = "Option::is_none")]
1238    pub clock: Option<ClockProvenance>,
1239}
1240
1241#[cfg(test)]
1242mod tests {
1243    use super::*;
1244
1245    #[test]
1246    fn file_score_suppression_metadata_preserves_legacy_and_explicit_zero() {
1247        let legacy = serde_json::json!({
1248            "path": "src/legacy.ts", "fan_in": 1, "fan_out": 0,
1249            "dead_code_ratio": 0.0, "complexity_density": 0.77, "maintainability_index": 88.0,
1250            "total_cyclomatic": 20, "total_cognitive": 18, "function_count": 2, "lines": 26,
1251            "crap_max": 110.0, "crap_above_threshold": 0
1252        });
1253        let restored: FileHealthScore =
1254            serde_json::from_value(legacy.clone()).expect("legacy file score");
1255        assert_eq!(restored.crap_suppressed, 0);
1256        assert_eq!(
1257            serde_json::to_value(restored).expect("serialize legacy file score"),
1258            legacy
1259        );
1260
1261        let mut suppressed = legacy;
1262        suppressed["crap_suppressed"] = serde_json::json!(2);
1263        suppressed["crap_unsuppressed_max"] = serde_json::json!(0.0);
1264        suppressed["crap_unsuppressed_effective_threshold"] = serde_json::json!(30.0);
1265        suppressed["crap_exempted"] = serde_json::json!(1);
1266        suppressed["crap_effective_threshold"] = serde_json::json!(500.0);
1267        let restored: FileHealthScore =
1268            serde_json::from_value(suppressed.clone()).expect("suppressed file score");
1269        assert_eq!(restored.crap_max, 110.0);
1270        assert_eq!(restored.crap_unsuppressed_max, Some(0.0));
1271        assert_eq!(restored.crap_unsuppressed_effective_threshold, Some(30.0));
1272        assert_eq!(
1273            serde_json::to_value(restored).expect("serialize suppressed file score"),
1274            suppressed
1275        );
1276    }
1277
1278    /// The three tokens are the wire contract a consumer branches on, so they
1279    /// are pinned here rather than left to the derive.
1280    #[test]
1281    fn clock_source_serializes_as_snake_case_tokens() {
1282        let tokens: Vec<String> = [
1283            ClockSource::Environment,
1284            ClockSource::HeadCommit,
1285            ClockSource::WallClock,
1286        ]
1287        .into_iter()
1288        .map(|source| serde_json::to_string(&source).expect("clock source should serialize"))
1289        .collect();
1290        assert_eq!(
1291            tokens,
1292            [r#""environment""#, r#""head_commit""#, r#""wall_clock""#]
1293        );
1294    }
1295
1296    /// A summary without a clock stays byte-identical to the shape consumers
1297    /// already parse; one with a clock publishes all three members.
1298    #[test]
1299    fn hotspot_summary_clock_is_omitted_when_absent_and_complete_when_present() {
1300        let mut summary = HotspotSummary {
1301            since: "6 months".to_owned(),
1302            min_commits: 3,
1303            files_analyzed: 4,
1304            files_excluded: 1,
1305            shallow_clone: false,
1306            clock: None,
1307        };
1308        let json = serde_json::to_string(&summary).expect("summary should serialize");
1309        assert!(!json.contains("clock"), "{json}");
1310
1311        summary.clock = Some(ClockProvenance {
1312            source: ClockSource::WallClock,
1313            epoch_secs: 1_788_782_400,
1314            reproducible: false,
1315        });
1316        let value: serde_json::Value =
1317            serde_json::to_value(&summary).expect("summary should serialize");
1318        assert_eq!(value["clock"]["source"], "wall_clock");
1319        assert_eq!(value["clock"]["epoch_secs"], 1_788_782_400_u64);
1320        assert_eq!(value["clock"]["reproducible"], false);
1321    }
1322
1323    #[test]
1324    fn exceeded_threshold_serializes_as_snake_case() {
1325        let json = serde_json::to_string(&ExceededThreshold::Both)
1326            .expect("threshold variant should serialize");
1327        assert_eq!(json, r#""both""#);
1328
1329        let json = serde_json::to_string(&ExceededThreshold::Cyclomatic)
1330            .expect("threshold variant should serialize");
1331        assert_eq!(json, r#""cyclomatic""#);
1332    }
1333
1334    #[test]
1335    fn exceeded_threshold_all_variants_serialize() {
1336        for (variant, expected) in [
1337            (ExceededThreshold::Cyclomatic, r#""cyclomatic""#),
1338            (ExceededThreshold::Cognitive, r#""cognitive""#),
1339            (ExceededThreshold::Both, r#""both""#),
1340            (ExceededThreshold::Crap, r#""crap""#),
1341            (ExceededThreshold::CyclomaticCrap, r#""cyclomatic_crap""#),
1342            (ExceededThreshold::CognitiveCrap, r#""cognitive_crap""#),
1343            (ExceededThreshold::All, r#""all""#),
1344        ] {
1345            let json = serde_json::to_string(&variant).expect("threshold variant should serialize");
1346            assert_eq!(json, expected, "wire form for {variant:?} should be stable");
1347        }
1348    }
1349
1350    #[test]
1351    fn letter_grade_boundaries() {
1352        assert_eq!(letter_grade(100.0), "A");
1353        assert_eq!(letter_grade(85.0), "A");
1354        assert_eq!(letter_grade(84.9), "B");
1355        assert_eq!(letter_grade(70.0), "B");
1356        assert_eq!(letter_grade(69.9), "C");
1357        assert_eq!(letter_grade(55.0), "C");
1358        assert_eq!(letter_grade(54.9), "D");
1359        assert_eq!(letter_grade(40.0), "D");
1360        assert_eq!(letter_grade(39.9), "F");
1361        assert_eq!(letter_grade(0.0), "F");
1362    }
1363
1364    #[test]
1365    fn coverage_tier_boundaries() {
1366        assert_eq!(CoverageTier::from_pct(0.0), CoverageTier::None);
1367        assert_eq!(CoverageTier::from_pct(0.1), CoverageTier::Partial);
1368        assert_eq!(CoverageTier::from_pct(69.9), CoverageTier::Partial);
1369        assert_eq!(CoverageTier::from_pct(70.0), CoverageTier::High);
1370        assert_eq!(CoverageTier::from_pct(100.0), CoverageTier::High);
1371    }
1372
1373    #[test]
1374    fn hotspot_score_threshold_is_50() {
1375        assert!((HOTSPOT_SCORE_THRESHOLD - 50.0).abs() < f64::EPSILON);
1376    }
1377
1378    #[test]
1379    fn health_score_serializes_correctly() {
1380        let score = HealthScore {
1381            formula_version: HEALTH_SCORE_FORMULA_VERSION,
1382            score: 78.5,
1383            grade: "B",
1384            penalties: HealthScorePenalties {
1385                dead_files: Some(3.1),
1386                dead_exports: Some(6.0),
1387                complexity: 0.0,
1388                p90_complexity: 0.0,
1389                maintainability: None,
1390                hotspots: None,
1391                unused_deps: Some(5.0),
1392                circular_deps: Some(4.0),
1393                unit_size: None,
1394                coupling: None,
1395                duplication: None,
1396                prop_drilling: None,
1397            },
1398        };
1399        let json = serde_json::to_string(&score).expect("health score should serialize");
1400        let parsed: serde_json::Value =
1401            serde_json::from_str(&json).expect("health score JSON should parse");
1402        assert_eq!(parsed["formula_version"], HEALTH_SCORE_FORMULA_VERSION);
1403        assert_eq!(parsed["score"], 78.5);
1404        assert_eq!(parsed["grade"], "B");
1405        assert_eq!(parsed["penalties"]["dead_files"], 3.1);
1406        assert!(!json.contains("maintainability"));
1407        assert!(!json.contains("hotspots"));
1408        assert!(!json.contains("duplication"));
1409    }
1410
1411    #[test]
1412    fn styling_health_serializes_correctly() {
1413        let styling = StylingHealth {
1414            formula_version: STYLING_HEALTH_FORMULA_VERSION,
1415            score: 72.0,
1416            grade: "B",
1417            penalties: StylingHealthPenalties {
1418                duplication: 12.0,
1419                dead_surface: 8.0,
1420                broken_references: 4.0,
1421                token_erosion: 2.0,
1422                structural: 2.0,
1423            },
1424            confidence: StylingHealthConfidence::High,
1425            confidence_reason: None,
1426        };
1427        let json = serde_json::to_string(&styling).expect("styling health should serialize");
1428        let parsed: serde_json::Value =
1429            serde_json::from_str(&json).expect("styling health JSON should parse");
1430        assert_eq!(parsed["formula_version"], STYLING_HEALTH_FORMULA_VERSION);
1431        assert_eq!(parsed["score"], 72.0);
1432        assert_eq!(parsed["grade"], "B");
1433        assert_eq!(parsed["penalties"]["duplication"], 12.0);
1434        assert_eq!(parsed["penalties"]["dead_surface"], 8.0);
1435        assert_eq!(parsed["penalties"]["broken_references"], 4.0);
1436        assert_eq!(parsed["penalties"]["token_erosion"], 2.0);
1437        assert_eq!(parsed["penalties"]["structural"], 2.0);
1438        // `high` confidence omits the reason; the enum serializes lowercase.
1439        assert_eq!(parsed["confidence"], "high");
1440        assert!(parsed.get("confidence_reason").is_none());
1441    }
1442
1443    #[test]
1444    fn styling_health_low_confidence_serializes_reason() {
1445        let styling = StylingHealth {
1446            formula_version: STYLING_HEALTH_FORMULA_VERSION,
1447            score: 89.0,
1448            grade: "A",
1449            penalties: StylingHealthPenalties {
1450                duplication: 0.0,
1451                dead_surface: 0.0,
1452                broken_references: 0.0,
1453                token_erosion: 0.0,
1454                structural: 0.0,
1455            },
1456            confidence: StylingHealthConfidence::Low,
1457            confidence_reason: Some("graded from only 24 declarations across 2 stylesheets".into()),
1458        };
1459        let json = serde_json::to_string(&styling).expect("styling health should serialize");
1460        let parsed: serde_json::Value =
1461            serde_json::from_str(&json).expect("styling health JSON should parse");
1462        assert_eq!(parsed["confidence"], "low");
1463        assert_eq!(
1464            parsed["confidence_reason"],
1465            "graded from only 24 declarations across 2 stylesheets"
1466        );
1467    }
1468
1469    #[test]
1470    fn coverage_model_serializes_as_snake_case() {
1471        let json = serde_json::to_string(&CoverageModel::StaticBinary)
1472            .expect("coverage model should serialize");
1473        assert_eq!(json, r#""static_binary""#);
1474
1475        let json = serde_json::to_string(&CoverageModel::StaticEstimated)
1476            .expect("coverage model should serialize");
1477        assert_eq!(json, r#""static_estimated""#);
1478
1479        let json = serde_json::to_string(&CoverageModel::Istanbul)
1480            .expect("coverage model should serialize");
1481        assert_eq!(json, r#""istanbul""#);
1482    }
1483
1484    #[test]
1485    fn finding_severity_serializes_as_snake_case() {
1486        assert_eq!(
1487            serde_json::to_string(&FindingSeverity::Moderate)
1488                .expect("finding severity should serialize"),
1489            r#""moderate""#,
1490        );
1491        assert_eq!(
1492            serde_json::to_string(&FindingSeverity::High)
1493                .expect("finding severity should serialize"),
1494            r#""high""#,
1495        );
1496        assert_eq!(
1497            serde_json::to_string(&FindingSeverity::Critical)
1498                .expect("finding severity should serialize"),
1499            r#""critical""#,
1500        );
1501    }
1502
1503    #[test]
1504    fn finding_severity_ordering() {
1505        assert!(FindingSeverity::Moderate < FindingSeverity::High);
1506        assert!(FindingSeverity::High < FindingSeverity::Critical);
1507    }
1508
1509    #[test]
1510    fn compute_severity_moderate_when_below_high_thresholds() {
1511        let severity = compute_finding_severity(20, 25, None, 25, 40, 30, 50);
1512        assert_eq!(severity, FindingSeverity::Moderate);
1513    }
1514
1515    #[test]
1516    fn compute_severity_high_from_cognitive() {
1517        let severity = compute_finding_severity(25, 20, None, 25, 40, 30, 50);
1518        assert_eq!(severity, FindingSeverity::High);
1519    }
1520
1521    #[test]
1522    fn compute_severity_high_from_cyclomatic() {
1523        let severity = compute_finding_severity(20, 30, None, 25, 40, 30, 50);
1524        assert_eq!(severity, FindingSeverity::High);
1525    }
1526
1527    #[test]
1528    fn compute_severity_critical_from_cognitive() {
1529        let severity = compute_finding_severity(40, 20, None, 25, 40, 30, 50);
1530        assert_eq!(severity, FindingSeverity::Critical);
1531    }
1532
1533    #[test]
1534    fn compute_severity_critical_from_cyclomatic() {
1535        let severity = compute_finding_severity(20, 50, None, 25, 40, 30, 50);
1536        assert_eq!(severity, FindingSeverity::Critical);
1537    }
1538
1539    #[test]
1540    fn compute_severity_uses_highest_across_dimensions() {
1541        let severity = compute_finding_severity(45, 20, None, 25, 40, 30, 50);
1542        assert_eq!(severity, FindingSeverity::Critical);
1543    }
1544
1545    #[test]
1546    fn compute_severity_at_exact_boundaries() {
1547        let severity = compute_finding_severity(25, 30, None, 25, 40, 30, 50);
1548        assert_eq!(severity, FindingSeverity::High);
1549
1550        let severity = compute_finding_severity(24, 29, None, 25, 40, 30, 50);
1551        assert_eq!(severity, FindingSeverity::Moderate);
1552
1553        let severity = compute_finding_severity(40, 50, None, 25, 40, 30, 50);
1554        assert_eq!(severity, FindingSeverity::Critical);
1555    }
1556
1557    #[test]
1558    fn compute_severity_crap_contributes_high() {
1559        let severity = compute_finding_severity(10, 10, Some(60.0), 25, 40, 30, 50);
1560        assert_eq!(severity, FindingSeverity::High);
1561    }
1562
1563    #[test]
1564    fn compute_severity_crap_contributes_critical() {
1565        let severity = compute_finding_severity(10, 10, Some(120.0), 25, 40, 30, 50);
1566        assert_eq!(severity, FindingSeverity::Critical);
1567    }
1568
1569    #[test]
1570    fn compute_severity_crap_moderate_under_high() {
1571        let severity = compute_finding_severity(10, 10, Some(30.0), 25, 40, 30, 50);
1572        assert_eq!(severity, FindingSeverity::Moderate);
1573    }
1574
1575    #[test]
1576    fn exceeded_threshold_from_bools() {
1577        assert!(matches!(
1578            ExceededThreshold::from_bools(true, false, false),
1579            ExceededThreshold::Cyclomatic
1580        ));
1581        assert!(matches!(
1582            ExceededThreshold::from_bools(true, true, true),
1583            ExceededThreshold::All
1584        ));
1585        assert!(matches!(
1586            ExceededThreshold::from_bools(false, false, true),
1587            ExceededThreshold::Crap
1588        ));
1589        assert!(matches!(
1590            ExceededThreshold::from_bools(true, false, true),
1591            ExceededThreshold::CyclomaticCrap
1592        ));
1593    }
1594
1595    #[test]
1596    fn exceeded_threshold_includes_helpers() {
1597        let all = ExceededThreshold::All;
1598        assert!(all.includes_cyclomatic());
1599        assert!(all.includes_cognitive());
1600        assert!(all.includes_crap());
1601
1602        let crap_only = ExceededThreshold::Crap;
1603        assert!(!crap_only.includes_cyclomatic());
1604        assert!(!crap_only.includes_cognitive());
1605        assert!(crap_only.includes_crap());
1606
1607        assert!(ExceededThreshold::CyclomaticCrap.includes_crap());
1608        assert!(ExceededThreshold::CognitiveCrap.includes_crap());
1609        assert!(!ExceededThreshold::Both.includes_crap());
1610        assert!(!ExceededThreshold::Cyclomatic.includes_crap());
1611        assert!(!ExceededThreshold::Cognitive.includes_crap());
1612    }
1613
1614    #[test]
1615    fn coverage_source_consistency_omits_empty_sources() {
1616        let sources = Vec::new();
1617        assert_eq!(summarize_coverage_source_consistency(sources), None);
1618    }
1619
1620    #[test]
1621    fn coverage_source_consistency_reports_uniform_sources() {
1622        assert_eq!(
1623            summarize_coverage_source_consistency([
1624                CoverageSource::Estimated,
1625                CoverageSource::Estimated,
1626            ]),
1627            Some(CoverageSourceConsistency::Uniform)
1628        );
1629    }
1630
1631    #[test]
1632    fn coverage_source_consistency_reports_mixed_sources() {
1633        assert_eq!(
1634            summarize_coverage_source_consistency([
1635                CoverageSource::Istanbul,
1636                CoverageSource::Estimated,
1637            ]),
1638            Some(CoverageSourceConsistency::Mixed)
1639        );
1640    }
1641}