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