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