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