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    pub output: OutputFormat,
288    pub complexity: bool,
289    pub file_scores: bool,
290    pub coverage_gaps: bool,
291    pub hotspots: bool,
292    pub targets: bool,
293    pub css: bool,
294    pub score: bool,
295    pub score_gate: bool,
296    pub snapshot_requested: bool,
297    pub 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    pub complexity: bool,
389    pub file_scores: bool,
390    pub coverage_gaps: bool,
391    pub config_activates_coverage_gaps: bool,
392    pub hotspots: bool,
393    pub ownership: bool,
394    pub ownership_emails: Option<EmailMode>,
395    pub targets: bool,
396    pub css: bool,
397    pub css_deep: bool,
398    pub force_full: bool,
399    pub score_only_output: bool,
400    pub enforce_coverage_gap_gate: bool,
401    pub effort: Option<EffortEstimate>,
402    pub score: bool,
403    pub gates: HealthGateOptions,
404    pub since: Option<&'a str>,
405    pub min_commits: Option<u32>,
406    pub explain: bool,
407    pub summary: bool,
408    pub save_snapshot: Option<PathBuf>,
409    pub trend: bool,
410    pub coverage_inputs: HealthCoverageInputs<'a>,
411    pub performance: bool,
412    pub runtime_coverage: Option<RuntimeCoverageOptions>,
413    pub churn_file: Option<&'a Path>,
414    /// Optional grouping mode for typed health output.
415    pub group_by: Option<GroupByMode>,
416}
417
418/// Derive effective health section flags for CLI and embedders.
419#[must_use]
420pub fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
421    let score = options.score
422        || options.score_gate
423        || options.trend
424        || matches!(options.output, OutputFormat::Badge);
425    let any_section = options.complexity
426        || options.file_scores
427        || options.coverage_gaps
428        || options.hotspots
429        || options.targets
430        || score;
431    let effective_score = if any_section { score } else { true } || options.snapshot_requested;
432    let force_full = options.snapshot_requested || effective_score;
433
434    DerivedHealthSections {
435        any_section,
436        complexity: if any_section {
437            options.complexity
438        } else {
439            true
440        },
441        file_scores: if any_section {
442            options.file_scores
443        } else {
444            true
445        } || force_full,
446        coverage_gaps: if any_section {
447            options.coverage_gaps
448        } else {
449            false
450        },
451        hotspots: if any_section { options.hotspots } else { true }
452            || options.snapshot_requested
453            || options.trend,
454        targets: if any_section { options.targets } else { true },
455        css: options.css,
456        score: effective_score,
457        force_full,
458        score_only_output: is_health_score_only_output(options, score),
459    }
460}
461
462/// Normalize health run inputs into the engine-owned run contract.
463#[must_use]
464pub fn derive_health_run_options(input: HealthRunOptionsInput<'_>) -> HealthRunOptions<'_> {
465    let targets = input.targets || input.effort.is_some();
466    let sections = derive_health_sections(&HealthSectionOptions {
467        output: input.output,
468        complexity: input.complexity,
469        file_scores: input.file_scores,
470        coverage_gaps: input.coverage_gaps,
471        hotspots: input.hotspots,
472        targets,
473        css: input.css,
474        score: input.score,
475        score_gate: input.gates.min_score.is_some(),
476        snapshot_requested: input.snapshot_requested,
477        trend: input.trend,
478    });
479
480    HealthRunOptions {
481        thresholds: input.thresholds,
482        top: input.top,
483        sort: input.sort,
484        sections,
485        ownership: input.ownership && sections.hotspots,
486        ownership_emails: input.ownership_emails,
487        effort: input.effort,
488        gates: input.gates,
489        since: input.since,
490        min_commits: input.min_commits,
491        coverage_inputs: input.coverage_inputs,
492        runtime_coverage: input.runtime_coverage,
493    }
494}
495
496fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
497    score
498        && !options.complexity
499        && !options.file_scores
500        && !options.coverage_gaps
501        && !options.hotspots
502        && !options.targets
503        && !options.trend
504}
505
506/// Input for deriving effective programmatic complexity sections.
507#[derive(Debug, Clone)]
508pub struct ComplexitySectionOptions {
509    pub complexity: bool,
510    pub file_scores: bool,
511    pub coverage_gaps: bool,
512    pub hotspots: bool,
513    pub ownership: bool,
514    pub targets: bool,
515    pub css: bool,
516    pub score: bool,
517}
518
519/// Derived section selection for programmatic health / complexity runs.
520#[derive(Debug, Clone, Copy, PartialEq, Eq)]
521pub struct DerivedComplexityOptions {
522    pub any_section: bool,
523    pub complexity: bool,
524    pub file_scores: bool,
525    pub coverage_gaps: bool,
526    pub hotspots: bool,
527    pub ownership: bool,
528    pub targets: bool,
529    pub force_full: bool,
530    pub score_only_output: bool,
531    pub score: bool,
532}
533
534/// Derive effective programmatic health / complexity section flags.
535#[must_use]
536pub fn derive_complexity_sections(options: &ComplexitySectionOptions) -> DerivedComplexityOptions {
537    let requested_hotspots = options.hotspots || options.ownership;
538    let sections = derive_health_sections(&HealthSectionOptions {
539        output: OutputFormat::Human,
540        complexity: options.complexity,
541        file_scores: options.file_scores,
542        coverage_gaps: options.coverage_gaps,
543        hotspots: requested_hotspots,
544        targets: options.targets,
545        css: options.css,
546        score: options.score,
547        score_gate: false,
548        snapshot_requested: false,
549        trend: false,
550    });
551
552    DerivedComplexityOptions {
553        any_section: sections.any_section,
554        complexity: sections.complexity,
555        file_scores: sections.file_scores,
556        coverage_gaps: sections.coverage_gaps,
557        hotspots: sections.hotspots,
558        ownership: options.ownership && sections.hotspots,
559        targets: sections.targets,
560        force_full: sections.force_full,
561        score_only_output: sections.score_only_output,
562        score: sections.score,
563    }
564}
565
566/// Normalized programmatic complexity / health inputs shared by API, NAPI, and
567/// engine-backed runners.
568#[derive(Debug, Clone, PartialEq)]
569pub struct ComplexityRunOptions<'a> {
570    pub thresholds: HealthThresholdOverrides,
571    pub top: Option<usize>,
572    pub sort: HealthSort,
573    pub complexity_breakdown: bool,
574    pub sections: DerivedComplexityOptions,
575    pub ownership_emails: Option<EmailMode>,
576    pub effort: Option<EffortEstimate>,
577    pub css: bool,
578    pub since: Option<&'a str>,
579    pub min_commits: Option<u32>,
580    pub coverage_inputs: HealthCoverageInputs<'a>,
581}
582
583/// Command-neutral runtime coverage input for health analysis.
584#[derive(Debug, Clone)]
585pub struct RuntimeCoverageOptions {
586    pub path: PathBuf,
587    pub min_invocations_hot: u64,
588    /// Minimum total trace volume before high-confidence `safe_to_delete` /
589    /// `review_required` verdicts may be emitted. Below this the sidecar caps
590    /// confidence at `medium`. `None` lets the sidecar use its spec-default
591    /// (5000).
592    pub min_observation_volume: Option<u32>,
593    /// Fraction of total trace count below which an invoked function is
594    /// classified as `low_traffic` rather than `active`. `None` lets the
595    /// sidecar use its spec-default (0.001 = 0.1%).
596    pub low_traffic_threshold: Option<f64>,
597    pub license_jwt: String,
598    pub watermark: Option<RuntimeCoverageWatermark>,
599}
600
601/// Pre-parsed health input reused from another analysis in the same process.
602pub struct HealthSharedParseData {
603    pub files: Vec<fallow_types::discover::DiscoveredFile>,
604    pub modules: Vec<fallow_types::extract::ModuleInfo>,
605    /// Dead-code results reused by advisory health surfaces that do not need the graph.
606    pub dead_code_results: Option<AnalysisResults>,
607    pub workspaces: Vec<WorkspaceInfo>,
608    /// Full analysis output (graph + results) for file scoring.
609    pub analysis_output: Option<DeadCodeAnalysisArtifacts>,
610}
611
612#[cfg(test)]
613mod tests {
614    use super::*;
615
616    fn health_run_input() -> HealthRunOptionsInput<'static> {
617        HealthRunOptionsInput {
618            output: OutputFormat::Json,
619            thresholds: HealthThresholdOverrides::default(),
620            top: None,
621            sort: HealthSort::Cyclomatic,
622            complexity: false,
623            file_scores: false,
624            coverage_gaps: false,
625            hotspots: false,
626            ownership: false,
627            ownership_emails: None,
628            targets: false,
629            css: false,
630            effort: None,
631            score: false,
632            gates: HealthGateOptions::default(),
633            snapshot_requested: false,
634            trend: false,
635            since: None,
636            min_commits: None,
637            coverage_inputs: HealthCoverageInputs::default(),
638            runtime_coverage: None,
639        }
640    }
641
642    #[test]
643    fn health_execution_options_own_shared_runner_scope() {
644        let root = Path::new("/project");
645        let config_path = None;
646        let workspace = vec!["packages/app".to_string()];
647        let diff = DiffIndex::from_unified_diff(
648            "diff --git a/src/a.ts b/src/a.ts\n\
649             --- a/src/a.ts\n\
650             +++ b/src/a.ts\n\
651             @@ -0,0 +1,1 @@\n\
652             +new line\n",
653        );
654        let runtime_coverage = RuntimeCoverageOptions {
655            path: PathBuf::from("coverage/v8"),
656            min_invocations_hot: 10,
657            min_observation_volume: Some(500),
658            low_traffic_threshold: Some(0.01),
659            license_jwt: "test.jwt".to_string(),
660            watermark: None,
661        };
662
663        let options = HealthExecutionOptions {
664            root,
665            config_path: &config_path,
666            output: OutputFormat::Json,
667            no_cache: true,
668            threads: 2,
669            quiet: true,
670            complexity_breakdown: true,
671            thresholds: HealthThresholdOverrides::default(),
672            top: Some(5),
673            sort: HealthSort::Cognitive,
674            production: true,
675            production_override: Some(true),
676            allow_remote_extends: false,
677            changed_since: Some("HEAD~1"),
678            diff_index: Some(&diff),
679            use_shared_diff_index: false,
680            workspace: Some(&workspace),
681            changed_workspaces: None,
682            baseline: Some(Path::new(".fallow/health-baseline.json")),
683            save_baseline: None,
684            complexity: true,
685            file_scores: true,
686            coverage_gaps: false,
687            config_activates_coverage_gaps: false,
688            hotspots: true,
689            ownership: false,
690            ownership_emails: None,
691            targets: true,
692            css: false,
693            css_deep: false,
694            force_full: true,
695            score_only_output: false,
696            enforce_coverage_gap_gate: true,
697            effort: Some(EffortEstimate::Low),
698            score: true,
699            gates: HealthGateOptions {
700                min_score: Some(80.0),
701                min_severity: None,
702                report_only: false,
703            },
704            since: Some("30d"),
705            min_commits: Some(2),
706            explain: true,
707            summary: false,
708            save_snapshot: Some(PathBuf::from(".fallow/snapshots/health.json")),
709            trend: true,
710            coverage_inputs: HealthCoverageInputs::default(),
711            performance: true,
712            runtime_coverage: Some(runtime_coverage),
713            churn_file: Some(Path::new("churn.json")),
714            group_by: Some(GroupByMode::Directory),
715        };
716
717        assert_eq!(options.root, root);
718        assert!(
719            options
720                .diff_index
721                .is_some_and(|index| index.line_is_added("src/a.ts", 1))
722        );
723        assert_eq!(options.workspace, Some(workspace.as_slice()));
724        assert!(options.runtime_coverage.is_some());
725        assert_eq!(options.group_by, Some(GroupByMode::Directory));
726        assert_eq!(
727            options.save_snapshot.as_deref(),
728            Some(Path::new(".fallow/snapshots/health.json"))
729        );
730    }
731
732    #[test]
733    fn health_run_options_default_sections_match_health_defaults() {
734        let run = derive_health_run_options(health_run_input());
735
736        assert!(run.sections.complexity);
737        assert!(run.sections.file_scores);
738        assert!(run.sections.hotspots);
739        assert!(run.sections.targets);
740        assert!(run.sections.score);
741        assert!(!run.ownership);
742    }
743
744    #[test]
745    fn health_run_options_effort_requests_targets() {
746        let mut input = health_run_input();
747        input.effort = Some(EffortEstimate::Low);
748
749        let run = derive_health_run_options(input);
750
751        assert!(run.sections.targets);
752        assert_eq!(run.effort, Some(EffortEstimate::Low));
753    }
754
755    struct HealthExecutionOptionsFixture {
756        config_path: Option<PathBuf>,
757    }
758
759    impl HealthExecutionOptionsFixture {
760        const fn new() -> Self {
761            Self { config_path: None }
762        }
763
764        fn options<'a>(&'a self, root: &'a Path) -> HealthExecutionOptions<'a> {
765            HealthExecutionOptions {
766                root,
767                config_path: &self.config_path,
768                output: OutputFormat::Human,
769                no_cache: true,
770                threads: 1,
771                quiet: true,
772                complexity_breakdown: false,
773                thresholds: HealthThresholdOverrides::default(),
774                top: None,
775                sort: HealthSort::Cyclomatic,
776                production: false,
777                production_override: None,
778                allow_remote_extends: false,
779                changed_since: None,
780                diff_index: None,
781                use_shared_diff_index: false,
782                workspace: None,
783                changed_workspaces: None,
784                baseline: None,
785                save_baseline: None,
786                complexity: true,
787                file_scores: false,
788                coverage_gaps: false,
789                config_activates_coverage_gaps: false,
790                hotspots: false,
791                ownership: false,
792                ownership_emails: None,
793                targets: false,
794                css: false,
795                css_deep: false,
796                force_full: false,
797                score_only_output: false,
798                enforce_coverage_gap_gate: true,
799                effort: None,
800                score: false,
801                gates: HealthGateOptions::default(),
802                since: None,
803                min_commits: None,
804                explain: false,
805                summary: false,
806                save_snapshot: None,
807                trend: false,
808                coverage_inputs: HealthCoverageInputs::default(),
809                performance: false,
810                runtime_coverage: None,
811                churn_file: None,
812                group_by: None,
813            }
814        }
815    }
816
817    #[test]
818    fn standalone_health_precomputes_dead_code_when_default_crap_can_use_graph() {
819        let project = tempfile::tempdir().expect("temp dir");
820        let fixture = HealthExecutionOptionsFixture::new();
821        let options = fixture.options(project.path());
822        let config = crate::project_config::default_project_config(project.path()).config;
823
824        assert!(should_precompute_dead_code_analysis(&options, &config));
825    }
826
827    #[test]
828    fn standalone_health_skips_precompute_when_no_section_needs_analysis_artifacts() {
829        let project = tempfile::tempdir().expect("temp dir");
830        let fixture = HealthExecutionOptionsFixture::new();
831        let mut options = fixture.options(project.path());
832        options.thresholds.max_crap = Some(0.0);
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_precomputes_dead_code_for_target_sections() {
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        options.targets = true;
845        let config = crate::project_config::default_project_config(project.path()).config;
846
847        assert!(should_precompute_dead_code_analysis(&options, &config));
848    }
849
850    #[test]
851    fn health_run_options_ownership_requires_hotspots() {
852        let mut input = health_run_input();
853        input.complexity = true;
854        input.ownership = true;
855
856        let run = derive_health_run_options(input);
857
858        assert!(!run.sections.hotspots);
859        assert!(!run.ownership);
860
861        let mut input = health_run_input();
862        input.ownership = true;
863        input.hotspots = true;
864
865        let run = derive_health_run_options(input);
866
867        assert!(run.sections.hotspots);
868        assert!(run.ownership);
869    }
870
871    #[test]
872    fn health_run_options_score_gate_forces_score() {
873        let mut input = health_run_input();
874        input.gates.min_score = Some(90.0);
875
876        let run = derive_health_run_options(input);
877
878        assert!(run.sections.score);
879        assert_eq!(run.gates.min_score, Some(90.0));
880    }
881
882    #[test]
883    fn coverage_root_accepts_posix_absolute() {
884        assert!(validate_coverage_root_absolute(Some(Path::new("/ci/workspace"))).is_ok());
885        assert!(
886            validate_coverage_root_absolute(Some(Path::new("/home/runner/work/myapp"))).is_ok()
887        );
888    }
889
890    #[test]
891    fn coverage_root_rejects_relative() {
892        assert!(validate_coverage_root_absolute(Some(Path::new("src"))).is_err());
893        assert!(validate_coverage_root_absolute(Some(Path::new("./coverage"))).is_err());
894        assert!(validate_coverage_root_absolute(Some(Path::new("a/b/c"))).is_err());
895    }
896
897    #[test]
898    fn coverage_root_accepts_none() {
899        assert!(validate_coverage_root_absolute(None).is_ok());
900    }
901
902    #[test]
903    fn coverage_root_accepts_windows_absolute_on_all_hosts() {
904        assert!(validate_coverage_root_absolute(Some(Path::new(r"C:\ci\workspace"))).is_ok());
905    }
906}