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