Skip to main content

fallow_engine/health/
mod.rs

1//! Command-neutral health execution options and runners.
2
3use std::path::{Path, PathBuf};
4
5use fallow_config::{EmailMode, WorkspaceInfo};
6use fallow_output::{
7    DiffIndex, EffortEstimate, FindingSeverity, GroupByMode, RuntimeCoverageReport,
8    RuntimeCoverageWatermark,
9};
10use fallow_types::output_format::OutputFormat;
11use fallow_types::path_util::is_absolute_path_any_platform;
12use fallow_types::results::AnalysisResults;
13use rustc_hash::{FxHashMap, FxHashSet};
14
15use crate::module_graph::RetainedModuleGraph;
16use crate::results::DeadCodeAnalysisArtifacts;
17
18mod actions;
19mod analysis_data;
20mod assembly;
21mod baseline_io;
22mod branching;
23pub use branching::BranchingByFile;
24use branching::branching_by_file;
25mod change_coupling_section;
26mod churn_file;
27mod component_rollup;
28mod core_pipeline;
29mod coverage_gaps;
30mod coverage_intelligence;
31mod coverage_settings;
32mod coverage_v8;
33mod css_analytics;
34mod cyclomatic_policy;
35mod derived_sections;
36pub(crate) mod diagnostics;
37mod execute;
38mod file_lines;
39mod file_scores;
40mod filters;
41mod finding_sort;
42mod findings;
43mod findings_pipeline;
44mod framework_health;
45mod grouping;
46pub use grouping::validate_group_filter;
47mod health_error;
48mod hotspots;
49pub(crate) mod ignore;
50mod inline;
51pub use inline::{InlineComplexity, inline_complexity};
52mod large_functions;
53mod output_build;
54pub mod ownership;
55mod package_json;
56mod pipeline;
57mod react_hooks;
58mod result;
59mod runner;
60mod runtime_filter;
61mod runtime_sections;
62mod scope;
63/// File health scoring: maintainability index, CRAP risk, triage concern
64/// classification, and Istanbul coverage ingestion.
65pub mod scoring;
66pub mod styling_score;
67mod tailwind_theme;
68mod targets;
69mod test_reach;
70mod threshold_overrides;
71mod timings;
72mod vital_data;
73mod vital_signs_scope;
74
75pub use crate::results::HealthAnalysisResult;
76pub use churn_file::validate_health_churn_file;
77pub use css_analytics::StylingAnalysisArtifacts;
78use derived_sections::{
79    HealthDerivedSectionInput, HealthDerivedSections, prepare_health_derived_sections,
80};
81use execute::HealthOptions;
82pub use execute::execute_health_inner;
83use file_scores::{
84    FileScoresAndChurnInput, compute_file_scores_and_churn, health_file_scores_slice,
85    print_slow_churn_note,
86};
87use finding_sort::sort_findings;
88pub use health_error::HealthError;
89pub use hotspots::{
90    TargetChurnEvidence, TargetChurnOptions, TargetChurnOutcome, analyze_target_churn,
91};
92pub use pipeline::{HealthPipelineInputs, HealthScopeInputs};
93pub use runner::{
94    UngroupedHealthSession, run_ungrouped_health_with_session,
95    run_ungrouped_health_with_session_artifacts,
96};
97pub use test_reach::TestReachGraph;
98use vital_data::{HealthVitalData, HealthVitalDataInput, prepare_health_vital_data};
99use vital_signs_scope::{
100    SubsetFilter, VitalSignsAndCountsInput, apply_duplication_metrics,
101    compute_vital_signs_and_counts,
102};
103
104pub(crate) fn build_styling_analysis_artifacts(
105    files: &[crate::discover::DiscoveredFile],
106    modules: &[crate::source::ModuleInfo],
107    config: &fallow_config::ResolvedConfig,
108) -> StylingAnalysisArtifacts {
109    css_analytics::build_styling_analysis_artifacts(files, modules, config)
110}
111
112/// Build health shared parse data from retained dead-code artifacts.
113#[must_use]
114pub fn shared_parse_data_from_artifacts(
115    results: &AnalysisResults,
116    graph: Option<RetainedModuleGraph>,
117    modules: Option<Vec<crate::source::ModuleInfo>>,
118    files: Option<Vec<crate::discover::DiscoveredFile>>,
119    workspaces: Vec<WorkspaceInfo>,
120    script_used_packages: impl IntoIterator<Item = String>,
121) -> Option<HealthSharedParseData> {
122    let (Some(modules), Some(files)) = (modules, files) else {
123        return None;
124    };
125    let script_used_packages: FxHashSet<String> = script_used_packages.into_iter().collect();
126    // The vital signs and file scores measure the code, not the report, so
127    // they count the findings that the cascade filter hid. Standalone
128    // `health` runs no rule pass and sees the same set.
129    let mut results = results.clone();
130    results.restore_cascade_findings();
131    let analysis_output = graph.map(|graph| DeadCodeAnalysisArtifacts {
132        results: results.clone(),
133        timings: None,
134        graph: Some(graph),
135        modules: None,
136        files: None,
137        script_used_packages: script_used_packages.clone(),
138        trace_provenance: crate::trace::TraceProvenance::default(),
139        file_hashes: FxHashMap::default(),
140    });
141    Some(HealthSharedParseData {
142        files,
143        modules,
144        dead_code_results: Some(results),
145        workspaces,
146        analysis_output,
147    })
148}
149
150/// Return true when health sections will need dead-code analysis artifacts.
151///
152/// Callers that already have a session and parsed modules can precompute these
153/// artifacts once, then pass them into [`HealthPipelineInputs`] to avoid a
154/// second graph and dead-code analysis inside the health pipeline.
155#[must_use]
156pub fn should_precompute_dead_code_analysis(
157    options: &HealthExecutionOptions<'_>,
158    config: &fallow_config::ResolvedConfig,
159) -> bool {
160    let max_crap = options
161        .thresholds
162        .max_crap
163        .unwrap_or(config.health.max_crap);
164    options.file_scores
165        || options.coverage_gaps
166        || options.config_activates_coverage_gaps
167        || options.hotspots
168        || options.targets
169        || options.force_full
170        || max_crap > 0.0
171        || options.runtime_coverage.is_some()
172}
173
174/// Command-neutral grouping resolver contract for `--group-by` health output.
175///
176/// The CLI owns the concrete resolver (CODEOWNERS parsing, package discovery);
177/// the engine grouping pass only needs these three read operations, so it stays
178/// generic over the resolver instead of depending on the CLI type.
179pub trait HealthGroupResolver {
180    /// Stable label for the active grouping mode (`owner` / `directory` / ...).
181    fn mode_label(&self) -> &'static str;
182    /// Resolve a repo-relative path to its group key and the matching rule.
183    fn resolve_with_rule(&self, rel_path: &Path) -> (String, Option<String>);
184    /// Section owners for the group a path belongs to, when known.
185    fn section_owners_of(&self, rel_path: &Path) -> Option<&[String]>;
186}
187
188/// Placeholder grouping resolver for runs without `--group-by` (the programmatic
189/// API path). Constructed only as `None`, so its methods are never invoked.
190#[derive(Debug, Clone, Copy)]
191#[expect(
192    clippy::empty_enums,
193    reason = "NoGroupResolver must be uninhabited so that no code can construct it"
194)]
195pub enum NoGroupResolver {}
196
197#[expect(
198    clippy::uninhabited_references,
199    reason = "NoGroupResolver is uninhabited; these methods are unreachable and exist only to satisfy the trait bound for the group-less programmatic path"
200)]
201impl HealthGroupResolver for NoGroupResolver {
202    fn mode_label(&self) -> &'static str {
203        match *self {}
204    }
205    fn resolve_with_rule(&self, _rel_path: &Path) -> (String, Option<String>) {
206        match *self {}
207    }
208    fn section_owners_of(&self, _rel_path: &Path) -> Option<&[String]> {
209        match *self {}
210    }
211}
212
213/// Runtime coverage analysis seam.
214///
215/// Runtime coverage execution drives the closed-source `fallow-cov` sidecar
216/// (license verification, subprocess spawning), which stays in the CLI. The
217/// engine calls this callback only when [`HealthExecutionOptions::runtime_coverage`]
218/// is set, so the default and programmatic paths never touch it.
219///
220/// The seam prints its own errors (license / sidecar diagnostics), so it returns
221/// the already-printed exit code as a bare `u8`. The engine wraps that code in
222/// [`HealthError::Printed`] so the CLI boundary honors the code without emitting
223/// a second error document.
224pub type RuntimeCoverageAnalyzer<'a> = dyn Fn(&RuntimeCoverageOptions, RuntimeCoverageSeamInput<'_>) -> Result<RuntimeCoverageReport, u8>
225    + 'a;
226
227/// Inputs the runtime coverage seam needs from the analysis core.
228pub struct RuntimeCoverageSeamInput<'a> {
229    /// Project root the analysis ran against.
230    pub root: &'a Path,
231    /// Parsed modules from the extract phase, for correlating trace symbols.
232    pub modules: &'a [fallow_types::extract::ModuleInfo],
233    /// Retained dead-code artifacts (graph plus results) the sidecar joins
234    /// runtime traces against.
235    pub analysis_output: &'a DeadCodeAnalysisArtifacts,
236    /// Parsed Istanbul test coverage when the run also supplied it.
237    pub istanbul_coverage: Option<&'a scoring::IstanbulCoverage>,
238    /// `FileId` to absolute-path lookup for resolving finding locations.
239    pub file_paths: &'a rustc_hash::FxHashMap<fallow_types::discover::FileId, &'a PathBuf>,
240    /// Compiled ignore globs; matching files are excluded from verdicts.
241    pub ignore_set: &'a globset::GlobSet,
242    /// Diff scope when the run is limited to changed files.
243    pub changed_files: Option<&'a rustc_hash::FxHashSet<PathBuf>>,
244    /// Workspace roots when the run is workspace-scoped.
245    pub ws_roots: Option<&'a [PathBuf]>,
246    /// Cap on rendered findings, forwarded from `--top`.
247    pub top: Option<usize>,
248    /// CODEOWNERS override path for ownership attribution on findings.
249    pub codeowners_path: Option<&'a str>,
250    /// Suppress progress notes on stderr.
251    pub quiet: bool,
252    /// Output format the seam should render its own diagnostics in.
253    pub output: OutputFormat,
254    /// Full-project graph for test reachability in production mode. `None`
255    /// outside production mode: then `analysis_output` holds the test files.
256    pub test_reach: Option<&'a TestReachGraph>,
257}
258
259/// CLI-supplied callbacks the command-neutral health pipeline needs.
260///
261/// The pipeline itself stays cli-free; these are the seams the CLI threads in.
262pub struct HealthSeams<'a> {
263    /// Runs the runtime coverage sidecar (only when runtime coverage is set).
264    pub runtime_coverage_analyzer: &'a RuntimeCoverageAnalyzer<'a>,
265    /// Records module-graph structure facts (graph node count, edge count) into
266    /// the CLI's process-global telemetry sinks. Best-effort; the engine never
267    /// owns telemetry state.
268    pub note_graph_structure: &'a dyn Fn(usize, usize),
269}
270
271/// Command-neutral sort criteria for health complexity findings.
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub enum HealthSort {
274    /// Worst first: exceeded-threshold class, then severity, CRAP presence,
275    /// and raw complexity metrics as tie-breakers.
276    Severity,
277    /// Descending cyclomatic complexity.
278    Cyclomatic,
279    /// Descending cognitive complexity.
280    Cognitive,
281    /// Descending function line count.
282    Lines,
283}
284
285/// Command-neutral threshold overrides for health complexity findings.
286#[derive(Debug, Clone, Copy, Default, PartialEq)]
287pub struct HealthThresholdOverrides {
288    /// Overrides the configured maximum cyclomatic complexity threshold.
289    pub max_cyclomatic: Option<u16>,
290    /// Overrides the configured maximum cognitive complexity threshold.
291    pub max_cognitive: Option<u16>,
292    /// Maximum CRAP score threshold. Functions meeting or exceeding this score
293    /// are reported as complexity findings.
294    pub max_crap: Option<f64>,
295    /// Overrides the configured file-length ceiling (`health.maxFileLines`)
296    /// in physical lines. `0` turns the check off.
297    pub max_file_lines: Option<u32>,
298}
299
300/// Command-neutral Istanbul coverage inputs for health CRAP scoring.
301#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
302pub struct HealthCoverageInputs<'a> {
303    /// Path to an Istanbul `coverage-final.json` used for CRAP scoring.
304    pub coverage: Option<&'a Path>,
305    /// Absolute coverage-path prefix to strip before rebasing files onto the
306    /// project root.
307    pub coverage_root: Option<&'a Path>,
308    /// The coverage map was recorded against a different checkout of this
309    /// project (the audit base-worktree pass), so function line numbers may
310    /// have drifted arbitrarily. Enables the distance-free unambiguous-name
311    /// match in the Istanbul lookup; keep `false` for same-checkout coverage,
312    /// where the bounded fuzz protects against stale data (#2347).
313    pub coverage_relocated: bool,
314}
315
316/// Validate that a coverage-data root is absolute under Unix or Windows path
317/// conventions.
318///
319/// Istanbul coverage paths often come from a Linux CI runner even when fallow
320/// is invoked on another host, so POSIX-rooted paths and Windows drive paths
321/// are both accepted on every platform.
322pub fn validate_coverage_root_absolute(coverage_root: Option<&Path>) -> Result<(), String> {
323    if let Some(path) = coverage_root
324        && !is_absolute_path_any_platform(path)
325    {
326        return Err(format!(
327            "--coverage-root expects an absolute path prefix from the coverage data, got '{}'. Use the checkout prefix from the machine that generated coverage, for example '/home/runner/work/myapp'.",
328            path.display()
329        ));
330    }
331    Ok(())
332}
333
334/// Command-neutral health exit gate options.
335#[derive(Debug, Clone, Copy, Default, PartialEq)]
336pub struct HealthGateOptions {
337    /// Fail the run when the health score (0-100) falls below this value.
338    pub min_score: Option<f64>,
339    /// Fail the run when any finding at or above this severity exists.
340    pub min_severity: Option<FindingSeverity>,
341    /// Render the score and findings but never fail CI on a health gate.
342    pub report_only: bool,
343    /// Fail the run when a loaded `--baseline` has entries that match nothing.
344    pub fail_on_stale_baseline: bool,
345    /// Fail the run when a source file did not parse cleanly (the
346    /// `parse-error` gate). Set from `--fail-on-parse-error`; the CLI adds the
347    /// `failOnParseError` config key before the gate is evaluated.
348    pub fail_on_parse_error: bool,
349    /// Raise every `warn` complexity finding to `error`, for
350    /// `--fail-on-issues`. Dead-code `warn` findings are raised the same way,
351    /// so every finding of such a run fails it.
352    pub fail_on_issues: bool,
353}
354
355/// Input for deriving effective health sections from command-neutral flags.
356#[derive(Debug, Clone)]
357pub struct HealthSectionOptions {
358    output: OutputFormat,
359    complexity: bool,
360    file_scores: bool,
361    coverage_gaps: bool,
362    hotspots: bool,
363    targets: bool,
364    css: bool,
365    score: bool,
366    score_gate: bool,
367    snapshot_requested: bool,
368    trend: bool,
369}
370
371/// Derived section selection for health runs.
372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
373pub struct DerivedHealthSections {
374    /// True when at least one section was explicitly requested; a request with
375    /// no explicit sections defaults to the full section set.
376    pub any_section: bool,
377    /// Render the complexity findings section.
378    pub complexity: bool,
379    /// Render the per-file health scores section.
380    pub file_scores: bool,
381    /// Render the static coverage gaps section.
382    pub coverage_gaps: bool,
383    /// Render the churn-based hotspots section.
384    pub hotspots: bool,
385    /// Render the refactoring targets section.
386    pub targets: bool,
387    /// Render the CSS / styling analytics section.
388    pub css: bool,
389    /// Compute and render the overall health score.
390    pub score: bool,
391    /// Analyze the full project even when only a subset of sections was
392    /// requested, because scores and snapshots need complete data.
393    pub force_full: bool,
394    /// True when the score is the only requested surface, so output can skip
395    /// section rendering entirely.
396    pub score_only_output: bool,
397}
398
399/// Command-neutral inputs used to normalize a health run before it reaches a
400/// concrete runner.
401#[derive(Debug, Clone)]
402pub struct HealthRunOptionsInput<'a> {
403    /// Output format; badge output implies the score section.
404    pub output: OutputFormat,
405    /// Complexity threshold overrides on top of the resolved config.
406    pub thresholds: HealthThresholdOverrides,
407    /// Cap on rendered findings per section.
408    pub top: Option<usize>,
409    /// Sort criteria for complexity findings.
410    pub sort: HealthSort,
411    /// Explicit request for the complexity findings section.
412    pub complexity: bool,
413    /// Explicit request for the per-file health scores section.
414    pub file_scores: bool,
415    /// Explicit request for the static coverage gaps section.
416    pub coverage_gaps: bool,
417    /// Explicit request for the churn-based hotspots section.
418    pub hotspots: bool,
419    /// Attribute hotspots to owners (implies the hotspots section data).
420    pub ownership: bool,
421    /// How owner identities are rendered (names or emails).
422    pub ownership_emails: Option<EmailMode>,
423    /// Explicit request for the refactoring targets section.
424    pub targets: bool,
425    /// Explicit request for the CSS / styling analytics section.
426    pub css: bool,
427    /// Effort estimation mode; requesting it also enables the targets section.
428    pub effort: Option<EffortEstimate>,
429    /// Explicit request for the overall health score.
430    pub score: bool,
431    /// Exit gate thresholds; a score gate implies the score section.
432    pub gates: HealthGateOptions,
433    /// True when the run should persist a health snapshot (forces a full run).
434    pub snapshot_requested: bool,
435    /// Explicit request for the score trend section (implies score).
436    pub trend: bool,
437    /// Churn lookback window for hotspots (`90d`, `6m`, `1y`, or an ISO date).
438    pub since: Option<&'a str>,
439    /// Minimum commit count for a file to qualify as churn evidence.
440    pub min_commits: Option<u32>,
441    /// Istanbul coverage inputs for CRAP scoring.
442    pub coverage_inputs: HealthCoverageInputs<'a>,
443    /// Runtime coverage sidecar options, when runtime analysis was requested.
444    pub runtime_coverage: Option<RuntimeCoverageOptions>,
445}
446
447/// Normalized health inputs shared by CLI, API, NAPI, and future runners.
448#[derive(Debug, Clone)]
449pub struct HealthRunOptions<'a> {
450    /// Complexity threshold overrides on top of the resolved config.
451    pub thresholds: HealthThresholdOverrides,
452    /// Cap on rendered findings per section.
453    pub top: Option<usize>,
454    /// Sort criteria for complexity findings.
455    pub sort: HealthSort,
456    /// Effective section selection derived from the raw request flags.
457    pub sections: DerivedHealthSections,
458    /// Attribute hotspots to owners; already gated on the hotspots section.
459    pub ownership: bool,
460    /// How owner identities are rendered (names or emails).
461    pub ownership_emails: Option<EmailMode>,
462    /// Effort estimation mode for refactoring targets.
463    pub effort: Option<EffortEstimate>,
464    /// Exit gate thresholds.
465    pub gates: HealthGateOptions,
466    /// Churn lookback window for hotspots (`90d`, `6m`, `1y`, or an ISO date).
467    pub since: Option<&'a str>,
468    /// Minimum commit count for a file to qualify as churn evidence.
469    pub min_commits: Option<u32>,
470    /// Istanbul coverage inputs for CRAP scoring.
471    pub coverage_inputs: HealthCoverageInputs<'a>,
472    /// Runtime coverage sidecar options, when runtime analysis was requested.
473    pub runtime_coverage: Option<RuntimeCoverageOptions>,
474}
475
476/// Command-neutral inputs needed to execute a health analysis.
477///
478/// These fields are shared runner inputs rather than rendering concerns.
479#[derive(Debug, Clone)]
480pub struct HealthExecutionOptions<'a> {
481    /// Project root to analyze.
482    pub root: &'a Path,
483    /// Explicit config file path; `None` triggers automatic discovery.
484    pub config_path: &'a Option<PathBuf>,
485    /// Output format of the run; badge output implies the score section.
486    pub output: OutputFormat,
487    /// Bypass the parse cache for this run.
488    pub no_cache: bool,
489    /// Worker thread count for parsing and analysis.
490    pub threads: usize,
491    /// Suppress progress notes on stderr.
492    pub quiet: bool,
493    /// Include per-decision-point complexity contributions in typed findings.
494    ///
495    /// This changes the produced health result shape, so it belongs to the
496    /// runner input contract rather than CLI rendering options.
497    pub complexity_breakdown: bool,
498    /// Complexity threshold overrides on top of the resolved config.
499    pub thresholds: HealthThresholdOverrides,
500    /// Cap on rendered findings per section.
501    pub top: Option<usize>,
502    /// Sort criteria for complexity findings.
503    pub sort: HealthSort,
504    /// Raw production-only request flag; folded into `production_override`
505    /// when the tri-state override is unset.
506    pub production: bool,
507    /// Tri-state production override: `Some` forces production-only analysis
508    /// on or off regardless of config, `None` defers to the config value.
509    pub production_override: Option<bool>,
510    /// Permit `extends` config inheritance from remote URLs.
511    pub allow_remote_extends: bool,
512    /// Git ref limiting findings to files changed since it.
513    pub changed_since: Option<&'a str>,
514    /// Pre-built diff index scoping findings to changed lines.
515    pub diff_index: Option<&'a DiffIndex>,
516    /// True when `diff_index` came from the process-shared diff source rather
517    /// than a health-specific one.
518    pub use_shared_diff_index: bool,
519    /// Workspace member paths limiting the analysis scope.
520    pub workspace: Option<&'a [String]>,
521    /// Git ref selecting only workspaces with changes since it.
522    pub changed_workspaces: Option<&'a str>,
523    /// Positional `[PATH]` scope: root-joined absolute file or directory inside
524    /// the root. Consumed CLI-side as one more workspace root (prefix scope),
525    /// so it composes with `workspace` the way multiple workspace roots
526    /// compose. `None` means whole-project scope.
527    pub scope: Option<PathBuf>,
528    /// Baseline file to compare finding counts against.
529    pub baseline: Option<&'a Path>,
530    /// Path to write the run's finding counts as a new baseline.
531    pub save_baseline: Option<&'a Path>,
532    /// Controls both halves of the baseline lifecycle: which buckets
533    /// `save_baseline` writes and how a loaded `baseline` is matched. An
534    /// identity save writes count and identity buckets, a count save writes
535    /// count buckets only.
536    pub baseline_mode: crate::baseline::HealthBaselineMode,
537    /// Whether `baseline_mode` was requested explicitly rather than defaulted.
538    /// A defaulted count save refuses to overwrite a baseline that carries
539    /// identity buckets, because dropping them breaks later identity-mode
540    /// comparisons; an explicit count request is treated as intent to
541    /// downgrade.
542    pub baseline_mode_explicit: bool,
543    /// Render the complexity findings section.
544    pub complexity: bool,
545    /// Render the per-file health scores section.
546    pub file_scores: bool,
547    /// Render the static coverage gaps section.
548    pub coverage_gaps: bool,
549    /// Let config-enabled coverage settings activate the coverage gaps
550    /// section even when it was not requested on this run.
551    pub config_activates_coverage_gaps: bool,
552    /// Render the churn-based hotspots section.
553    pub hotspots: bool,
554    /// Attribute hotspots to owners.
555    pub ownership: bool,
556    /// How owner identities are rendered (names or emails).
557    pub ownership_emails: Option<EmailMode>,
558    /// Render the refactoring targets section.
559    pub targets: bool,
560    /// Render the CSS / styling analytics section.
561    pub css: bool,
562    /// Scan all stylesheets for the CSS section instead of only changed files.
563    pub css_deep: bool,
564    /// Analyze the full project even when only a subset of sections was
565    /// requested, because scores and snapshots need complete data.
566    pub force_full: bool,
567    /// True when the score is the only requested surface, so output can skip
568    /// section rendering entirely.
569    pub score_only_output: bool,
570    /// Fail the run on coverage gaps instead of reporting them advisorily.
571    pub enforce_coverage_gap_gate: bool,
572    /// Effort estimation mode for refactoring targets.
573    pub effort: Option<EffortEstimate>,
574    /// Compute and render the overall health score.
575    pub score: bool,
576    /// Exit gate thresholds.
577    pub gates: HealthGateOptions,
578    /// Churn lookback window for hotspots (`90d`, `6m`, `1y`, or an ISO date).
579    pub since: Option<&'a str>,
580    /// Minimum commit count for a file to qualify as churn evidence.
581    pub min_commits: Option<u32>,
582    /// Include score-derivation explanations in the rendered output.
583    pub explain: bool,
584    /// Render the condensed summary view instead of full sections.
585    pub summary: bool,
586    /// Path to persist a health snapshot for later trend comparison.
587    pub save_snapshot: Option<PathBuf>,
588    /// Render the score trend against previously saved snapshots.
589    pub trend: bool,
590    /// Istanbul coverage inputs for CRAP scoring.
591    pub coverage_inputs: HealthCoverageInputs<'a>,
592    /// Print per-phase timing diagnostics.
593    pub performance: bool,
594    /// Runtime coverage sidecar options, when runtime analysis was requested.
595    pub runtime_coverage: Option<RuntimeCoverageOptions>,
596    /// Pre-recorded churn data file replacing live `git log` analysis.
597    pub churn_file: Option<&'a Path>,
598    /// Compatibility identity persisted with snapshots and checked by trends.
599    pub analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
600    /// Optional grouping mode for typed health output.
601    pub group_by: Option<GroupByMode>,
602    /// `--group` selector: keep only the groups whose key matches. Exact keys,
603    /// globs and `!`-prefixed negations. Ignored without `group_by`.
604    pub group_filter: Option<&'a [String]>,
605    /// `--trend-from`: compare against this snapshot file instead of the
606    /// newest file in `.fallow/snapshots/`. Implies `trend`.
607    pub trend_from: Option<&'a Path>,
608}
609
610/// Derive effective health section flags for CLI and embedders.
611#[must_use]
612fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
613    let score = options.score
614        || options.score_gate
615        || options.trend
616        || matches!(options.output, OutputFormat::Badge);
617    let any_section = options.complexity
618        || options.file_scores
619        || options.coverage_gaps
620        || options.hotspots
621        || options.targets
622        || score;
623    let effective_score = if any_section { score } else { true } || options.snapshot_requested;
624    let force_full = options.snapshot_requested || effective_score;
625
626    DerivedHealthSections {
627        any_section,
628        complexity: if any_section {
629            options.complexity
630        } else {
631            true
632        },
633        file_scores: if any_section {
634            options.file_scores
635        } else {
636            true
637        } || force_full,
638        coverage_gaps: if any_section {
639            options.coverage_gaps
640        } else {
641            false
642        },
643        hotspots: if any_section { options.hotspots } else { true }
644            || options.snapshot_requested
645            || options.trend,
646        targets: if any_section { options.targets } else { true },
647        css: options.css,
648        score: effective_score,
649        force_full,
650        score_only_output: is_health_score_only_output(options, score),
651    }
652}
653
654/// Normalize health run inputs into the engine-owned run contract.
655#[must_use]
656pub fn derive_health_run_options(input: HealthRunOptionsInput<'_>) -> HealthRunOptions<'_> {
657    let targets = input.targets || input.effort.is_some();
658    let sections = derive_health_sections(&HealthSectionOptions {
659        output: input.output,
660        complexity: input.complexity,
661        file_scores: input.file_scores,
662        coverage_gaps: input.coverage_gaps,
663        hotspots: input.hotspots,
664        targets,
665        css: input.css,
666        score: input.score,
667        score_gate: input.gates.min_score.is_some(),
668        snapshot_requested: input.snapshot_requested,
669        trend: input.trend,
670    });
671
672    HealthRunOptions {
673        thresholds: input.thresholds,
674        top: input.top,
675        sort: input.sort,
676        sections,
677        ownership: input.ownership && sections.hotspots,
678        ownership_emails: input.ownership_emails,
679        effort: input.effort,
680        gates: input.gates,
681        since: input.since,
682        min_commits: input.min_commits,
683        coverage_inputs: input.coverage_inputs,
684        runtime_coverage: input.runtime_coverage,
685    }
686}
687
688fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
689    score
690        && !options.complexity
691        && !options.file_scores
692        && !options.coverage_gaps
693        && !options.hotspots
694        && !options.targets
695        && !options.trend
696}
697
698/// Command-neutral runtime coverage input for health analysis.
699#[derive(Debug, Clone)]
700pub struct RuntimeCoverageOptions {
701    /// Path to the runtime coverage artifact captured by the sidecar.
702    pub path: PathBuf,
703    /// Minimum invocation count for a function to classify as hot-path.
704    pub min_invocations_hot: u64,
705    /// Minimum total trace volume before high-confidence `safe_to_delete` /
706    /// `review_required` verdicts may be emitted. Below this the sidecar caps
707    /// confidence at `medium`. `None` lets the sidecar use its spec-default
708    /// (5000).
709    pub min_observation_volume: Option<u32>,
710    /// Fraction of total trace count below which an invoked function is
711    /// classified as `low_traffic` rather than `active`. `None` lets the
712    /// sidecar use its spec-default (0.001 = 0.1%).
713    pub low_traffic_threshold: Option<f64>,
714    /// Verified license JWT forwarded to the closed-source sidecar.
715    pub license_jwt: String,
716    /// License or trial watermark to stamp on the runtime coverage output.
717    pub watermark: Option<RuntimeCoverageWatermark>,
718}
719
720/// Pre-parsed health input reused from another analysis in the same process.
721pub struct HealthSharedParseData {
722    /// Discovered files reused from the upstream analysis.
723    pub files: Vec<fallow_types::discover::DiscoveredFile>,
724    /// Parsed modules reused from the upstream analysis.
725    pub modules: Vec<fallow_types::extract::ModuleInfo>,
726    /// Dead-code results reused by advisory health surfaces that do not need the graph.
727    pub dead_code_results: Option<AnalysisResults>,
728    /// Workspace metadata discovered during config resolution.
729    pub workspaces: Vec<WorkspaceInfo>,
730    /// Full analysis output (graph + results) for file scoring.
731    pub analysis_output: Option<DeadCodeAnalysisArtifacts>,
732}
733
734#[cfg(test)]
735mod tests {
736    use super::*;
737
738    fn health_run_input() -> HealthRunOptionsInput<'static> {
739        HealthRunOptionsInput {
740            output: OutputFormat::Json,
741            thresholds: HealthThresholdOverrides::default(),
742            top: None,
743            sort: HealthSort::Cyclomatic,
744            complexity: false,
745            file_scores: false,
746            coverage_gaps: false,
747            hotspots: false,
748            ownership: false,
749            ownership_emails: None,
750            targets: false,
751            css: false,
752            effort: None,
753            score: false,
754            gates: HealthGateOptions::default(),
755            snapshot_requested: false,
756            trend: false,
757            since: None,
758            min_commits: None,
759            coverage_inputs: HealthCoverageInputs::default(),
760            runtime_coverage: None,
761        }
762    }
763
764    #[test]
765    fn health_execution_options_own_shared_runner_scope() {
766        let root = Path::new("/project");
767        let config_path = None;
768        let workspace = vec!["packages/app".to_string()];
769        let diff = DiffIndex::from_unified_diff(
770            "diff --git a/src/a.ts b/src/a.ts\n\
771             --- a/src/a.ts\n\
772             +++ b/src/a.ts\n\
773             @@ -0,0 +1,1 @@\n\
774             +new line\n",
775        );
776        let runtime_coverage = RuntimeCoverageOptions {
777            path: PathBuf::from("coverage/v8"),
778            min_invocations_hot: 10,
779            min_observation_volume: Some(500),
780            low_traffic_threshold: Some(0.01),
781            license_jwt: "test.jwt".to_string(),
782            watermark: None,
783        };
784
785        let options = HealthExecutionOptions {
786            root,
787            config_path: &config_path,
788            output: OutputFormat::Json,
789            no_cache: true,
790            threads: 2,
791            quiet: true,
792            complexity_breakdown: true,
793            thresholds: HealthThresholdOverrides::default(),
794            top: Some(5),
795            sort: HealthSort::Cognitive,
796            production: true,
797            production_override: Some(true),
798            allow_remote_extends: false,
799            changed_since: Some("HEAD~1"),
800            diff_index: Some(&diff),
801            use_shared_diff_index: false,
802            workspace: Some(&workspace),
803            changed_workspaces: None,
804            scope: None,
805            baseline: Some(Path::new(".fallow/health-baseline.json")),
806            save_baseline: None,
807            baseline_mode: crate::baseline::HealthBaselineMode::Count,
808            baseline_mode_explicit: false,
809            complexity: true,
810            file_scores: true,
811            coverage_gaps: false,
812            config_activates_coverage_gaps: false,
813            hotspots: true,
814            ownership: false,
815            ownership_emails: None,
816            targets: true,
817            css: false,
818            css_deep: false,
819            force_full: true,
820            score_only_output: false,
821            enforce_coverage_gap_gate: true,
822            effort: Some(EffortEstimate::Low),
823            score: true,
824            gates: HealthGateOptions {
825                min_score: Some(80.0),
826                min_severity: None,
827                report_only: false,
828                fail_on_stale_baseline: false,
829                fail_on_parse_error: false,
830                fail_on_issues: false,
831            },
832            since: Some("30d"),
833            min_commits: Some(2),
834            explain: true,
835            summary: false,
836            save_snapshot: Some(PathBuf::from(".fallow/snapshots/health.json")),
837            trend: true,
838            coverage_inputs: HealthCoverageInputs::default(),
839            performance: true,
840            runtime_coverage: Some(runtime_coverage),
841            churn_file: Some(Path::new("churn.json")),
842            analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
843            group_by: Some(GroupByMode::Directory),
844            group_filter: None,
845            trend_from: None,
846        };
847
848        assert_eq!(options.root, root);
849        assert!(
850            options
851                .diff_index
852                .is_some_and(|index| index.line_is_added("src/a.ts", 1))
853        );
854        assert_eq!(options.workspace, Some(workspace.as_slice()));
855        assert!(options.runtime_coverage.is_some());
856        assert_eq!(options.group_by, Some(GroupByMode::Directory));
857        assert_eq!(
858            options.save_snapshot.as_deref(),
859            Some(Path::new(".fallow/snapshots/health.json"))
860        );
861    }
862
863    #[test]
864    fn health_run_options_default_sections_match_health_defaults() {
865        let run = derive_health_run_options(health_run_input());
866
867        assert!(run.sections.complexity);
868        assert!(run.sections.file_scores);
869        assert!(run.sections.hotspots);
870        assert!(run.sections.targets);
871        assert!(run.sections.score);
872        assert!(!run.ownership);
873    }
874
875    #[test]
876    fn health_run_options_effort_requests_targets() {
877        let mut input = health_run_input();
878        input.effort = Some(EffortEstimate::Low);
879
880        let run = derive_health_run_options(input);
881
882        assert!(run.sections.targets);
883        assert_eq!(run.effort, Some(EffortEstimate::Low));
884    }
885
886    struct HealthExecutionOptionsFixture {
887        config_path: Option<PathBuf>,
888    }
889
890    impl HealthExecutionOptionsFixture {
891        const fn new() -> Self {
892            Self { config_path: None }
893        }
894
895        fn options<'a>(&'a self, root: &'a Path) -> HealthExecutionOptions<'a> {
896            HealthExecutionOptions {
897                root,
898                config_path: &self.config_path,
899                output: OutputFormat::Human,
900                no_cache: true,
901                threads: 1,
902                quiet: true,
903                complexity_breakdown: false,
904                thresholds: HealthThresholdOverrides::default(),
905                top: None,
906                sort: HealthSort::Cyclomatic,
907                production: false,
908                production_override: None,
909                allow_remote_extends: false,
910                changed_since: None,
911                diff_index: None,
912                use_shared_diff_index: false,
913                workspace: None,
914                changed_workspaces: None,
915                scope: None,
916                baseline: None,
917                save_baseline: None,
918                baseline_mode: crate::baseline::HealthBaselineMode::Count,
919                baseline_mode_explicit: false,
920                complexity: true,
921                file_scores: false,
922                coverage_gaps: false,
923                config_activates_coverage_gaps: false,
924                hotspots: false,
925                ownership: false,
926                ownership_emails: None,
927                targets: false,
928                css: false,
929                css_deep: false,
930                force_full: false,
931                score_only_output: false,
932                enforce_coverage_gap_gate: true,
933                effort: None,
934                score: false,
935                gates: HealthGateOptions::default(),
936                since: None,
937                min_commits: None,
938                explain: false,
939                summary: false,
940                save_snapshot: None,
941                trend: false,
942                coverage_inputs: HealthCoverageInputs::default(),
943                performance: false,
944                runtime_coverage: None,
945                churn_file: None,
946                analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
947                group_by: None,
948                group_filter: None,
949                trend_from: None,
950            }
951        }
952    }
953
954    /// The churn-file re-read is a time-of-check path: the up-front gate
955    /// accepted the file and it changed before the analysis read it again. The
956    /// CLI gate exits 2 on a file that is malformed at check time, so this is
957    /// the level that can drive the branch, and without the diagnostic such a
958    /// run reports the hotspot, churn and ownership sections as zero rather than
959    /// as unmeasured (issue #2734).
960    #[test]
961    fn a_churn_file_that_fails_the_re_read_records_the_skip() {
962        let project = tempfile::tempdir().expect("temp dir");
963        let root = project.path();
964        let churn_file = root.join("churn.json");
965        std::fs::write(&churn_file, "{ not json").expect("churn file");
966        let fixture = HealthExecutionOptionsFixture::new();
967        let mut options = fixture.options(root);
968        options.churn_file = Some(&churn_file);
969
970        assert!(
971            hotspots::fetch_churn_data(&options, &root.join(".fallow")).is_none(),
972            "an unreadable churn file yields no churn"
973        );
974
975        let recorded = fallow_config::health_stage_workspace_diagnostics(root);
976        let skip = recorded
977            .iter()
978            .find(|entry| entry.kind.id() == "hotspots-skipped")
979            .expect("the skip is recorded");
980        assert_eq!(
981            skip.kind,
982            fallow_types::workspace::WorkspaceDiagnosticKind::HotspotsSkipped {
983                cause: "churn-file-unreadable".to_owned(),
984            }
985        );
986        assert!(
987            skip.message.contains("churn.json"),
988            "the remedy names the file: {}",
989            skip.message
990        );
991    }
992
993    #[test]
994    fn standalone_health_precomputes_dead_code_when_default_crap_can_use_graph() {
995        let project = tempfile::tempdir().expect("temp dir");
996        let fixture = HealthExecutionOptionsFixture::new();
997        let options = fixture.options(project.path());
998        let config = crate::project_config::default_project_config(project.path()).config;
999
1000        assert!(should_precompute_dead_code_analysis(&options, &config));
1001    }
1002
1003    #[test]
1004    fn standalone_health_skips_precompute_when_no_section_needs_analysis_artifacts() {
1005        let project = tempfile::tempdir().expect("temp dir");
1006        let fixture = HealthExecutionOptionsFixture::new();
1007        let mut options = fixture.options(project.path());
1008        options.thresholds.max_crap = Some(0.0);
1009        let config = crate::project_config::default_project_config(project.path()).config;
1010
1011        assert!(!should_precompute_dead_code_analysis(&options, &config));
1012    }
1013
1014    #[test]
1015    fn standalone_health_precomputes_dead_code_for_target_sections() {
1016        let project = tempfile::tempdir().expect("temp dir");
1017        let fixture = HealthExecutionOptionsFixture::new();
1018        let mut options = fixture.options(project.path());
1019        options.thresholds.max_crap = Some(0.0);
1020        options.targets = true;
1021        let config = crate::project_config::default_project_config(project.path()).config;
1022
1023        assert!(should_precompute_dead_code_analysis(&options, &config));
1024    }
1025
1026    #[test]
1027    fn health_run_options_ownership_requires_hotspots() {
1028        let mut input = health_run_input();
1029        input.complexity = true;
1030        input.ownership = true;
1031
1032        let run = derive_health_run_options(input);
1033
1034        assert!(!run.sections.hotspots);
1035        assert!(!run.ownership);
1036
1037        let mut input = health_run_input();
1038        input.ownership = true;
1039        input.hotspots = true;
1040
1041        let run = derive_health_run_options(input);
1042
1043        assert!(run.sections.hotspots);
1044        assert!(run.ownership);
1045    }
1046
1047    #[test]
1048    fn health_run_options_score_gate_forces_score() {
1049        let mut input = health_run_input();
1050        input.gates.min_score = Some(90.0);
1051
1052        let run = derive_health_run_options(input);
1053
1054        assert!(run.sections.score);
1055        assert_eq!(run.gates.min_score, Some(90.0));
1056    }
1057
1058    #[test]
1059    fn coverage_root_accepts_posix_absolute() {
1060        assert!(validate_coverage_root_absolute(Some(Path::new("/ci/workspace"))).is_ok());
1061        assert!(
1062            validate_coverage_root_absolute(Some(Path::new("/home/runner/work/myapp"))).is_ok()
1063        );
1064    }
1065
1066    #[test]
1067    fn coverage_root_rejects_relative() {
1068        assert!(validate_coverage_root_absolute(Some(Path::new("src"))).is_err());
1069        assert!(validate_coverage_root_absolute(Some(Path::new("./coverage"))).is_err());
1070        assert!(validate_coverage_root_absolute(Some(Path::new("a/b/c"))).is_err());
1071    }
1072
1073    #[test]
1074    fn coverage_root_accepts_none() {
1075        assert!(validate_coverage_root_absolute(None).is_ok());
1076    }
1077
1078    #[test]
1079    fn coverage_root_accepts_windows_absolute_on_all_hosts() {
1080        assert!(validate_coverage_root_absolute(Some(Path::new(r"C:\ci\workspace"))).is_ok());
1081    }
1082}