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