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 churn_file;
23mod component_rollup;
24mod core_pipeline;
25mod coverage_gaps;
26mod coverage_intelligence;
27mod coverage_settings;
28mod css_analytics;
29mod derived_sections;
30mod execute;
31mod file_scores;
32mod filters;
33mod finding_sort;
34mod findings;
35mod findings_pipeline;
36mod framework_health;
37mod grouping;
38mod health_error;
39mod hotspots;
40mod ignore;
41mod large_functions;
42mod output_build;
43pub mod ownership;
44mod package_json;
45mod pipeline;
46mod react_hooks;
47mod result;
48mod runner;
49mod runtime_filter;
50mod runtime_sections;
51mod scope;
52pub mod scoring;
53pub mod styling_score;
54mod tailwind_theme;
55mod targets;
56mod threshold_overrides;
57mod timings;
58mod vital_data;
59mod vital_signs_scope;
60
61pub use crate::results::HealthAnalysisResult;
62pub use churn_file::validate_health_churn_file;
63pub use css_analytics::StylingAnalysisArtifacts;
64use derived_sections::{
65    HealthDerivedSectionInput, HealthDerivedSections, prepare_health_derived_sections,
66};
67use execute::HealthOptions;
68pub use execute::execute_health_inner;
69use file_scores::{
70    FileScoresAndChurnInput, compute_file_scores_and_churn, health_file_scores_slice,
71    print_slow_churn_note,
72};
73use finding_sort::sort_findings;
74pub use health_error::HealthError;
75pub use hotspots::{
76    TargetChurnEvidence, TargetChurnOptions, TargetChurnOutcome, analyze_target_churn,
77};
78pub use pipeline::{HealthPipelineInputs, HealthScopeInputs};
79pub use runner::{
80    run_ungrouped_health, run_ungrouped_health_with_session,
81    run_ungrouped_health_with_session_artifacts,
82};
83use vital_data::{HealthVitalData, HealthVitalDataInput, prepare_health_vital_data};
84use vital_signs_scope::{
85    SubsetFilter, VitalSignsAndCountsInput, apply_duplication_metrics,
86    compute_vital_signs_and_counts,
87};
88
89pub(crate) fn build_styling_analysis_artifacts(
90    files: &[crate::discover::DiscoveredFile],
91    config: &fallow_config::ResolvedConfig,
92) -> StylingAnalysisArtifacts {
93    css_analytics::build_styling_analysis_artifacts(files, config)
94}
95
96/// Build health shared parse data from retained dead-code artifacts.
97#[must_use]
98pub fn shared_parse_data_from_artifacts(
99    results: &AnalysisResults,
100    graph: Option<RetainedModuleGraph>,
101    modules: Option<Vec<crate::source::ModuleInfo>>,
102    files: Option<Vec<crate::discover::DiscoveredFile>>,
103    workspaces: Vec<WorkspaceInfo>,
104    script_used_packages: impl IntoIterator<Item = String>,
105) -> Option<HealthSharedParseData> {
106    let (Some(modules), Some(files)) = (modules, files) else {
107        return None;
108    };
109    let script_used_packages: FxHashSet<String> = script_used_packages.into_iter().collect();
110    let analysis_output = graph.map(|graph| DeadCodeAnalysisArtifacts {
111        results: results.clone(),
112        timings: None,
113        graph: Some(graph),
114        modules: None,
115        files: None,
116        script_used_packages: script_used_packages.clone(),
117        file_hashes: FxHashMap::default(),
118    });
119    Some(HealthSharedParseData {
120        files,
121        modules,
122        dead_code_results: Some(results.clone()),
123        workspaces,
124        analysis_output,
125    })
126}
127
128/// Return true when health sections will need dead-code analysis artifacts.
129///
130/// Callers that already have a session and parsed modules can precompute these
131/// artifacts once, then pass them into [`HealthPipelineInputs`] to avoid a
132/// second graph and dead-code analysis inside the health pipeline.
133#[must_use]
134pub fn should_precompute_dead_code_analysis(
135    options: &HealthExecutionOptions<'_>,
136    config: &fallow_config::ResolvedConfig,
137) -> bool {
138    let max_crap = options
139        .thresholds
140        .max_crap
141        .unwrap_or(config.health.max_crap);
142    options.file_scores
143        || options.coverage_gaps
144        || options.config_activates_coverage_gaps
145        || options.hotspots
146        || options.targets
147        || options.force_full
148        || max_crap > 0.0
149        || options.runtime_coverage.is_some()
150}
151
152/// Command-neutral grouping resolver contract for `--group-by` health output.
153///
154/// The CLI owns the concrete resolver (CODEOWNERS parsing, package discovery);
155/// the engine grouping pass only needs these three read operations, so it stays
156/// generic over the resolver instead of depending on the CLI type.
157pub trait HealthGroupResolver {
158    /// Stable label for the active grouping mode (`owner` / `directory` / ...).
159    fn mode_label(&self) -> &'static str;
160    /// Resolve a repo-relative path to its group key and the matching rule.
161    fn resolve_with_rule(&self, rel_path: &Path) -> (String, Option<String>);
162    /// Section owners for the group a path belongs to, when known.
163    fn section_owners_of(&self, rel_path: &Path) -> Option<&[String]>;
164}
165
166/// Placeholder grouping resolver for runs without `--group-by` (the programmatic
167/// API path). Constructed only as `None`, so its methods are never invoked.
168#[derive(Debug, Clone, Copy)]
169pub enum NoGroupResolver {}
170
171#[expect(
172    clippy::uninhabited_references,
173    reason = "NoGroupResolver is uninhabited; these methods are unreachable and exist only to satisfy the trait bound for the group-less programmatic path"
174)]
175impl HealthGroupResolver for NoGroupResolver {
176    fn mode_label(&self) -> &'static str {
177        match *self {}
178    }
179    fn resolve_with_rule(&self, _rel_path: &Path) -> (String, Option<String>) {
180        match *self {}
181    }
182    fn section_owners_of(&self, _rel_path: &Path) -> Option<&[String]> {
183        match *self {}
184    }
185}
186
187/// Runtime coverage analysis seam.
188///
189/// Runtime coverage execution drives the closed-source `fallow-cov` sidecar
190/// (license verification, subprocess spawning), which stays in the CLI. The
191/// engine calls this callback only when [`HealthExecutionOptions::runtime_coverage`]
192/// is set, so the default and programmatic paths never touch it.
193///
194/// The seam prints its own errors (license / sidecar diagnostics), so it returns
195/// the already-printed exit code as a bare `u8`. The engine wraps that code in
196/// [`HealthError::Printed`] so the CLI boundary honors the code without emitting
197/// a second error document.
198pub type RuntimeCoverageAnalyzer<'a> = dyn Fn(&RuntimeCoverageOptions, RuntimeCoverageSeamInput<'_>) -> Result<RuntimeCoverageReport, u8>
199    + 'a;
200
201/// Inputs the runtime coverage seam needs from the analysis core.
202pub struct RuntimeCoverageSeamInput<'a> {
203    pub root: &'a Path,
204    pub modules: &'a [fallow_types::extract::ModuleInfo],
205    pub analysis_output: &'a DeadCodeAnalysisArtifacts,
206    pub istanbul_coverage: Option<&'a scoring::IstanbulCoverage>,
207    pub file_paths: &'a rustc_hash::FxHashMap<fallow_types::discover::FileId, &'a PathBuf>,
208    pub ignore_set: &'a globset::GlobSet,
209    pub changed_files: Option<&'a rustc_hash::FxHashSet<PathBuf>>,
210    pub ws_roots: Option<&'a [PathBuf]>,
211    pub top: Option<usize>,
212    pub codeowners_path: Option<&'a str>,
213    pub quiet: bool,
214    pub output: OutputFormat,
215}
216
217/// CLI-supplied callbacks the command-neutral health pipeline needs.
218///
219/// The pipeline itself stays cli-free; these are the seams the CLI threads in.
220pub struct HealthSeams<'a> {
221    /// Runs the runtime coverage sidecar (only when runtime coverage is set).
222    pub runtime_coverage_analyzer: &'a RuntimeCoverageAnalyzer<'a>,
223    /// Records module-graph structure facts (graph node count, edge count) into
224    /// the CLI's process-global telemetry sinks. Best-effort; the engine never
225    /// owns telemetry state.
226    pub note_graph_structure: &'a dyn Fn(usize, usize),
227}
228
229/// Command-neutral sort criteria for health complexity findings.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231pub enum HealthSort {
232    Severity,
233    Cyclomatic,
234    Cognitive,
235    Lines,
236}
237
238/// Command-neutral threshold overrides for health complexity findings.
239#[derive(Debug, Clone, Copy, Default, PartialEq)]
240pub struct HealthThresholdOverrides {
241    pub max_cyclomatic: Option<u16>,
242    pub max_cognitive: Option<u16>,
243    /// Maximum CRAP score threshold. Functions meeting or exceeding this score
244    /// are reported as complexity findings.
245    pub max_crap: Option<f64>,
246}
247
248/// Command-neutral Istanbul coverage inputs for health CRAP scoring.
249#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
250pub struct HealthCoverageInputs<'a> {
251    pub coverage: Option<&'a Path>,
252    /// Absolute coverage-path prefix to strip before rebasing files onto the
253    /// project root.
254    pub coverage_root: Option<&'a Path>,
255}
256
257/// Validate that a coverage-data root is absolute under Unix or Windows path
258/// conventions.
259///
260/// Istanbul coverage paths often come from a Linux CI runner even when fallow
261/// is invoked on another host, so POSIX-rooted paths and Windows drive paths
262/// are both accepted on every platform.
263pub fn validate_coverage_root_absolute(coverage_root: Option<&Path>) -> Result<(), String> {
264    if let Some(path) = coverage_root
265        && !is_absolute_path_any_platform(path)
266    {
267        return Err(format!(
268            "--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'.",
269            path.display()
270        ));
271    }
272    Ok(())
273}
274
275/// Command-neutral health exit gate options.
276#[derive(Debug, Clone, Copy, Default, PartialEq)]
277pub struct HealthGateOptions {
278    pub min_score: Option<f64>,
279    pub min_severity: Option<FindingSeverity>,
280    /// Render the score and findings but never fail CI on a health gate.
281    pub report_only: bool,
282}
283
284/// Input for deriving effective health sections from command-neutral flags.
285#[derive(Debug, Clone)]
286pub struct HealthSectionOptions {
287    output: OutputFormat,
288    complexity: bool,
289    file_scores: bool,
290    coverage_gaps: bool,
291    hotspots: bool,
292    targets: bool,
293    css: bool,
294    score: bool,
295    score_gate: bool,
296    snapshot_requested: bool,
297    trend: bool,
298}
299
300/// Derived section selection for health runs.
301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
302pub struct DerivedHealthSections {
303    pub any_section: bool,
304    pub complexity: bool,
305    pub file_scores: bool,
306    pub coverage_gaps: bool,
307    pub hotspots: bool,
308    pub targets: bool,
309    pub css: bool,
310    pub score: bool,
311    pub force_full: bool,
312    pub score_only_output: bool,
313}
314
315/// Command-neutral inputs used to normalize a health run before it reaches a
316/// concrete runner.
317#[derive(Debug, Clone)]
318pub struct HealthRunOptionsInput<'a> {
319    pub output: OutputFormat,
320    pub thresholds: HealthThresholdOverrides,
321    pub top: Option<usize>,
322    pub sort: HealthSort,
323    pub complexity: bool,
324    pub file_scores: bool,
325    pub coverage_gaps: bool,
326    pub hotspots: bool,
327    pub ownership: bool,
328    pub ownership_emails: Option<EmailMode>,
329    pub targets: bool,
330    pub css: bool,
331    pub effort: Option<EffortEstimate>,
332    pub score: bool,
333    pub gates: HealthGateOptions,
334    pub snapshot_requested: bool,
335    pub trend: bool,
336    pub since: Option<&'a str>,
337    pub min_commits: Option<u32>,
338    pub coverage_inputs: HealthCoverageInputs<'a>,
339    pub runtime_coverage: Option<RuntimeCoverageOptions>,
340}
341
342/// Normalized health inputs shared by CLI, API, NAPI, and future runners.
343#[derive(Debug, Clone)]
344pub struct HealthRunOptions<'a> {
345    pub thresholds: HealthThresholdOverrides,
346    pub top: Option<usize>,
347    pub sort: HealthSort,
348    pub sections: DerivedHealthSections,
349    pub ownership: bool,
350    pub ownership_emails: Option<EmailMode>,
351    pub effort: Option<EffortEstimate>,
352    pub gates: HealthGateOptions,
353    pub since: Option<&'a str>,
354    pub min_commits: Option<u32>,
355    pub coverage_inputs: HealthCoverageInputs<'a>,
356    pub runtime_coverage: Option<RuntimeCoverageOptions>,
357}
358
359/// Command-neutral inputs needed to execute a health analysis.
360///
361/// These fields are shared runner inputs rather than rendering concerns.
362#[derive(Debug, Clone)]
363pub struct HealthExecutionOptions<'a> {
364    pub root: &'a Path,
365    pub config_path: &'a Option<PathBuf>,
366    pub output: OutputFormat,
367    pub no_cache: bool,
368    pub threads: usize,
369    pub quiet: bool,
370    /// Include per-decision-point complexity contributions in typed findings.
371    ///
372    /// This changes the produced health result shape, so it belongs to the
373    /// runner input contract rather than CLI rendering options.
374    pub complexity_breakdown: bool,
375    pub thresholds: HealthThresholdOverrides,
376    pub top: Option<usize>,
377    pub sort: HealthSort,
378    pub production: bool,
379    pub production_override: Option<bool>,
380    pub allow_remote_extends: bool,
381    pub changed_since: Option<&'a str>,
382    pub diff_index: Option<&'a DiffIndex>,
383    pub use_shared_diff_index: bool,
384    pub workspace: Option<&'a [String]>,
385    pub changed_workspaces: Option<&'a str>,
386    pub baseline: Option<&'a Path>,
387    pub save_baseline: Option<&'a Path>,
388    /// Controls both halves of the baseline lifecycle: which buckets
389    /// `save_baseline` writes and how a loaded `baseline` is matched. An
390    /// identity save writes count and identity buckets, a count save writes
391    /// count buckets only.
392    pub baseline_mode: crate::baseline::HealthBaselineMode,
393    pub complexity: bool,
394    pub file_scores: bool,
395    pub coverage_gaps: bool,
396    pub config_activates_coverage_gaps: bool,
397    pub hotspots: bool,
398    pub ownership: bool,
399    pub ownership_emails: Option<EmailMode>,
400    pub targets: bool,
401    pub css: bool,
402    pub css_deep: bool,
403    pub force_full: bool,
404    pub score_only_output: bool,
405    pub enforce_coverage_gap_gate: bool,
406    pub effort: Option<EffortEstimate>,
407    pub score: bool,
408    pub gates: HealthGateOptions,
409    pub since: Option<&'a str>,
410    pub min_commits: Option<u32>,
411    pub explain: bool,
412    pub summary: bool,
413    pub save_snapshot: Option<PathBuf>,
414    pub trend: bool,
415    pub coverage_inputs: HealthCoverageInputs<'a>,
416    pub performance: bool,
417    pub runtime_coverage: Option<RuntimeCoverageOptions>,
418    pub churn_file: Option<&'a Path>,
419    /// Compatibility identity persisted with snapshots and checked by trends.
420    pub analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
421    /// Optional grouping mode for typed health output.
422    pub group_by: Option<GroupByMode>,
423}
424
425/// Derive effective health section flags for CLI and embedders.
426#[must_use]
427fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
428    let score = options.score
429        || options.score_gate
430        || options.trend
431        || matches!(options.output, OutputFormat::Badge);
432    let any_section = options.complexity
433        || options.file_scores
434        || options.coverage_gaps
435        || options.hotspots
436        || options.targets
437        || score;
438    let effective_score = if any_section { score } else { true } || options.snapshot_requested;
439    let force_full = options.snapshot_requested || effective_score;
440
441    DerivedHealthSections {
442        any_section,
443        complexity: if any_section {
444            options.complexity
445        } else {
446            true
447        },
448        file_scores: if any_section {
449            options.file_scores
450        } else {
451            true
452        } || force_full,
453        coverage_gaps: if any_section {
454            options.coverage_gaps
455        } else {
456            false
457        },
458        hotspots: if any_section { options.hotspots } else { true }
459            || options.snapshot_requested
460            || options.trend,
461        targets: if any_section { options.targets } else { true },
462        css: options.css,
463        score: effective_score,
464        force_full,
465        score_only_output: is_health_score_only_output(options, score),
466    }
467}
468
469/// Normalize health run inputs into the engine-owned run contract.
470#[must_use]
471pub fn derive_health_run_options(input: HealthRunOptionsInput<'_>) -> HealthRunOptions<'_> {
472    let targets = input.targets || input.effort.is_some();
473    let sections = derive_health_sections(&HealthSectionOptions {
474        output: input.output,
475        complexity: input.complexity,
476        file_scores: input.file_scores,
477        coverage_gaps: input.coverage_gaps,
478        hotspots: input.hotspots,
479        targets,
480        css: input.css,
481        score: input.score,
482        score_gate: input.gates.min_score.is_some(),
483        snapshot_requested: input.snapshot_requested,
484        trend: input.trend,
485    });
486
487    HealthRunOptions {
488        thresholds: input.thresholds,
489        top: input.top,
490        sort: input.sort,
491        sections,
492        ownership: input.ownership && sections.hotspots,
493        ownership_emails: input.ownership_emails,
494        effort: input.effort,
495        gates: input.gates,
496        since: input.since,
497        min_commits: input.min_commits,
498        coverage_inputs: input.coverage_inputs,
499        runtime_coverage: input.runtime_coverage,
500    }
501}
502
503fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
504    score
505        && !options.complexity
506        && !options.file_scores
507        && !options.coverage_gaps
508        && !options.hotspots
509        && !options.targets
510        && !options.trend
511}
512
513/// Input for deriving effective programmatic complexity sections.
514#[derive(Debug, Clone)]
515pub struct ComplexitySectionOptions {
516    complexity: bool,
517    file_scores: bool,
518    coverage_gaps: bool,
519    hotspots: bool,
520    ownership: bool,
521    targets: bool,
522    css: bool,
523    score: bool,
524}
525
526/// Derived section selection for programmatic health / complexity runs.
527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
528pub struct DerivedComplexityOptions {
529    any_section: bool,
530    complexity: bool,
531    file_scores: bool,
532    coverage_gaps: bool,
533    hotspots: bool,
534    ownership: bool,
535    targets: bool,
536    force_full: bool,
537    score_only_output: bool,
538    score: bool,
539}
540
541/// Derive effective programmatic health / complexity section flags.
542#[must_use]
543pub fn derive_complexity_sections(options: &ComplexitySectionOptions) -> DerivedComplexityOptions {
544    let requested_hotspots = options.hotspots || options.ownership;
545    let sections = derive_health_sections(&HealthSectionOptions {
546        output: OutputFormat::Human,
547        complexity: options.complexity,
548        file_scores: options.file_scores,
549        coverage_gaps: options.coverage_gaps,
550        hotspots: requested_hotspots,
551        targets: options.targets,
552        css: options.css,
553        score: options.score,
554        score_gate: false,
555        snapshot_requested: false,
556        trend: false,
557    });
558
559    DerivedComplexityOptions {
560        any_section: sections.any_section,
561        complexity: sections.complexity,
562        file_scores: sections.file_scores,
563        coverage_gaps: sections.coverage_gaps,
564        hotspots: sections.hotspots,
565        ownership: options.ownership && sections.hotspots,
566        targets: sections.targets,
567        force_full: sections.force_full,
568        score_only_output: sections.score_only_output,
569        score: sections.score,
570    }
571}
572
573/// Normalized programmatic complexity / health inputs shared by API, NAPI, and
574/// engine-backed runners.
575#[derive(Debug, Clone, PartialEq)]
576pub struct ComplexityRunOptions<'a> {
577    thresholds: HealthThresholdOverrides,
578    top: Option<usize>,
579    sort: HealthSort,
580    complexity_breakdown: bool,
581    sections: DerivedComplexityOptions,
582    ownership_emails: Option<EmailMode>,
583    effort: Option<EffortEstimate>,
584    css: bool,
585    since: Option<&'a str>,
586    min_commits: Option<u32>,
587    coverage_inputs: HealthCoverageInputs<'a>,
588}
589
590/// Command-neutral runtime coverage input for health analysis.
591#[derive(Debug, Clone)]
592pub struct RuntimeCoverageOptions {
593    pub path: PathBuf,
594    pub min_invocations_hot: u64,
595    /// Minimum total trace volume before high-confidence `safe_to_delete` /
596    /// `review_required` verdicts may be emitted. Below this the sidecar caps
597    /// confidence at `medium`. `None` lets the sidecar use its spec-default
598    /// (5000).
599    pub min_observation_volume: Option<u32>,
600    /// Fraction of total trace count below which an invoked function is
601    /// classified as `low_traffic` rather than `active`. `None` lets the
602    /// sidecar use its spec-default (0.001 = 0.1%).
603    pub low_traffic_threshold: Option<f64>,
604    pub license_jwt: String,
605    pub watermark: Option<RuntimeCoverageWatermark>,
606}
607
608/// Pre-parsed health input reused from another analysis in the same process.
609pub struct HealthSharedParseData {
610    pub files: Vec<fallow_types::discover::DiscoveredFile>,
611    pub modules: Vec<fallow_types::extract::ModuleInfo>,
612    /// Dead-code results reused by advisory health surfaces that do not need the graph.
613    pub dead_code_results: Option<AnalysisResults>,
614    pub workspaces: Vec<WorkspaceInfo>,
615    /// Full analysis output (graph + results) for file scoring.
616    pub analysis_output: Option<DeadCodeAnalysisArtifacts>,
617}
618
619#[cfg(test)]
620mod tests {
621    use super::*;
622
623    fn health_run_input() -> HealthRunOptionsInput<'static> {
624        HealthRunOptionsInput {
625            output: OutputFormat::Json,
626            thresholds: HealthThresholdOverrides::default(),
627            top: None,
628            sort: HealthSort::Cyclomatic,
629            complexity: false,
630            file_scores: false,
631            coverage_gaps: false,
632            hotspots: false,
633            ownership: false,
634            ownership_emails: None,
635            targets: false,
636            css: false,
637            effort: None,
638            score: false,
639            gates: HealthGateOptions::default(),
640            snapshot_requested: false,
641            trend: false,
642            since: None,
643            min_commits: None,
644            coverage_inputs: HealthCoverageInputs::default(),
645            runtime_coverage: None,
646        }
647    }
648
649    #[test]
650    fn health_execution_options_own_shared_runner_scope() {
651        let root = Path::new("/project");
652        let config_path = None;
653        let workspace = vec!["packages/app".to_string()];
654        let diff = DiffIndex::from_unified_diff(
655            "diff --git a/src/a.ts b/src/a.ts\n\
656             --- a/src/a.ts\n\
657             +++ b/src/a.ts\n\
658             @@ -0,0 +1,1 @@\n\
659             +new line\n",
660        );
661        let runtime_coverage = RuntimeCoverageOptions {
662            path: PathBuf::from("coverage/v8"),
663            min_invocations_hot: 10,
664            min_observation_volume: Some(500),
665            low_traffic_threshold: Some(0.01),
666            license_jwt: "test.jwt".to_string(),
667            watermark: None,
668        };
669
670        let options = HealthExecutionOptions {
671            root,
672            config_path: &config_path,
673            output: OutputFormat::Json,
674            no_cache: true,
675            threads: 2,
676            quiet: true,
677            complexity_breakdown: true,
678            thresholds: HealthThresholdOverrides::default(),
679            top: Some(5),
680            sort: HealthSort::Cognitive,
681            production: true,
682            production_override: Some(true),
683            allow_remote_extends: false,
684            changed_since: Some("HEAD~1"),
685            diff_index: Some(&diff),
686            use_shared_diff_index: false,
687            workspace: Some(&workspace),
688            changed_workspaces: None,
689            baseline: Some(Path::new(".fallow/health-baseline.json")),
690            save_baseline: None,
691            baseline_mode: crate::baseline::HealthBaselineMode::Count,
692            complexity: true,
693            file_scores: true,
694            coverage_gaps: false,
695            config_activates_coverage_gaps: false,
696            hotspots: true,
697            ownership: false,
698            ownership_emails: None,
699            targets: true,
700            css: false,
701            css_deep: false,
702            force_full: true,
703            score_only_output: false,
704            enforce_coverage_gap_gate: true,
705            effort: Some(EffortEstimate::Low),
706            score: true,
707            gates: HealthGateOptions {
708                min_score: Some(80.0),
709                min_severity: None,
710                report_only: false,
711            },
712            since: Some("30d"),
713            min_commits: Some(2),
714            explain: true,
715            summary: false,
716            save_snapshot: Some(PathBuf::from(".fallow/snapshots/health.json")),
717            trend: true,
718            coverage_inputs: HealthCoverageInputs::default(),
719            performance: true,
720            runtime_coverage: Some(runtime_coverage),
721            churn_file: Some(Path::new("churn.json")),
722            analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
723            group_by: Some(GroupByMode::Directory),
724        };
725
726        assert_eq!(options.root, root);
727        assert!(
728            options
729                .diff_index
730                .is_some_and(|index| index.line_is_added("src/a.ts", 1))
731        );
732        assert_eq!(options.workspace, Some(workspace.as_slice()));
733        assert!(options.runtime_coverage.is_some());
734        assert_eq!(options.group_by, Some(GroupByMode::Directory));
735        assert_eq!(
736            options.save_snapshot.as_deref(),
737            Some(Path::new(".fallow/snapshots/health.json"))
738        );
739    }
740
741    #[test]
742    fn health_run_options_default_sections_match_health_defaults() {
743        let run = derive_health_run_options(health_run_input());
744
745        assert!(run.sections.complexity);
746        assert!(run.sections.file_scores);
747        assert!(run.sections.hotspots);
748        assert!(run.sections.targets);
749        assert!(run.sections.score);
750        assert!(!run.ownership);
751    }
752
753    #[test]
754    fn health_run_options_effort_requests_targets() {
755        let mut input = health_run_input();
756        input.effort = Some(EffortEstimate::Low);
757
758        let run = derive_health_run_options(input);
759
760        assert!(run.sections.targets);
761        assert_eq!(run.effort, Some(EffortEstimate::Low));
762    }
763
764    struct HealthExecutionOptionsFixture {
765        config_path: Option<PathBuf>,
766    }
767
768    impl HealthExecutionOptionsFixture {
769        const fn new() -> Self {
770            Self { config_path: None }
771        }
772
773        fn options<'a>(&'a self, root: &'a Path) -> HealthExecutionOptions<'a> {
774            HealthExecutionOptions {
775                root,
776                config_path: &self.config_path,
777                output: OutputFormat::Human,
778                no_cache: true,
779                threads: 1,
780                quiet: true,
781                complexity_breakdown: false,
782                thresholds: HealthThresholdOverrides::default(),
783                top: None,
784                sort: HealthSort::Cyclomatic,
785                production: false,
786                production_override: None,
787                allow_remote_extends: false,
788                changed_since: None,
789                diff_index: None,
790                use_shared_diff_index: false,
791                workspace: None,
792                changed_workspaces: None,
793                baseline: None,
794                save_baseline: None,
795                baseline_mode: crate::baseline::HealthBaselineMode::Count,
796                complexity: true,
797                file_scores: false,
798                coverage_gaps: false,
799                config_activates_coverage_gaps: false,
800                hotspots: false,
801                ownership: false,
802                ownership_emails: None,
803                targets: false,
804                css: false,
805                css_deep: false,
806                force_full: false,
807                score_only_output: false,
808                enforce_coverage_gap_gate: true,
809                effort: None,
810                score: false,
811                gates: HealthGateOptions::default(),
812                since: None,
813                min_commits: None,
814                explain: false,
815                summary: false,
816                save_snapshot: None,
817                trend: false,
818                coverage_inputs: HealthCoverageInputs::default(),
819                performance: false,
820                runtime_coverage: None,
821                churn_file: None,
822                analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
823                group_by: None,
824            }
825        }
826    }
827
828    #[test]
829    fn standalone_health_precomputes_dead_code_when_default_crap_can_use_graph() {
830        let project = tempfile::tempdir().expect("temp dir");
831        let fixture = HealthExecutionOptionsFixture::new();
832        let options = fixture.options(project.path());
833        let config = crate::project_config::default_project_config(project.path()).config;
834
835        assert!(should_precompute_dead_code_analysis(&options, &config));
836    }
837
838    #[test]
839    fn standalone_health_skips_precompute_when_no_section_needs_analysis_artifacts() {
840        let project = tempfile::tempdir().expect("temp dir");
841        let fixture = HealthExecutionOptionsFixture::new();
842        let mut options = fixture.options(project.path());
843        options.thresholds.max_crap = Some(0.0);
844        let config = crate::project_config::default_project_config(project.path()).config;
845
846        assert!(!should_precompute_dead_code_analysis(&options, &config));
847    }
848
849    #[test]
850    fn standalone_health_precomputes_dead_code_for_target_sections() {
851        let project = tempfile::tempdir().expect("temp dir");
852        let fixture = HealthExecutionOptionsFixture::new();
853        let mut options = fixture.options(project.path());
854        options.thresholds.max_crap = Some(0.0);
855        options.targets = true;
856        let config = crate::project_config::default_project_config(project.path()).config;
857
858        assert!(should_precompute_dead_code_analysis(&options, &config));
859    }
860
861    #[test]
862    fn health_run_options_ownership_requires_hotspots() {
863        let mut input = health_run_input();
864        input.complexity = true;
865        input.ownership = true;
866
867        let run = derive_health_run_options(input);
868
869        assert!(!run.sections.hotspots);
870        assert!(!run.ownership);
871
872        let mut input = health_run_input();
873        input.ownership = true;
874        input.hotspots = true;
875
876        let run = derive_health_run_options(input);
877
878        assert!(run.sections.hotspots);
879        assert!(run.ownership);
880    }
881
882    #[test]
883    fn health_run_options_score_gate_forces_score() {
884        let mut input = health_run_input();
885        input.gates.min_score = Some(90.0);
886
887        let run = derive_health_run_options(input);
888
889        assert!(run.sections.score);
890        assert_eq!(run.gates.min_score, Some(90.0));
891    }
892
893    #[test]
894    fn coverage_root_accepts_posix_absolute() {
895        assert!(validate_coverage_root_absolute(Some(Path::new("/ci/workspace"))).is_ok());
896        assert!(
897            validate_coverage_root_absolute(Some(Path::new("/home/runner/work/myapp"))).is_ok()
898        );
899    }
900
901    #[test]
902    fn coverage_root_rejects_relative() {
903        assert!(validate_coverage_root_absolute(Some(Path::new("src"))).is_err());
904        assert!(validate_coverage_root_absolute(Some(Path::new("./coverage"))).is_err());
905        assert!(validate_coverage_root_absolute(Some(Path::new("a/b/c"))).is_err());
906    }
907
908    #[test]
909    fn coverage_root_accepts_none() {
910        assert!(validate_coverage_root_absolute(None).is_ok());
911    }
912
913    #[test]
914    fn coverage_root_accepts_windows_absolute_on_all_hosts() {
915        assert!(validate_coverage_root_absolute(Some(Path::new(r"C:\ci\workspace"))).is_ok());
916    }
917}