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 /// Test coverage percentage (0-100) backing the CRAP score.
452 #[serde(default, skip_serializing_if = "Option::is_none")]
453 pub coverage_pct: Option<f64>,
454 /// Coverage tier bucket.
455 ///
456 /// Derived from `coverage_pct` when coverage was measured. When
457 /// `coverage_source` is estimated, `coverage_pct` is absent and the tier
458 /// describes the static estimate behind the CRAP score rather than an
459 /// observation, so read the two fields together.
460 #[serde(default, skip_serializing_if = "Option::is_none")]
461 pub coverage_tier: Option<CoverageTier>,
462 /// Provenance of the coverage signal.
463 #[serde(default, skip_serializing_if = "Option::is_none")]
464 pub coverage_source: Option<CoverageSource>,
465 /// Component file the inherited coverage estimate came from, for
466 /// component-inherited coverage.
467 #[serde(
468 default,
469 serialize_with = "fallow_types::serde_path::serialize_option",
470 skip_serializing_if = "Option::is_none"
471 )]
472 pub inherited_from: Option<std::path::PathBuf>,
473 /// Aggregate of the enclosing component's findings, when rolled up.
474 #[serde(default, skip_serializing_if = "Option::is_none")]
475 pub component_rollup: Option<ComponentRollup>,
476 /// Per-decision-point complexity breakdown explaining WHICH constructs drove
477 /// the cyclomatic and cognitive scores. Populated only when the caller opts
478 /// in via `health --complexity-breakdown`; empty (and omitted from JSON)
479 /// otherwise so default and CI output stay lean.
480 #[serde(default, skip_serializing_if = "Vec::is_empty")]
481 pub contributions: Vec<fallow_types::extract::ComplexityContribution>,
482 /// Resolved thresholds used for this finding when a config override changed
483 /// at least one ceiling. Omitted for findings using global thresholds.
484 #[serde(default, skip_serializing_if = "Option::is_none")]
485 pub effective_thresholds: Option<HealthEffectiveThresholds>,
486 /// Source of the effective thresholds. Omitted when thresholds are global.
487 #[serde(default, skip_serializing_if = "Option::is_none")]
488 pub threshold_source: Option<ThresholdSource>,
489}
490
491impl ComplexityViolation {
492 /// Whether the finding fails the run.
493 ///
494 /// A `warn` gate severity does not block. A finding without the field, for
495 /// example from an older saved report, blocks as before.
496 #[must_use]
497 pub fn blocks(&self) -> bool {
498 self.effective_severity != Some(fallow_types::output_dead_code::EffectiveSeverity::Warn)
499 }
500
501 /// Ceilings this finding was actually evaluated against: the per-file
502 /// `thresholdOverrides` result when an override matched, otherwise the
503 /// run's global summary ceilings.
504 ///
505 /// Every renderer that prints or compares a threshold must go through this
506 /// so a finding is never described against a ceiling it was not measured
507 /// with.
508 #[must_use]
509 pub fn resolved_thresholds(&self, summary: &HealthSummary) -> HealthEffectiveThresholds {
510 self.effective_thresholds
511 .unwrap_or(HealthEffectiveThresholds {
512 max_cyclomatic: summary.max_cyclomatic_threshold,
513 max_cognitive: summary.max_cognitive_threshold,
514 max_crap: summary.max_crap_threshold,
515 max_unit_size: summary.max_unit_size_threshold,
516 })
517 }
518}
519
520/// Default unit-size ceiling (`health.maxUnitSize`): functions over 60 lines of
521/// code are reported as oversized. Mirrors the config crate's default so
522/// renderers can fill an effective-thresholds fallback without a config handle.
523pub const DEFAULT_MAX_UNIT_SIZE: u32 = 60;
524
525/// Resolved thresholds used to evaluate a health finding.
526#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
527#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
528#[allow(
529 clippy::struct_field_names,
530 reason = "target-dependent clippy lint; wire fields mirror max_* config keys"
531)]
532pub struct HealthEffectiveThresholds {
533 /// Effective cyclomatic-complexity ceiling for the matched file.
534 pub max_cyclomatic: u16,
535 /// Effective cognitive-complexity ceiling for the matched file.
536 pub max_cognitive: u16,
537 /// Effective CRAP-score ceiling for the matched file.
538 pub max_crap: f64,
539 /// Effective unit-size ceiling (maximum function length in lines) for the
540 /// matched file, after applying any `thresholdOverrides` on top of the
541 /// global `health.maxUnitSize` default.
542 pub max_unit_size: u32,
543}
544
545/// Threshold values configured by a single override entry.
546#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
547#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
548#[allow(
549 clippy::struct_field_names,
550 reason = "target-dependent clippy lint; wire fields mirror max_* config keys"
551)]
552pub struct HealthConfiguredThresholds {
553 /// Cyclomatic ceiling set by the override, when it sets one.
554 #[serde(default, skip_serializing_if = "Option::is_none")]
555 pub max_cyclomatic: Option<u16>,
556 /// Cognitive ceiling set by the override, when it sets one.
557 #[serde(default, skip_serializing_if = "Option::is_none")]
558 pub max_cognitive: Option<u16>,
559 /// CRAP ceiling set by the override, when it sets one.
560 #[serde(default, skip_serializing_if = "Option::is_none")]
561 pub max_crap: Option<f64>,
562 /// Unit-size ceiling set by the override, when it sets one.
563 #[serde(default, skip_serializing_if = "Option::is_none")]
564 pub max_unit_size: Option<u32>,
565}
566
567/// Source for a finding's effective thresholds.
568#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
569#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
570#[serde(rename_all = "snake_case")]
571pub enum ThresholdSource {
572 /// A `thresholdOverrides` config entry changed at least one ceiling.
573 Override,
574}
575
576/// Lifecycle state for a configured threshold override.
577#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
578#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
579#[serde(rename_all = "snake_case")]
580pub enum ThresholdOverrideStatus {
581 /// The override matches a finding that still needs the raised ceiling.
582 Active,
583 /// The override is not what keeps the matched unit quiet, so it can go:
584 /// either the unit passes the global thresholds on its own, or an inline
585 /// suppression already covers it.
586 Stale,
587 /// The override raises the ceiling for this dimension but the matched code
588 /// still exceeds the raised value, so the finding survives the override.
589 /// Without this state the row was dropped entirely and a user saw no
590 /// feedback at all on an override that was in force (issue #2163).
591 Insufficient,
592 /// The override matches no analyzed file or function.
593 NoMatch,
594}
595
596/// Which threshold dimension a `thresholdOverrides` state row describes.
597///
598/// One configured override produces one row per dimension it participates in,
599/// because the complexity ceilings and the CRAP ceiling are evaluated
600/// independently: raising `maxCyclomatic` says nothing about whether the unit
601/// still breaches `maxCrap`.
602#[derive(
603 Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
604)]
605#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
606#[serde(rename_all = "snake_case")]
607pub enum ThresholdOverrideDimension {
608 /// The structural ceilings: `maxCyclomatic`, `maxCognitive` and
609 /// `maxUnitSize`.
610 Complexity,
611 /// The `maxCrap` ceiling, and only that ceiling.
612 Crap,
613}
614
615/// Current complexity metrics for a matched threshold override entry.
616#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
617#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
618pub struct ThresholdOverrideMetrics {
619 /// Current cyclomatic complexity of the matched function.
620 pub cyclomatic: u16,
621 /// Current cognitive complexity of the matched function.
622 pub cognitive: u16,
623 /// Current CRAP score, when coverage data exists.
624 #[serde(default, skip_serializing_if = "Option::is_none")]
625 pub crap: Option<f64>,
626 /// Measured line count of the matched unit. Present on complexity rows,
627 /// where `maxUnitSize` participates in the dimension; absent on CRAP rows
628 /// and `<component>` rollup rows, which are never scored on unit size.
629 #[serde(default, skip_serializing_if = "Option::is_none")]
630 pub line_count: Option<u32>,
631}
632
633/// Report entry describing whether a threshold override is active, stale, or
634/// no longer matching any analyzed file or function.
635#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
636#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
637pub struct ThresholdOverrideState {
638 /// Lifecycle state of the override.
639 pub status: ThresholdOverrideStatus,
640 /// Index of the entry in the configured `thresholdOverrides` array.
641 /// Several rows can share one index when the override participates in more
642 /// than one dimension; group on this to count configured overrides.
643 pub override_index: usize,
644 /// Threshold dimension this row describes.
645 pub dimension: ThresholdOverrideDimension,
646 /// Dimensions the matched unit still breaches despite this override,
647 /// whether or not this override configures their ceilings. Non-empty means
648 /// raising the ceiling did not settle the matter: a complexity or CRAP
649 /// finding survived, or the unit is still longer than the resolved
650 /// `maxUnitSize`, which keeps it in the large-function list without
651 /// emitting a finding of its own.
652 #[serde(default, skip_serializing_if = "Vec::is_empty")]
653 pub outstanding: Vec<ThresholdOverrideDimension>,
654 /// Matched file path, when the override matched one.
655 #[serde(
656 default,
657 serialize_with = "fallow_types::serde_path::serialize_option",
658 skip_serializing_if = "Option::is_none"
659 )]
660 pub path: Option<std::path::PathBuf>,
661 /// Matched function name, for function-scoped overrides.
662 #[serde(default, skip_serializing_if = "Option::is_none")]
663 pub function: Option<String>,
664 /// 1-based line of the matched unit. Absent on `no_match` rows, which
665 /// describe an entry that matched nothing. Name alone is not an identity:
666 /// one file can hold several units sharing a name, so this pairs with
667 /// `col` to keep their rows distinct (issue #2163).
668 #[serde(default, skip_serializing_if = "Option::is_none")]
669 pub line: Option<u32>,
670 /// 0-based byte column of the matched unit. Absent on `no_match` rows.
671 #[serde(default, skip_serializing_if = "Option::is_none")]
672 pub col: Option<u32>,
673 /// Ceilings the override entry configures.
674 pub configured_thresholds: HealthConfiguredThresholds,
675 /// Ceilings in effect after applying the override to the defaults.
676 pub effective_thresholds: HealthEffectiveThresholds,
677 /// Current complexity metrics of the matched code, when matched.
678 #[serde(default, skip_serializing_if = "Option::is_none")]
679 pub metrics: Option<ThresholdOverrideMetrics>,
680 /// Human-readable explanation of the status.
681 #[serde(default, skip_serializing_if = "Option::is_none")]
682 pub reason: Option<String>,
683}
684
685impl ThresholdOverrideState {
686 /// Render the matched unit as `path:line:function`, given the path already
687 /// formatted for the target surface.
688 ///
689 /// Every renderer must go through this: two units sharing a name in one
690 /// file produce two rows, and without the position they print as the same
691 /// line (issue #2163).
692 #[must_use]
693 pub fn target_label(&self, display: &str) -> String {
694 let Some(name) = self.function.as_deref() else {
695 return display.to_owned();
696 };
697 self.line.map_or_else(
698 || format!("{display}:{name}"),
699 |line| format!("{display}:{line}:{name}"),
700 )
701 }
702}
703
704/// Component-level aggregate attached to a template complexity finding,
705/// pairing the template's scores with the worst class-side function.
706#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
707#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
708pub struct ComponentRollup {
709 /// Component name.
710 pub component: String,
711 /// Name of the worst-scoring function in the component class.
712 pub class_worst_function: String,
713 /// Cyclomatic complexity of that worst class function.
714 pub class_cyclomatic: u16,
715 /// Cognitive complexity of that worst class function.
716 pub class_cognitive: u16,
717 /// Template file path relative to the project root.
718 #[serde(serialize_with = "fallow_types::serde_path::serialize")]
719 pub template_path: std::path::PathBuf,
720 /// Cyclomatic complexity of the template.
721 pub template_cyclomatic: u16,
722 /// Cognitive complexity of the template.
723 pub template_cognitive: u16,
724}
725
726/// Which complexity threshold was exceeded.
727#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
728#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
729#[serde(rename_all = "snake_case")]
730pub enum ExceededThreshold {
731 /// Only cyclomatic exceeded.
732 Cyclomatic,
733 /// Only cognitive exceeded.
734 Cognitive,
735 /// Both cyclomatic and cognitive exceeded (may or may not also exceed CRAP).
736 Both,
737 /// Only CRAP exceeded (cyclomatic and cognitive are under threshold).
738 Crap,
739 /// Cyclomatic and CRAP exceeded.
740 CyclomaticCrap,
741 /// Cognitive and CRAP exceeded.
742 CognitiveCrap,
743 /// Cyclomatic, cognitive, and CRAP all exceeded.
744 All,
745}
746
747impl ExceededThreshold {
748 /// Classify a finding from which individual thresholds were exceeded.
749 ///
750 /// Panics if all three bools are false; callers are expected to only
751 /// construct an `ExceededThreshold` for findings that exceeded at least
752 /// one threshold.
753 #[must_use]
754 pub fn from_bools(cyclomatic: bool, cognitive: bool, crap: bool) -> Self {
755 match (cyclomatic, cognitive, crap) {
756 (true, true, true) => Self::All,
757 (true, true, false) => Self::Both,
758 (true, false, true) => Self::CyclomaticCrap,
759 (false, true, true) => Self::CognitiveCrap,
760 (true, false, false) => Self::Cyclomatic,
761 (false, true, false) => Self::Cognitive,
762 (false, false, true) => Self::Crap,
763 (false, false, false) => {
764 unreachable!("ExceededThreshold requires at least one threshold exceeded")
765 }
766 }
767 }
768
769 /// True when the cyclomatic threshold contributed to the finding.
770 #[must_use]
771 pub const fn includes_cyclomatic(self) -> bool {
772 matches!(
773 self,
774 Self::Cyclomatic | Self::Both | Self::CyclomaticCrap | Self::All
775 )
776 }
777
778 /// True when the cognitive threshold contributed to the finding.
779 #[must_use]
780 pub const fn includes_cognitive(self) -> bool {
781 matches!(
782 self,
783 Self::Cognitive | Self::Both | Self::CognitiveCrap | Self::All
784 )
785 }
786
787 /// True when the CRAP threshold contributed to the finding.
788 #[must_use]
789 pub const fn includes_crap(self) -> bool {
790 matches!(
791 self,
792 Self::Crap | Self::CyclomaticCrap | Self::CognitiveCrap | Self::All
793 )
794 }
795}
796
797/// Severity tier indicating how far a function exceeds complexity thresholds.
798///
799/// Determined by the highest tier reached across both cognitive and cyclomatic
800/// scores. Default thresholds: cognitive 25/40, cyclomatic 30/50.
801#[derive(
802 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
803)]
804#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
805#[serde(rename_all = "snake_case")]
806pub enum FindingSeverity {
807 /// Above threshold but manageable (cognitive < 25 or cyclomatic < 30).
808 Moderate,
809 /// Recommended for extraction (cognitive 25-39 or cyclomatic 30-49).
810 High,
811 /// Immediate extraction candidate (cognitive >= 40 or cyclomatic >= 50).
812 Critical,
813}
814
815/// CRAP score threshold for "high" severity. CC=7 untested -> 56, CC=10 -> 110.
816pub const DEFAULT_CRAP_HIGH: f64 = 50.0;
817
818/// CRAP score threshold for "critical" severity. CC=10 untested gives 110,
819/// CC=12 untested gives 156; 100 lands between the two and flags genuinely
820/// dangerous combinations of high complexity and low coverage.
821pub const DEFAULT_CRAP_CRITICAL: f64 = 100.0;
822
823/// Compute the severity tier for a complexity finding.
824///
825/// Uses the highest tier reached across cognitive, cyclomatic, and CRAP
826/// scores. Pass `None` for `crap` to skip the CRAP contribution (used when
827/// the finding was triggered by complexity thresholds only).
828#[expect(
829 clippy::too_many_arguments,
830 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"
831)]
832pub fn compute_finding_severity(
833 cognitive: u16,
834 cyclomatic: u16,
835 crap: Option<f64>,
836 cognitive_high: u16,
837 cognitive_critical: u16,
838 cyclomatic_high: u16,
839 cyclomatic_critical: u16,
840) -> FindingSeverity {
841 let cog = if cognitive >= cognitive_critical {
842 FindingSeverity::Critical
843 } else if cognitive >= cognitive_high {
844 FindingSeverity::High
845 } else {
846 FindingSeverity::Moderate
847 };
848
849 let cyc = if cyclomatic >= cyclomatic_critical {
850 FindingSeverity::Critical
851 } else if cyclomatic >= cyclomatic_high {
852 FindingSeverity::High
853 } else {
854 FindingSeverity::Moderate
855 };
856
857 let crap_sev = crap.map_or(FindingSeverity::Moderate, |c| {
858 if c >= DEFAULT_CRAP_CRITICAL {
859 FindingSeverity::Critical
860 } else if c >= DEFAULT_CRAP_HIGH {
861 FindingSeverity::High
862 } else {
863 FindingSeverity::Moderate
864 }
865 });
866
867 cog.max(cyc).max(crap_sev)
868}
869
870/// A function exceeding the very-high-risk size threshold (>60 LOC).
871#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
872#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
873pub struct LargeFunctionEntry {
874 /// File path relative to the project root.
875 #[serde(serialize_with = "fallow_types::serde_path::serialize")]
876 pub path: std::path::PathBuf,
877 /// Function name, or a synthesized name for anonymous functions.
878 pub name: String,
879 /// 1-based line the function starts on.
880 pub line: u32,
881 /// Lines of code in the function body.
882 pub line_count: u32,
883}
884
885/// Summary statistics for the health report.
886#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
887#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
888pub struct HealthSummary {
889 /// Files included in the health analysis.
890 pub files_analyzed: usize,
891 /// Functions and template units checked for threshold findings across the
892 /// analyzed files. Synthetic module-scope units are excluded. Cyclomatic
893 /// aggregates include module units too; `vital_signs.cyclomatic_population`
894 /// reports the disjoint authored-function, module, and template populations
895 /// behind those aggregates.
896 pub functions_analyzed: usize,
897 /// Functions exceeding at least one complexity or CRAP threshold.
898 pub functions_above_threshold: usize,
899 /// Global cyclomatic-complexity ceiling for this run.
900 pub max_cyclomatic_threshold: u16,
901 /// Global cognitive-complexity ceiling for this run.
902 pub max_cognitive_threshold: u16,
903 /// Global CRAP-score ceiling for this run.
904 pub max_crap_threshold: f64,
905 /// Effective global unit-size ceiling (`health.maxUnitSize`, maximum
906 /// function length in lines) for this run. Sits alongside the other three
907 /// `max_*_threshold` siblings so a consumer reading the summary sees every
908 /// configured threshold. Per-file `thresholdOverrides` are not reflected
909 /// here; this is the global default.
910 pub max_unit_size_threshold: u32,
911 /// Files with a computed maintainability score; absent when file scoring
912 /// did not run.
913 #[serde(default, skip_serializing_if = "Option::is_none")]
914 pub files_scored: Option<usize>,
915 /// Mean maintainability index over scored files (0-100).
916 #[serde(default, skip_serializing_if = "Option::is_none")]
917 pub average_maintainability: Option<f64>,
918 /// Coverage model behind the CRAP scores, when coverage was used.
919 #[serde(default, skip_serializing_if = "Option::is_none")]
920 pub coverage_model: Option<CoverageModel>,
921 /// Input format of the measured coverage (`istanbul` or `v8`). Present
922 /// only with `coverage_model: "istanbul"`.
923 #[serde(default, skip_serializing_if = "Option::is_none")]
924 pub coverage_input_format: Option<CoverageInputFormat>,
925 /// Whether CRAP findings mix coverage sources.
926 #[serde(default, skip_serializing_if = "Option::is_none")]
927 pub coverage_source_consistency: Option<CoverageSourceConsistency>,
928 /// Functions matched against the Istanbul coverage file, in Istanbul mode.
929 #[serde(default, skip_serializing_if = "Option::is_none")]
930 pub istanbul_matched: Option<usize>,
931 /// Functions in the Istanbul coverage file, in Istanbul mode.
932 #[serde(default, skip_serializing_if = "Option::is_none")]
933 pub istanbul_total: Option<usize>,
934 /// Analyzed files the Istanbul coverage file carried an entry for.
935 /// Read against `istanbul_files_total`, this separates a coverage file
936 /// that did not join from code the coverage file says nothing ran in.
937 #[serde(default, skip_serializing_if = "Option::is_none")]
938 pub istanbul_files_matched: Option<usize>,
939 /// Files described by the Istanbul coverage file, joined or not.
940 #[serde(default, skip_serializing_if = "Option::is_none")]
941 pub istanbul_files_total: Option<usize>,
942 /// Findings with critical severity.
943 pub severity_critical_count: usize,
944 /// Findings with high severity.
945 pub severity_high_count: usize,
946 /// Findings with moderate severity.
947 pub severity_moderate_count: usize,
948 /// Baseline staleness data, present only when a baseline was loaded.
949 #[serde(default, skip_serializing_if = "Option::is_none")]
950 pub baseline_staleness: Option<crate::BaselineStaleness>,
951}
952
953impl Default for HealthSummary {
954 fn default() -> Self {
955 Self {
956 files_analyzed: 0,
957 functions_analyzed: 0,
958 functions_above_threshold: 0,
959 max_cyclomatic_threshold: 20,
960 max_cognitive_threshold: 15,
961 max_crap_threshold: 30.0,
962 max_unit_size_threshold: DEFAULT_MAX_UNIT_SIZE,
963 files_scored: None,
964 average_maintainability: None,
965 coverage_model: None,
966 coverage_input_format: None,
967 coverage_source_consistency: None,
968 istanbul_matched: None,
969 istanbul_total: None,
970 istanbul_files_matched: None,
971 istanbul_files_total: None,
972 severity_critical_count: 0,
973 severity_high_count: 0,
974 severity_moderate_count: 0,
975 baseline_staleness: None,
976 }
977 }
978}
979
980/// Per-file health score combining complexity, coupling, and dead code metrics.
981#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
982#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
983pub struct FileHealthScore {
984 /// File path relative to the project root.
985 #[serde(serialize_with = "fallow_types::serde_path::serialize")]
986 pub path: std::path::PathBuf,
987 /// Modules importing this file.
988 pub fan_in: usize,
989 /// Modules this file imports.
990 pub fan_out: usize,
991 /// Unused exports as a fraction of the file's exports, in `[0, 1]`.
992 pub dead_code_ratio: f64,
993 /// Total cyclomatic complexity per line of code.
994 pub complexity_density: f64,
995 /// Maintainability index (0-100); higher is healthier.
996 pub maintainability_index: f64,
997 /// Summed cyclomatic complexity over all units, including module and template scope.
998 pub total_cyclomatic: u32,
999 /// Summed cognitive complexity over all units, including module and template scope.
1000 pub total_cognitive: u32,
1001 /// Complexity units in the file, including synthetic module and template units.
1002 pub function_count: usize,
1003 /// Lines of code in the file.
1004 pub lines: u32,
1005 /// Highest CRAP score among the file's functions. Always the raw measured
1006 /// value; threshold overrides never rewrite it.
1007 pub crap_max: f64,
1008 /// Functions whose rounded CRAP score meets or exceeds their effective
1009 /// ceiling, resolved from `health.thresholdOverrides` over the global
1010 /// `maxCrap` / `--max-crap` value. Zero when CRAP enforcement is disabled
1011 /// (global ceiling `0`).
1012 pub crap_above_threshold: usize,
1013 /// Functions whose rounded CRAP score is at or above the canonical 30.0
1014 /// baseline but below their effective ceiling: the count the configuration
1015 /// let through. Stays `0` when the effective ceiling is stricter than 30.
1016 /// When CRAP enforcement is disabled (global ceiling `0`), counts every
1017 /// function at or above the canonical baseline. Omitted when zero.
1018 #[serde(default, skip_serializing_if = "is_zero_usize")]
1019 #[cfg_attr(feature = "schema", schemars(default))]
1020 pub crap_exempted: usize,
1021 /// Lowest effective CRAP ceiling among the file's functions, present only
1022 /// when it differs from the run global (`summary.max_crap_threshold`).
1023 /// Consumers fall back to `summary.max_crap_threshold` when absent.
1024 #[serde(default, skip_serializing_if = "Option::is_none")]
1025 pub crap_effective_threshold: Option<f64>,
1026}
1027
1028/// A hotspot: a file that is both complex and frequently changing.
1029#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1030#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1031pub struct HotspotEntry {
1032 /// File path relative to the project root.
1033 #[serde(serialize_with = "fallow_types::serde_path::serialize")]
1034 pub path: std::path::PathBuf,
1035 /// Churn-times-complexity hotspot score; higher is riskier.
1036 pub score: f64,
1037 /// Commits touching the file in the analysis window.
1038 pub commits: u32,
1039 /// Recency-weighted commit count.
1040 pub weighted_commits: f64,
1041 /// Lines added to the file in the analysis window.
1042 pub lines_added: u32,
1043 /// Lines deleted from the file in the analysis window.
1044 pub lines_deleted: u32,
1045 /// Total cyclomatic complexity per line of code.
1046 pub complexity_density: f64,
1047 /// Modules importing this file.
1048 pub fan_in: usize,
1049 /// Whether churn is rising, falling, or steady over the window.
1050 pub trend: fallow_types::churn::ChurnTrend,
1051 /// Ownership metrics, when ownership analysis ran.
1052 #[serde(default, skip_serializing_if = "Option::is_none")]
1053 pub ownership: Option<OwnershipMetrics>,
1054 /// True for files matched by test-path patterns; omitted when false.
1055 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1056 #[cfg_attr(feature = "schema", schemars(default))]
1057 pub is_test_path: bool,
1058}
1059
1060/// One contributor row in ownership metrics.
1061#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1062#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1063pub struct ContributorEntry {
1064 /// Contributor identifier, encoded per `format`.
1065 pub identifier: String,
1066 /// How `identifier` is encoded (raw, handle, anonymized, or hash).
1067 pub format: ContributorIdentifierFormat,
1068 /// Contributor's share of the file's commits, in `[0, 1]`.
1069 pub share: f64,
1070 /// Days since the contributor's last commit to the file.
1071 pub stale_days: u64,
1072 /// Contributor's commits touching the file in the window.
1073 pub commits: u32,
1074}
1075
1076/// Encoding applied to a [`ContributorEntry::identifier`].
1077#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1078#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1079#[serde(rename_all = "kebab-case")]
1080pub enum ContributorIdentifierFormat {
1081 /// Raw git author identity.
1082 Raw,
1083 /// Platform handle, e.g. a GitHub username.
1084 Handle,
1085 /// Anonymized label that stays stable within the report.
1086 Anonymized,
1087 /// One-way hash of the identity.
1088 Hash,
1089}
1090
1091/// Ownership lifecycle state of a file.
1092#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1093#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1094#[serde(rename_all = "snake_case")]
1095pub enum OwnershipState {
1096 /// A declared or de-facto owner is still actively contributing.
1097 Active,
1098 /// No owner could be resolved.
1099 Unowned,
1100 /// The declared owner has stopped contributing.
1101 DeclaredInactive,
1102 /// Recent contributions come from outside the declared ownership.
1103 Drifting,
1104}
1105
1106/// Ownership metrics for a hotspot file, derived from git history and
1107/// CODEOWNERS declarations.
1108#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1109#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1110pub struct OwnershipMetrics {
1111 /// Minimum contributors covering half the file's commits.
1112 pub bus_factor: u32,
1113
1114 /// Distinct contributors touching the file in the window.
1115 pub contributor_count: u32,
1116
1117 /// Contributor with the largest commit share.
1118 pub top_contributor: ContributorEntry,
1119
1120 /// Contributors active in the recent window; omitted when empty.
1121 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1122 #[cfg_attr(feature = "schema", schemars(default))]
1123 pub recent_contributors: Vec<ContributorEntry>,
1124
1125 /// Contributors best positioned to review changes; omitted when empty.
1126 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1127 #[cfg_attr(feature = "schema", schemars(default))]
1128 pub suggested_reviewers: Vec<ContributorEntry>,
1129
1130 /// Owner declared in CODEOWNERS, when one matches the file.
1131 #[serde(default, skip_serializing_if = "Option::is_none")]
1132 pub declared_owner: Option<String>,
1133
1134 /// Whether no owner could be resolved; `null` when ownership resolution
1135 /// did not run.
1136 pub unowned: Option<bool>,
1137
1138 /// Ownership lifecycle state.
1139 pub ownership_state: OwnershipState,
1140
1141 /// True when recent contributions drift away from the declared ownership.
1142 pub drift: bool,
1143
1144 /// Human-readable explanation of the drift, when drifting.
1145 #[serde(default, skip_serializing_if = "Option::is_none")]
1146 pub drift_reason: Option<String>,
1147}
1148
1149/// Where the run's reference epoch came from.
1150///
1151/// Churn recency weighting and ownership staleness are measured against one
1152/// instant. `head_commit` and `environment` resolve to the same value on every
1153/// run over the same commit; `wall_clock` does not.
1154#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1155#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1156#[serde(rename_all = "snake_case")]
1157pub enum ClockSource {
1158 /// Pinned by the `FALLOW_CLOCK_EPOCH` environment variable.
1159 Environment,
1160 /// HEAD's committer timestamp.
1161 HeadCommit,
1162 /// The system wall clock, because no commit timestamp was readable.
1163 WallClock,
1164}
1165
1166/// The instant a run measured commit ages and staleness against.
1167///
1168/// A consumer reading `weighted_commits`, `stale_days`, or anything derived
1169/// from them needs to know whether re-running over the same commit yields the
1170/// same number. The human report says so in a warning that `--quiet` removes,
1171/// which left the JSON consumer, who cannot see stderr at all, with no way to
1172/// find out.
1173#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1174#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1175pub struct ClockProvenance {
1176 /// Which of the three sources supplied the epoch.
1177 pub source: ClockSource,
1178 /// The reference epoch itself, in unix seconds. Pass it back as
1179 /// `FALLOW_CLOCK_EPOCH` to reproduce this run's churn-derived numbers.
1180 pub epoch_secs: u64,
1181 /// False only for `wall_clock`, where the numbers drift between runs.
1182 pub reproducible: bool,
1183}
1184
1185/// Scope metadata for the hotspot analysis.
1186#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1187#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1188pub struct HotspotSummary {
1189 /// Start of the churn window, as passed to `git log --since`.
1190 pub since: String,
1191 /// Minimum commit count for a file to qualify as a hotspot.
1192 pub min_commits: u32,
1193 /// Files with churn data in the window.
1194 pub files_analyzed: usize,
1195 /// Files excluded by test-path and ignore filters.
1196 pub files_excluded: usize,
1197 /// True when the repository is a shallow clone, so churn counts are
1198 /// truncated.
1199 pub shallow_clone: bool,
1200 /// Provenance of the instant every churn and staleness number was measured
1201 /// against. Absent only when a caller assembled a summary without one.
1202 #[serde(default, skip_serializing_if = "Option::is_none")]
1203 pub clock: Option<ClockProvenance>,
1204}
1205
1206#[cfg(test)]
1207mod tests {
1208 use super::*;
1209
1210 /// The three tokens are the wire contract a consumer branches on, so they
1211 /// are pinned here rather than left to the derive.
1212 #[test]
1213 fn clock_source_serializes_as_snake_case_tokens() {
1214 let tokens: Vec<String> = [
1215 ClockSource::Environment,
1216 ClockSource::HeadCommit,
1217 ClockSource::WallClock,
1218 ]
1219 .into_iter()
1220 .map(|source| serde_json::to_string(&source).expect("clock source should serialize"))
1221 .collect();
1222 assert_eq!(
1223 tokens,
1224 [r#""environment""#, r#""head_commit""#, r#""wall_clock""#]
1225 );
1226 }
1227
1228 /// A summary without a clock stays byte-identical to the shape consumers
1229 /// already parse; one with a clock publishes all three members.
1230 #[test]
1231 fn hotspot_summary_clock_is_omitted_when_absent_and_complete_when_present() {
1232 let mut summary = HotspotSummary {
1233 since: "6 months".to_owned(),
1234 min_commits: 3,
1235 files_analyzed: 4,
1236 files_excluded: 1,
1237 shallow_clone: false,
1238 clock: None,
1239 };
1240 let json = serde_json::to_string(&summary).expect("summary should serialize");
1241 assert!(!json.contains("clock"), "{json}");
1242
1243 summary.clock = Some(ClockProvenance {
1244 source: ClockSource::WallClock,
1245 epoch_secs: 1_788_782_400,
1246 reproducible: false,
1247 });
1248 let value: serde_json::Value =
1249 serde_json::to_value(&summary).expect("summary should serialize");
1250 assert_eq!(value["clock"]["source"], "wall_clock");
1251 assert_eq!(value["clock"]["epoch_secs"], 1_788_782_400_u64);
1252 assert_eq!(value["clock"]["reproducible"], false);
1253 }
1254
1255 #[test]
1256 fn exceeded_threshold_serializes_as_snake_case() {
1257 let json = serde_json::to_string(&ExceededThreshold::Both)
1258 .expect("threshold variant should serialize");
1259 assert_eq!(json, r#""both""#);
1260
1261 let json = serde_json::to_string(&ExceededThreshold::Cyclomatic)
1262 .expect("threshold variant should serialize");
1263 assert_eq!(json, r#""cyclomatic""#);
1264 }
1265
1266 #[test]
1267 fn exceeded_threshold_all_variants_serialize() {
1268 for (variant, expected) in [
1269 (ExceededThreshold::Cyclomatic, r#""cyclomatic""#),
1270 (ExceededThreshold::Cognitive, r#""cognitive""#),
1271 (ExceededThreshold::Both, r#""both""#),
1272 (ExceededThreshold::Crap, r#""crap""#),
1273 (ExceededThreshold::CyclomaticCrap, r#""cyclomatic_crap""#),
1274 (ExceededThreshold::CognitiveCrap, r#""cognitive_crap""#),
1275 (ExceededThreshold::All, r#""all""#),
1276 ] {
1277 let json = serde_json::to_string(&variant).expect("threshold variant should serialize");
1278 assert_eq!(json, expected, "wire form for {variant:?} should be stable");
1279 }
1280 }
1281
1282 #[test]
1283 fn letter_grade_boundaries() {
1284 assert_eq!(letter_grade(100.0), "A");
1285 assert_eq!(letter_grade(85.0), "A");
1286 assert_eq!(letter_grade(84.9), "B");
1287 assert_eq!(letter_grade(70.0), "B");
1288 assert_eq!(letter_grade(69.9), "C");
1289 assert_eq!(letter_grade(55.0), "C");
1290 assert_eq!(letter_grade(54.9), "D");
1291 assert_eq!(letter_grade(40.0), "D");
1292 assert_eq!(letter_grade(39.9), "F");
1293 assert_eq!(letter_grade(0.0), "F");
1294 }
1295
1296 #[test]
1297 fn coverage_tier_boundaries() {
1298 assert_eq!(CoverageTier::from_pct(0.0), CoverageTier::None);
1299 assert_eq!(CoverageTier::from_pct(0.1), CoverageTier::Partial);
1300 assert_eq!(CoverageTier::from_pct(69.9), CoverageTier::Partial);
1301 assert_eq!(CoverageTier::from_pct(70.0), CoverageTier::High);
1302 assert_eq!(CoverageTier::from_pct(100.0), CoverageTier::High);
1303 }
1304
1305 #[test]
1306 fn hotspot_score_threshold_is_50() {
1307 assert!((HOTSPOT_SCORE_THRESHOLD - 50.0).abs() < f64::EPSILON);
1308 }
1309
1310 #[test]
1311 fn health_score_serializes_correctly() {
1312 let score = HealthScore {
1313 formula_version: HEALTH_SCORE_FORMULA_VERSION,
1314 score: 78.5,
1315 grade: "B",
1316 penalties: HealthScorePenalties {
1317 dead_files: Some(3.1),
1318 dead_exports: Some(6.0),
1319 complexity: 0.0,
1320 p90_complexity: 0.0,
1321 maintainability: None,
1322 hotspots: None,
1323 unused_deps: Some(5.0),
1324 circular_deps: Some(4.0),
1325 unit_size: None,
1326 coupling: None,
1327 duplication: None,
1328 prop_drilling: None,
1329 },
1330 };
1331 let json = serde_json::to_string(&score).expect("health score should serialize");
1332 let parsed: serde_json::Value =
1333 serde_json::from_str(&json).expect("health score JSON should parse");
1334 assert_eq!(parsed["formula_version"], HEALTH_SCORE_FORMULA_VERSION);
1335 assert_eq!(parsed["score"], 78.5);
1336 assert_eq!(parsed["grade"], "B");
1337 assert_eq!(parsed["penalties"]["dead_files"], 3.1);
1338 assert!(!json.contains("maintainability"));
1339 assert!(!json.contains("hotspots"));
1340 assert!(!json.contains("duplication"));
1341 }
1342
1343 #[test]
1344 fn styling_health_serializes_correctly() {
1345 let styling = StylingHealth {
1346 formula_version: STYLING_HEALTH_FORMULA_VERSION,
1347 score: 72.0,
1348 grade: "B",
1349 penalties: StylingHealthPenalties {
1350 duplication: 12.0,
1351 dead_surface: 8.0,
1352 broken_references: 4.0,
1353 token_erosion: 2.0,
1354 structural: 2.0,
1355 },
1356 confidence: StylingHealthConfidence::High,
1357 confidence_reason: None,
1358 };
1359 let json = serde_json::to_string(&styling).expect("styling health should serialize");
1360 let parsed: serde_json::Value =
1361 serde_json::from_str(&json).expect("styling health JSON should parse");
1362 assert_eq!(parsed["formula_version"], STYLING_HEALTH_FORMULA_VERSION);
1363 assert_eq!(parsed["score"], 72.0);
1364 assert_eq!(parsed["grade"], "B");
1365 assert_eq!(parsed["penalties"]["duplication"], 12.0);
1366 assert_eq!(parsed["penalties"]["dead_surface"], 8.0);
1367 assert_eq!(parsed["penalties"]["broken_references"], 4.0);
1368 assert_eq!(parsed["penalties"]["token_erosion"], 2.0);
1369 assert_eq!(parsed["penalties"]["structural"], 2.0);
1370 // `high` confidence omits the reason; the enum serializes lowercase.
1371 assert_eq!(parsed["confidence"], "high");
1372 assert!(parsed.get("confidence_reason").is_none());
1373 }
1374
1375 #[test]
1376 fn styling_health_low_confidence_serializes_reason() {
1377 let styling = StylingHealth {
1378 formula_version: STYLING_HEALTH_FORMULA_VERSION,
1379 score: 89.0,
1380 grade: "A",
1381 penalties: StylingHealthPenalties {
1382 duplication: 0.0,
1383 dead_surface: 0.0,
1384 broken_references: 0.0,
1385 token_erosion: 0.0,
1386 structural: 0.0,
1387 },
1388 confidence: StylingHealthConfidence::Low,
1389 confidence_reason: Some("graded from only 24 declarations across 2 stylesheets".into()),
1390 };
1391 let json = serde_json::to_string(&styling).expect("styling health should serialize");
1392 let parsed: serde_json::Value =
1393 serde_json::from_str(&json).expect("styling health JSON should parse");
1394 assert_eq!(parsed["confidence"], "low");
1395 assert_eq!(
1396 parsed["confidence_reason"],
1397 "graded from only 24 declarations across 2 stylesheets"
1398 );
1399 }
1400
1401 #[test]
1402 fn coverage_model_serializes_as_snake_case() {
1403 let json = serde_json::to_string(&CoverageModel::StaticBinary)
1404 .expect("coverage model should serialize");
1405 assert_eq!(json, r#""static_binary""#);
1406
1407 let json = serde_json::to_string(&CoverageModel::StaticEstimated)
1408 .expect("coverage model should serialize");
1409 assert_eq!(json, r#""static_estimated""#);
1410
1411 let json = serde_json::to_string(&CoverageModel::Istanbul)
1412 .expect("coverage model should serialize");
1413 assert_eq!(json, r#""istanbul""#);
1414 }
1415
1416 #[test]
1417 fn finding_severity_serializes_as_snake_case() {
1418 assert_eq!(
1419 serde_json::to_string(&FindingSeverity::Moderate)
1420 .expect("finding severity should serialize"),
1421 r#""moderate""#,
1422 );
1423 assert_eq!(
1424 serde_json::to_string(&FindingSeverity::High)
1425 .expect("finding severity should serialize"),
1426 r#""high""#,
1427 );
1428 assert_eq!(
1429 serde_json::to_string(&FindingSeverity::Critical)
1430 .expect("finding severity should serialize"),
1431 r#""critical""#,
1432 );
1433 }
1434
1435 #[test]
1436 fn finding_severity_ordering() {
1437 assert!(FindingSeverity::Moderate < FindingSeverity::High);
1438 assert!(FindingSeverity::High < FindingSeverity::Critical);
1439 }
1440
1441 #[test]
1442 fn compute_severity_moderate_when_below_high_thresholds() {
1443 let severity = compute_finding_severity(20, 25, None, 25, 40, 30, 50);
1444 assert_eq!(severity, FindingSeverity::Moderate);
1445 }
1446
1447 #[test]
1448 fn compute_severity_high_from_cognitive() {
1449 let severity = compute_finding_severity(25, 20, None, 25, 40, 30, 50);
1450 assert_eq!(severity, FindingSeverity::High);
1451 }
1452
1453 #[test]
1454 fn compute_severity_high_from_cyclomatic() {
1455 let severity = compute_finding_severity(20, 30, None, 25, 40, 30, 50);
1456 assert_eq!(severity, FindingSeverity::High);
1457 }
1458
1459 #[test]
1460 fn compute_severity_critical_from_cognitive() {
1461 let severity = compute_finding_severity(40, 20, None, 25, 40, 30, 50);
1462 assert_eq!(severity, FindingSeverity::Critical);
1463 }
1464
1465 #[test]
1466 fn compute_severity_critical_from_cyclomatic() {
1467 let severity = compute_finding_severity(20, 50, None, 25, 40, 30, 50);
1468 assert_eq!(severity, FindingSeverity::Critical);
1469 }
1470
1471 #[test]
1472 fn compute_severity_uses_highest_across_dimensions() {
1473 let severity = compute_finding_severity(45, 20, None, 25, 40, 30, 50);
1474 assert_eq!(severity, FindingSeverity::Critical);
1475 }
1476
1477 #[test]
1478 fn compute_severity_at_exact_boundaries() {
1479 let severity = compute_finding_severity(25, 30, None, 25, 40, 30, 50);
1480 assert_eq!(severity, FindingSeverity::High);
1481
1482 let severity = compute_finding_severity(24, 29, None, 25, 40, 30, 50);
1483 assert_eq!(severity, FindingSeverity::Moderate);
1484
1485 let severity = compute_finding_severity(40, 50, None, 25, 40, 30, 50);
1486 assert_eq!(severity, FindingSeverity::Critical);
1487 }
1488
1489 #[test]
1490 fn compute_severity_crap_contributes_high() {
1491 let severity = compute_finding_severity(10, 10, Some(60.0), 25, 40, 30, 50);
1492 assert_eq!(severity, FindingSeverity::High);
1493 }
1494
1495 #[test]
1496 fn compute_severity_crap_contributes_critical() {
1497 let severity = compute_finding_severity(10, 10, Some(120.0), 25, 40, 30, 50);
1498 assert_eq!(severity, FindingSeverity::Critical);
1499 }
1500
1501 #[test]
1502 fn compute_severity_crap_moderate_under_high() {
1503 let severity = compute_finding_severity(10, 10, Some(30.0), 25, 40, 30, 50);
1504 assert_eq!(severity, FindingSeverity::Moderate);
1505 }
1506
1507 #[test]
1508 fn exceeded_threshold_from_bools() {
1509 assert!(matches!(
1510 ExceededThreshold::from_bools(true, false, false),
1511 ExceededThreshold::Cyclomatic
1512 ));
1513 assert!(matches!(
1514 ExceededThreshold::from_bools(true, true, true),
1515 ExceededThreshold::All
1516 ));
1517 assert!(matches!(
1518 ExceededThreshold::from_bools(false, false, true),
1519 ExceededThreshold::Crap
1520 ));
1521 assert!(matches!(
1522 ExceededThreshold::from_bools(true, false, true),
1523 ExceededThreshold::CyclomaticCrap
1524 ));
1525 }
1526
1527 #[test]
1528 fn exceeded_threshold_includes_helpers() {
1529 let all = ExceededThreshold::All;
1530 assert!(all.includes_cyclomatic());
1531 assert!(all.includes_cognitive());
1532 assert!(all.includes_crap());
1533
1534 let crap_only = ExceededThreshold::Crap;
1535 assert!(!crap_only.includes_cyclomatic());
1536 assert!(!crap_only.includes_cognitive());
1537 assert!(crap_only.includes_crap());
1538
1539 assert!(ExceededThreshold::CyclomaticCrap.includes_crap());
1540 assert!(ExceededThreshold::CognitiveCrap.includes_crap());
1541 assert!(!ExceededThreshold::Both.includes_crap());
1542 assert!(!ExceededThreshold::Cyclomatic.includes_crap());
1543 assert!(!ExceededThreshold::Cognitive.includes_crap());
1544 }
1545
1546 #[test]
1547 fn coverage_source_consistency_omits_empty_sources() {
1548 let sources = Vec::new();
1549 assert_eq!(summarize_coverage_source_consistency(sources), None);
1550 }
1551
1552 #[test]
1553 fn coverage_source_consistency_reports_uniform_sources() {
1554 assert_eq!(
1555 summarize_coverage_source_consistency([
1556 CoverageSource::Estimated,
1557 CoverageSource::Estimated,
1558 ]),
1559 Some(CoverageSourceConsistency::Uniform)
1560 );
1561 }
1562
1563 #[test]
1564 fn coverage_source_consistency_reports_mixed_sources() {
1565 assert_eq!(
1566 summarize_coverage_source_consistency([
1567 CoverageSource::Istanbul,
1568 CoverageSource::Estimated,
1569 ]),
1570 Some(CoverageSourceConsistency::Mixed)
1571 );
1572 }
1573}