Skip to main content

fallow_cli/health/
mod.rs

1//! `fallow health` complexity / health command.
2//!
3//! The command-neutral analysis pipeline (scoring, hotspots, targets, grouping,
4//! coverage gaps, vital signs, report assembly) lives in
5//! `fallow_engine::health` API. This module owns the CLI orchestration that the
6//! engine intentionally does not: command option validation, workspace /
7//! changed-file / shared-diff scope resolution, CODEOWNERS-backed
8//! grouping-resolver construction, the runtime coverage sidecar seam,
9//! telemetry recording, exit-code gating, and human / machine rendering.
10
11pub mod coverage;
12
13/// Health scoring helpers, re-exported from the engine for CLI consumers that
14/// still address them through `crate::health::scoring`.
15pub use fallow_engine::health::scoring;
16
17use std::process::ExitCode;
18use std::time::Instant;
19
20use colored::Colorize;
21use fallow_config::OutputFormat;
22use fallow_engine::health::{
23    HealthError, HealthExecutionOptions, HealthGateOptions, HealthGroupResolver,
24    HealthPipelineInputs, HealthScopeInputs, HealthSeams, HealthSharedParseData, HealthSort,
25    RuntimeCoverageSeamInput, execute_health_inner, validate_health_churn_file,
26};
27
28use crate::check::{get_changed_files, resolve_workspace_scope};
29use crate::error::emit_error;
30use crate::report;
31use crate::report::OwnershipResolver;
32
33/// Sort criteria for complexity output.
34#[derive(Clone, clap::ValueEnum)]
35pub enum SortBy {
36    Severity,
37    Cyclomatic,
38    Cognitive,
39    Lines,
40}
41
42impl From<SortBy> for HealthSort {
43    fn from(sort: SortBy) -> Self {
44        match sort {
45            SortBy::Severity => Self::Severity,
46            SortBy::Cyclomatic => Self::Cyclomatic,
47            SortBy::Cognitive => Self::Cognitive,
48            SortBy::Lines => Self::Lines,
49        }
50    }
51}
52
53pub type HealthOptions<'a> = HealthExecutionOptions<'a>;
54
55/// CLI-only semantic overlay options for `health --type-coupling`.
56pub struct TypeAwareHealthOptions<'a> {
57    /// CLI override: `Some(true)` for `--type-aware`, `Some(false)` for
58    /// `--no-type-aware`, `None` when neither flag was passed.
59    pub enabled: Option<bool>,
60    pub requested: bool,
61    pub unfiltered: bool,
62    pub projects: &'a [std::path::PathBuf],
63    pub require: Option<fallow_config::TypeAwareRequire>,
64}
65
66impl HealthGroupResolver for OwnershipResolver {
67    fn mode_label(&self) -> &'static str {
68        OwnershipResolver::mode_label(self)
69    }
70
71    fn resolve_with_rule(&self, rel_path: &std::path::Path) -> (String, Option<String>) {
72        OwnershipResolver::resolve_with_rule(self, rel_path)
73    }
74
75    fn section_owners_of(&self, rel_path: &std::path::Path) -> Option<&[String]> {
76        OwnershipResolver::section_owners_of(self, rel_path)
77    }
78}
79
80/// Resolve the diff index for a health run: an explicit `--diff-file` index
81/// wins, otherwise the process-shared diff cache when the caller opted in.
82fn health_diff_index<'a>(opts: &HealthOptions<'a>) -> Option<&'a fallow_output::DiffIndex> {
83    match opts.diff_index {
84        Some(index) => Some(index),
85        None if opts.use_shared_diff_index => crate::report::ci::diff_filter::shared_diff_index(),
86        None => None,
87    }
88}
89
90/// Build the CODEOWNERS / package-backed grouping resolver for `--group-by`.
91fn build_health_group_resolver(
92    opts: &HealthOptions<'_>,
93    config: &fallow_config::ResolvedConfig,
94) -> Result<Option<OwnershipResolver>, ExitCode> {
95    crate::runtime_support::build_ownership_resolver_for_mode(
96        opts.group_by,
97        opts.root,
98        config.codeowners.as_deref(),
99        opts.output,
100    )
101}
102
103/// Record health telemetry from the finished report. Mirrors the per-analysis
104/// telemetry the other commands record; lives in the CLI because the telemetry
105/// sinks are process-global CLI state.
106fn record_health_telemetry(report: &fallow_output::HealthReport, coverage_gaps_has_findings: bool) {
107    if coverage_gaps_has_findings && report.findings.is_empty() {
108        crate::telemetry::note_findings_present(true);
109    } else {
110        crate::telemetry::note_result_count(report.findings.len());
111    }
112    crate::telemetry::note_analysis_scale(
113        Some(report.summary.files_analyzed),
114        Some(report.summary.functions_analyzed),
115    );
116}
117
118/// Build the engine seam callbacks: the runtime coverage sidecar adapter and
119/// the graph-structure telemetry hook.
120fn health_seams<'a>() -> HealthSeams<'a> {
121    HealthSeams {
122        runtime_coverage_analyzer: &runtime_coverage_seam,
123        note_graph_structure: &|module_count, edge_count| {
124            crate::telemetry::note_graph_structure_counts(module_count, edge_count);
125        },
126    }
127}
128
129/// Adapt the engine's runtime coverage seam input to the CLI coverage module,
130/// which owns the closed-source sidecar (license verification, subprocess
131/// spawning, signal handling).
132#[expect(
133    clippy::needless_pass_by_value,
134    reason = "by-value input matches the engine RuntimeCoverageAnalyzer seam signature"
135)]
136fn runtime_coverage_seam(
137    options: &fallow_engine::health::RuntimeCoverageOptions,
138    input: RuntimeCoverageSeamInput<'_>,
139) -> Result<fallow_output::RuntimeCoverageReport, u8> {
140    coverage::analyze(
141        options,
142        &coverage::RuntimeCoverageAnalysisInput {
143            root: input.root,
144            modules: input.modules,
145            analysis_output: input.analysis_output,
146            istanbul_coverage: input.istanbul_coverage,
147            file_paths: input.file_paths,
148            ignore_set: input.ignore_set,
149            changed_files: input.changed_files,
150            ws_roots: input.ws_roots,
151            top: input.top,
152            codeowners_path: input.codeowners_path,
153            quiet: input.quiet,
154            output: input.output,
155        },
156    )
157}
158
159/// Resolve the command-neutral scope inputs the engine needs: changed files,
160/// the diff index, workspace roots, and the grouping resolver.
161fn build_health_scope_inputs<'a>(
162    opts: &HealthOptions<'a>,
163    config: &fallow_config::ResolvedConfig,
164) -> Result<HealthScopeInputs<'a, OwnershipResolver>, ExitCode> {
165    let changed_files = opts
166        .changed_since
167        .and_then(|git_ref| get_changed_files(opts.root, git_ref));
168    let diff_index = health_diff_index(opts);
169    let ws_roots = resolve_workspace_scope(
170        opts.root,
171        opts.workspace,
172        opts.changed_workspaces,
173        opts.output,
174    )?;
175    let group_resolver = build_health_group_resolver(opts, config)?;
176    Ok(HealthScopeInputs {
177        changed_files,
178        diff_index,
179        ws_roots,
180        group_resolver,
181    })
182}
183
184/// Translate an engine [`HealthError`] into a CLI exit code at the command
185/// boundary. `Message` is rendered here (the engine no longer prints fatal
186/// errors); `Printed` was already emitted by a lower layer (the runtime-coverage
187/// seam), so its exit code is honored without a second error document.
188fn health_err_to_exit(error: HealthError, output: OutputFormat) -> ExitCode {
189    match error {
190        HealthError::Message { message, exit_code } => emit_error(&message, exit_code, output),
191        HealthError::Printed(code) => ExitCode::from(code),
192    }
193}
194
195/// Load config for a health run, validating coverage-root and churn-file inputs
196/// up front (loud exit 2 on a malformed input).
197pub fn load_health_config(
198    opts: &HealthOptions<'_>,
199) -> Result<(fallow_config::ResolvedConfig, f64), ExitCode> {
200    fallow_engine::health::validate_coverage_root_absolute(opts.coverage_inputs.coverage_root)
201        .map_err(|e| emit_error(&e, 2, opts.output))?;
202    validate_health_churn_file(opts).map_err(|e| health_err_to_exit(e, opts.output))?;
203    let t = Instant::now();
204    let config = crate::load_config_for_analysis(
205        opts.root,
206        opts.config_path,
207        crate::ConfigLoadOptions {
208            output: opts.output,
209            no_cache: opts.no_cache,
210            threads: opts.threads,
211            production_override: opts
212                .production_override
213                .or_else(|| opts.production.then_some(true)),
214            quiet: opts.quiet,
215            allow_remote_extends: opts.allow_remote_extends,
216        },
217        fallow_config::ProductionAnalysis::Health,
218    )?;
219    let config_ms = t.elapsed().as_secs_f64() * 1000.0;
220    Ok((config, config_ms))
221}
222
223/// Run health analysis using pre-parsed modules from the dead-code pipeline.
224///
225/// Skips file discovery and parsing (saves ~1.9s on 21K-file projects).
226pub fn execute_health_with_shared_parse(
227    opts: &HealthOptions<'_>,
228    shared: HealthSharedParseData,
229) -> Result<HealthResult, ExitCode> {
230    let (config, config_ms) = load_health_config(opts)?;
231    let scope_inputs = build_health_scope_inputs(opts, &config)?;
232    let workspace_diagnostics = fallow_config::workspace_diagnostics_for(&config.root);
233    let workspaces = shared.workspaces;
234    let seams = health_seams();
235    let result = execute_health_inner(
236        opts,
237        HealthPipelineInputs {
238            config,
239            files: shared.files,
240            modules: shared.modules,
241            config_ms,
242            discover_ms: 0.0,
243            parse_ms: 0.0,
244            parse_cpu_ms: 0.0,
245            shared_parse: true,
246            pre_computed_analysis: shared.analysis_output,
247            dead_code_results: shared.dead_code_results,
248            styling_artifacts: None,
249            pre_computed_duplication: None,
250            workspaces,
251            workspace_diagnostics,
252        },
253        scope_inputs,
254        &seams,
255    )
256    .map_err(|e| health_err_to_exit(e, opts.output))?;
257    record_health_telemetry(&result.report, result.coverage_gaps_has_findings);
258    Ok(result)
259}
260
261pub fn execute_health(opts: &HealthOptions<'_>) -> Result<HealthResult, ExitCode> {
262    let (config, config_ms) = load_health_config(opts)?;
263    execute_health_with_config(opts, config, config_ms)
264}
265
266pub fn execute_health_with_config(
267    opts: &HealthOptions<'_>,
268    config: fallow_config::ResolvedConfig,
269    config_ms: f64,
270) -> Result<HealthResult, ExitCode> {
271    let seams = health_seams();
272    let result = execute_health_with_config_and_seams(opts, config, config_ms, &seams)?;
273    record_health_telemetry(&result.report, result.coverage_gaps_has_findings);
274    Ok(result)
275}
276
277fn execute_health_with_config_and_seams(
278    opts: &HealthOptions<'_>,
279    config: fallow_config::ResolvedConfig,
280    config_ms: f64,
281    seams: &HealthSeams<'_>,
282) -> Result<HealthResult, ExitCode> {
283    let t = Instant::now();
284    let session = fallow_engine::session::AnalysisSession::from_resolved_config(config)
285        .map_err(|e| emit_error(&format!("analysis failed: {e}"), 2, opts.output))?;
286    let discover_ms = t.elapsed().as_secs_f64() * 1000.0;
287    let parts = session.parsed_parts_uncached(true);
288    let pre_computed_analysis =
289        fallow_engine::health::should_precompute_dead_code_analysis(opts, session.config())
290            .then(|| session.analyze_dead_code_with_parsed_modules(&parts.modules))
291            .transpose()
292            .map_err(|e| emit_error(&format!("analysis failed: {e}"), 2, opts.output))?;
293    let config = parts.config;
294    let files = parts.files;
295    let modules = parts.modules;
296    let workspaces = parts.workspaces;
297    let workspace_diagnostics = if pre_computed_analysis.is_some() {
298        session.current_workspace_diagnostics()
299    } else {
300        parts.workspace_diagnostics
301    };
302    let parse_ms = parts.parse_ms;
303    let parse_cpu_ms = parts.parse_cpu_ms;
304
305    let scope_inputs = build_health_scope_inputs(opts, &config)?;
306    execute_health_inner(
307        opts,
308        HealthPipelineInputs {
309            config,
310            files,
311            modules,
312            config_ms,
313            discover_ms,
314            parse_ms,
315            parse_cpu_ms,
316            shared_parse: false,
317            dead_code_results: None,
318            styling_artifacts: None,
319            pre_computed_analysis,
320            pre_computed_duplication: None,
321            workspaces,
322            workspace_diagnostics,
323        },
324        scope_inputs,
325        seams,
326    )
327    .map_err(|e| health_err_to_exit(e, opts.output))
328}
329
330pub fn benchmark_execute_health_with_response(
331    opts: &HealthOptions<'_>,
332    response_bytes: &[u8],
333    request_len: &std::cell::Cell<usize>,
334) -> Result<HealthResult, ExitCode> {
335    let analyzer = |options: &fallow_engine::health::RuntimeCoverageOptions,
336                    input: RuntimeCoverageSeamInput<'_>| {
337        coverage::analyze_with_transport(
338            options,
339            &coverage::RuntimeCoverageAnalysisInput {
340                root: input.root,
341                modules: input.modules,
342                analysis_output: input.analysis_output,
343                istanbul_coverage: input.istanbul_coverage,
344                file_paths: input.file_paths,
345                ignore_set: input.ignore_set,
346                changed_files: input.changed_files,
347                ws_roots: input.ws_roots,
348                top: input.top,
349                codeowners_path: input.codeowners_path,
350                quiet: input.quiet,
351                output: input.output,
352            },
353            |request, _quiet, output| {
354                let (response, len) =
355                    coverage::in_process_response_transport(request, response_bytes, output)?;
356                request_len.set(len);
357                Ok(response)
358            },
359        )
360    };
361    let seams = HealthSeams {
362        runtime_coverage_analyzer: &analyzer,
363        note_graph_structure: &|_module_count, _edge_count| {},
364    };
365    let (config, config_ms) = load_health_config(opts)?;
366    execute_health_with_config_and_seams(opts, config, config_ms, &seams)
367}
368
369pub fn run_health(
370    opts: &HealthOptions<'_>,
371    json_style: crate::json_style::JsonStyle,
372    type_aware: &TypeAwareHealthOptions<'_>,
373) -> ExitCode {
374    let mut completeness_failed = false;
375    let (config, config_ms) = match load_health_config(opts) {
376        Ok(config) => config,
377        Err(code) => return code,
378    };
379    let resolved_type_aware = match resolve_type_aware_health_options(type_aware, &config) {
380        Ok(options) => options,
381        Err(message) => return emit_error(&message, 2, opts.output),
382    };
383    let requested = type_aware.requested || (type_aware.unfiltered && resolved_type_aware.enabled);
384    let semantic = if requested {
385        let enabled = resolved_type_aware.enabled;
386        if !enabled {
387            return emit_error(
388                "--type-coupling requires --type-aware or typeAware.enabled in config",
389                2,
390                opts.output,
391            );
392        }
393        let projects = resolved_type_aware.projects;
394        let require = resolved_type_aware.require;
395        let outcome = match fallow_api::analyze_type_coupling(opts.root, &projects, &[]) {
396            Ok(outcome) => outcome,
397            Err(error) => {
398                return emit_error(
399                    &format!("Type-aware coupling failed: {error}"),
400                    2,
401                    opts.output,
402                );
403            }
404        };
405        completeness_failed = require == fallow_config::TypeAwareRequire::Complete
406            && outcome.report.status != fallow_types::semantic::SemanticCompleteness::Complete;
407        Some(outcome)
408    } else {
409        None
410    };
411    let mut execution_opts = opts.clone();
412    if let Some(identity) = semantic
413        .as_ref()
414        .and_then(|outcome| outcome.type_aware.meta.identity.clone())
415    {
416        execution_opts.analysis_identity = identity;
417    }
418    let mut result = match execute_health_with_config(&execution_opts, config, config_ms) {
419        Ok(result) => result,
420        Err(code) => return code,
421    };
422    let required_completeness = result.config.type_aware.require.into();
423    result.type_aware_meta = semantic.map(|outcome| {
424        let mut meta = outcome.type_aware.meta;
425        meta.required_completeness = Some(required_completeness);
426        meta
427    });
428    if let Some(ref timings) = result.timings {
429        report::print_health_performance(timings, opts.output, json_style);
430    }
431    let code = print_health_result(
432        &result,
433        HealthPrintOptions {
434            quiet: opts.quiet,
435            explain: opts.explain,
436            gates: opts.gates,
437            summary: opts.summary,
438            summary_heading: true,
439            show_explain_tip: true,
440            type_aware_scope: None,
441            skip_score_and_trend: false,
442            css_requested: opts.css,
443            json_style,
444        },
445    );
446    if code == ExitCode::SUCCESS && completeness_failed {
447        ExitCode::from(1)
448    } else {
449        code
450    }
451}
452
453pub struct ResolvedTypeAwareHealthOptions {
454    pub enabled: bool,
455    pub projects: Vec<std::path::PathBuf>,
456    pub require: fallow_config::TypeAwareRequire,
457}
458
459pub fn resolve_type_aware_health_options(
460    options: &TypeAwareHealthOptions<'_>,
461    config: &fallow_config::ResolvedConfig,
462) -> Result<ResolvedTypeAwareHealthOptions, String> {
463    let env_enabled = std::env::var("FALLOW_TYPE_AWARE")
464        .ok()
465        .map(|value| match value.trim().to_ascii_lowercase().as_str() {
466            "1" | "true" | "yes" | "on" => Ok(true),
467            "0" | "false" | "no" | "off" => Ok(false),
468            _ => Err(
469                "FALLOW_TYPE_AWARE must be one of true, false, 1, 0, yes, no, on, or off"
470                    .to_string(),
471            ),
472        })
473        .transpose()?;
474    let enabled = options
475        .enabled
476        .or(env_enabled)
477        .unwrap_or(config.type_aware.enabled);
478    let projects = if !options.projects.is_empty() {
479        options.projects.to_vec()
480    } else if let Some(value) = std::env::var_os("FALLOW_TYPE_AWARE_PROJECTS") {
481        std::env::split_paths(&value).collect()
482    } else {
483        config
484            .type_aware
485            .projects
486            .iter()
487            .map(std::path::PathBuf::from)
488            .collect()
489    };
490    let require = if let Some(require) = options.require {
491        require
492    } else if let Ok(value) = std::env::var("FALLOW_TYPE_AWARE_REQUIRE") {
493        match value.trim().to_ascii_lowercase().as_str() {
494            "best-effort" => fallow_config::TypeAwareRequire::BestEffort,
495            "complete" => fallow_config::TypeAwareRequire::Complete,
496            _ => {
497                return Err("FALLOW_TYPE_AWARE_REQUIRE must be best-effort or complete".to_string());
498            }
499        }
500    } else {
501        config.type_aware.require
502    };
503    Ok(ResolvedTypeAwareHealthOptions {
504        enabled,
505        projects,
506        require,
507    })
508}
509
510/// Result of executing health analysis without printing.
511pub type HealthResult =
512    fallow_engine::health::HealthAnalysisResult<crate::report::OwnershipResolver>;
513
514/// Print health results and return appropriate exit code.
515///
516/// When called from combined mode (`fallow --score` / `fallow --trend`),
517/// `skip_score_and_trend` MUST be `true`: the orientation header already
518/// renders both blocks and rendering them a second time here would duplicate
519/// the lines. Standalone `fallow health` invocations pass `false`.
520///
521/// Exit-code gating (when `report_only` is `false`): the score gate
522/// (`--min-score`), the findings gate (`--min-severity`, or any finding when
523/// no gate flag is set), the runtime-coverage gate, and the coverage-gap gate
524/// are OR-combined. `report_only` short-circuits all of them to
525/// `ExitCode::SUCCESS` after rendering. Combined and audit callers pass
526/// `report_only: false` (they own their own gate semantics).
527///
528/// Callers that pass `min_score: Some(_)` must ensure
529/// `result.report.health_score` is `Some` (the CLI guarantees this because
530/// `--min-score` implies `--score`). If the score is missing the score gate
531/// cannot evaluate, so a direct API caller that requests a score gate without
532/// computing the score would get a permissive `ExitCode::SUCCESS`.
533#[derive(Clone, Copy)]
534pub struct HealthPrintOptions {
535    pub quiet: bool,
536    pub explain: bool,
537    pub gates: HealthGateOptions,
538    pub summary: bool,
539    pub summary_heading: bool,
540    pub show_explain_tip: bool,
541    pub type_aware_scope: Option<&'static str>,
542    pub skip_score_and_trend: bool,
543    /// Whether `--css` was requested. Forwarded to the human renderer so an empty
544    /// CSS result (no import-reachable stylesheet) is explained rather than
545    /// silently omitted. Defaults `false` for callers that do not request CSS.
546    pub css_requested: bool,
547    pub json_style: crate::json_style::JsonStyle,
548}
549
550pub fn print_health_result(result: &HealthResult, options: HealthPrintOptions) -> ExitCode {
551    let ctx = health_report_context(result, options);
552    let report_code = report::print_health_report(
553        &result.report,
554        result.grouping.as_ref(),
555        result.group_resolver.as_ref(),
556        &ctx,
557        result.config.output,
558    );
559    if report_code != ExitCode::SUCCESS {
560        return report_code;
561    }
562
563    if options.gates.report_only {
564        return ExitCode::SUCCESS;
565    }
566
567    if health_exit_gate_failed(result, options) {
568        return ExitCode::from(1);
569    }
570    if result.should_fail_on_coverage_gaps && result.coverage_gaps_has_findings {
571        return ExitCode::from(1);
572    }
573    maybe_print_score_gate_note(result, options);
574
575    ExitCode::SUCCESS
576}
577
578fn health_report_context(
579    result: &HealthResult,
580    options: HealthPrintOptions,
581) -> report::ReportContext<'_> {
582    report::ReportContext {
583        root: &result.config.root,
584        rules: &result.config.rules,
585        workspace_diagnostics: &result.workspace_diagnostics,
586        elapsed: result.elapsed,
587        quiet: options.quiet,
588        explain: options.explain,
589        type_aware: result.type_aware_meta.as_ref(),
590        type_aware_scope: options.type_aware_scope,
591        group_by: None,
592        top: None,
593        summary: options.summary,
594        summary_heading: options.summary_heading,
595        show_explain_tip: options.show_explain_tip,
596        baseline_matched: None,
597        config_fixable: false,
598        skip_score_and_trend: options.skip_score_and_trend,
599        css_requested: options.css_requested,
600        json_style: options.json_style,
601    }
602}
603
604fn health_exit_gate_failed(result: &HealthResult, options: HealthPrintOptions) -> bool {
605    score_gate_failed(result, options)
606        || findings_gate_failed(result, options)
607        || has_failing_runtime_coverage(result)
608}
609
610fn score_gate_failed(result: &HealthResult, options: HealthPrintOptions) -> bool {
611    let Some(threshold) = options.gates.min_score else {
612        return false;
613    };
614    let Some(ref hs) = result.report.health_score else {
615        return false;
616    };
617    if hs.score >= threshold {
618        return false;
619    }
620
621    if !options.quiet {
622        eprintln!(
623            "Health score {:.1} ({}) is below minimum threshold {:.0}",
624            hs.score, hs.grade, threshold
625        );
626    }
627    true
628}
629
630fn findings_gate_failed(result: &HealthResult, options: HealthPrintOptions) -> bool {
631    if let Some(min_sev) = options.gates.min_severity {
632        result.report.findings.iter().any(|f| f.severity >= min_sev)
633    } else if options.gates.min_score.is_none() {
634        !result.report.findings.is_empty()
635    } else {
636        false
637    }
638}
639
640fn has_failing_runtime_coverage(result: &HealthResult) -> bool {
641    result
642        .report
643        .runtime_coverage
644        .as_ref()
645        .is_some_and(|report| report.findings.iter().any(is_failing_runtime_coverage))
646}
647
648fn is_failing_runtime_coverage(finding: &fallow_output::RuntimeCoverageFinding) -> bool {
649    matches!(
650        finding.verdict,
651        fallow_output::RuntimeCoverageVerdict::SafeToDelete
652            | fallow_output::RuntimeCoverageVerdict::ReviewRequired
653            | fallow_output::RuntimeCoverageVerdict::LowTraffic
654    )
655}
656
657fn maybe_print_score_gate_note(result: &HealthResult, options: HealthPrintOptions) {
658    if options.gates.min_score.is_none()
659        || options.gates.min_severity.is_some()
660        || options.quiet
661        || result.report.findings.is_empty()
662        || !matches!(result.config.output, OutputFormat::Human)
663    {
664        return;
665    }
666
667    {
668        eprintln!(
669            "{}",
670            "Findings above are informational: --min-score gates on the score, not on findings."
671                .dimmed()
672        );
673    }
674}
675
676#[cfg(test)]
677mod tests {
678    use super::*;
679    use fallow_config::{FallowConfig, OutputFormat};
680    use fallow_output::{ComplexityViolation, ExceededThreshold, FindingSeverity};
681    use std::path::PathBuf;
682    use std::time::Duration;
683
684    fn make_finding(name: &str, exceeded: ExceededThreshold) -> ComplexityViolation {
685        ComplexityViolation {
686            path: PathBuf::from("/project/src/a.ts"),
687            name: name.to_string(),
688            line: 1,
689            col: 0,
690            cyclomatic: match exceeded {
691                ExceededThreshold::Cyclomatic
692                | ExceededThreshold::Both
693                | ExceededThreshold::CyclomaticCrap
694                | ExceededThreshold::All => 25,
695                _ => 8,
696            },
697            cognitive: match exceeded {
698                ExceededThreshold::Cognitive
699                | ExceededThreshold::Both
700                | ExceededThreshold::CognitiveCrap
701                | ExceededThreshold::All => 20,
702                _ => 5,
703            },
704            line_count: 10,
705            param_count: 0,
706            react_hook_count: 0,
707            react_jsx_max_depth: 0,
708            react_prop_count: 0,
709            react_hook_profile: None,
710            exceeded,
711            severity: FindingSeverity::Moderate,
712            crap: exceeded.includes_crap().then_some(30.0),
713            coverage_pct: None,
714            coverage_tier: None,
715            coverage_source: None,
716            inherited_from: None,
717            component_rollup: None,
718            contributions: Vec::new(),
719            effective_thresholds: None,
720            threshold_source: None,
721        }
722    }
723
724    fn test_resolved_config() -> fallow_config::ResolvedConfig {
725        FallowConfig::default().resolve(
726            PathBuf::from("/project"),
727            OutputFormat::Json,
728            1,
729            true,
730            true,
731            None,
732        )
733    }
734
735    fn fx_summary(
736        tracked: usize,
737        hit: usize,
738        unhit: usize,
739        untracked: usize,
740    ) -> fallow_output::RuntimeCoverageSummary {
741        #[expect(
742            clippy::cast_precision_loss,
743            reason = "test fixture totals are tiny, f64 precision is fine"
744        )]
745        let coverage_percent = if tracked == 0 {
746            0.0
747        } else {
748            (hit as f64 / tracked as f64) * 100.0
749        };
750        fallow_output::RuntimeCoverageSummary {
751            data_source: fallow_output::RuntimeCoverageDataSource::Local,
752            last_received_at: None,
753            functions_tracked: tracked,
754            functions_hit: hit,
755            functions_unhit: unhit,
756            functions_untracked: untracked,
757            coverage_percent,
758            trace_count: 512,
759            period_days: 7,
760            deployments_seen: 2,
761            capture_quality: None,
762        }
763    }
764
765    fn fx_evidence(
766        static_status: &str,
767        test_coverage: &str,
768        v8_tracking: &str,
769    ) -> fallow_output::RuntimeCoverageEvidence {
770        fallow_output::RuntimeCoverageEvidence {
771            static_status: static_status.to_owned(),
772            test_coverage: test_coverage.to_owned(),
773            v8_tracking: v8_tracking.to_owned(),
774            untracked_reason: None,
775            observation_days: 7,
776            deployments_observed: 2,
777        }
778    }
779
780    fn fx_health_score(score: f64, grade: &'static str) -> fallow_output::HealthScore {
781        fallow_output::HealthScore {
782            formula_version: 2,
783            score,
784            grade,
785            penalties: fallow_output::HealthScorePenalties {
786                dead_files: None,
787                dead_exports: None,
788                complexity: 0.0,
789                p90_complexity: 0.0,
790                maintainability: None,
791                hotspots: None,
792                unused_deps: None,
793                circular_deps: None,
794                unit_size: None,
795                coupling: None,
796                duplication: None,
797                prop_drilling: None,
798            },
799        }
800    }
801
802    fn fx_gate_result(
803        findings: Vec<fallow_output::HealthFinding>,
804        score: Option<fallow_output::HealthScore>,
805    ) -> HealthResult {
806        HealthResult {
807            report: fallow_output::HealthReport {
808                findings,
809                health_score: score,
810                ..fallow_output::HealthReport::default()
811            },
812            grouping: None,
813            group_resolver: None,
814            config: test_resolved_config(),
815            workspace_diagnostics: Vec::new(),
816            elapsed: Duration::default(),
817            timings: None,
818            type_aware_meta: None,
819            coverage_gaps_has_findings: false,
820            should_fail_on_coverage_gaps: false,
821        }
822    }
823
824    fn moderate_finding() -> fallow_output::HealthFinding {
825        make_finding("moderate", ExceededThreshold::Cyclomatic).into()
826    }
827
828    fn critical_finding() -> fallow_output::HealthFinding {
829        let mut v = make_finding("critical", ExceededThreshold::All);
830        v.severity = FindingSeverity::Critical;
831        v.into()
832    }
833
834    /// Helper: run the gate with the given flags, quiet, no report-only.
835    fn gate_exit(
836        result: &HealthResult,
837        min_score: Option<f64>,
838        min_severity: Option<FindingSeverity>,
839        report_only: bool,
840    ) -> ExitCode {
841        print_health_result(
842            result,
843            HealthPrintOptions {
844                quiet: true,
845                explain: false,
846                gates: HealthGateOptions {
847                    min_score,
848                    min_severity,
849                    report_only,
850                },
851                summary: false,
852                summary_heading: true,
853                show_explain_tip: true,
854                type_aware_scope: None,
855                skip_score_and_trend: false,
856                css_requested: false,
857                json_style: crate::json_style::JsonStyle::Compact,
858            },
859        )
860    }
861
862    #[test]
863    fn plain_health_with_findings_fails() {
864        let result = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(87.5, "A")));
865        assert_eq!(gate_exit(&result, None, None, false), ExitCode::from(1));
866    }
867
868    #[test]
869    fn plain_health_with_no_findings_succeeds() {
870        let result = fx_gate_result(vec![], Some(fx_health_score(100.0, "A")));
871        assert_eq!(gate_exit(&result, None, None, false), ExitCode::SUCCESS);
872    }
873
874    #[test]
875    fn min_score_zero_never_fails_even_with_findings() {
876        let result = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(50.0, "D")));
877        assert_eq!(
878            gate_exit(&result, Some(0.0), None, false),
879            ExitCode::SUCCESS
880        );
881    }
882
883    #[test]
884    fn min_score_passing_demotes_findings_to_informational() {
885        let result = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(87.5, "A")));
886        assert_eq!(
887            gate_exit(&result, Some(80.0), None, false),
888            ExitCode::SUCCESS
889        );
890    }
891
892    #[test]
893    fn min_score_below_threshold_fails() {
894        let result = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(50.0, "D")));
895        assert_eq!(
896            gate_exit(&result, Some(80.0), None, false),
897            ExitCode::from(1)
898        );
899    }
900
901    #[test]
902    fn min_severity_gates_on_severity_independent_of_min_score() {
903        let only_moderate =
904            fx_gate_result(vec![moderate_finding()], Some(fx_health_score(87.5, "A")));
905        assert_eq!(
906            gate_exit(&only_moderate, None, Some(FindingSeverity::Critical), false),
907            ExitCode::SUCCESS,
908        );
909        let with_critical = fx_gate_result(
910            vec![moderate_finding(), critical_finding()],
911            Some(fx_health_score(87.5, "A")),
912        );
913        assert_eq!(
914            gate_exit(&with_critical, None, Some(FindingSeverity::Critical), false),
915            ExitCode::from(1),
916        );
917    }
918
919    #[test]
920    fn min_score_and_min_severity_compose_as_or() {
921        let pass = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(87.5, "A")));
922        assert_eq!(
923            gate_exit(&pass, Some(80.0), Some(FindingSeverity::Critical), false),
924            ExitCode::SUCCESS,
925        );
926        let low_score = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(50.0, "D")));
927        assert_eq!(
928            gate_exit(
929                &low_score,
930                Some(80.0),
931                Some(FindingSeverity::Critical),
932                false
933            ),
934            ExitCode::from(1),
935        );
936        let critical = fx_gate_result(vec![critical_finding()], Some(fx_health_score(87.5, "A")));
937        assert_eq!(
938            gate_exit(
939                &critical,
940                Some(80.0),
941                Some(FindingSeverity::Critical),
942                false
943            ),
944            ExitCode::from(1),
945        );
946    }
947
948    #[test]
949    fn report_only_never_fails_on_findings_or_low_score() {
950        let result = fx_gate_result(
951            vec![moderate_finding(), critical_finding()],
952            Some(fx_health_score(10.0, "F")),
953        );
954        assert_eq!(gate_exit(&result, None, None, true), ExitCode::SUCCESS);
955    }
956
957    #[test]
958    fn runtime_coverage_gate_independent_of_min_score() {
959        let result = fx_low_traffic_runtime_result();
960        assert_eq!(
961            gate_exit(&result, Some(0.0), None, false),
962            ExitCode::from(1)
963        );
964        assert_eq!(gate_exit(&result, None, None, true), ExitCode::SUCCESS);
965    }
966
967    fn fx_low_traffic_runtime_result() -> HealthResult {
968        HealthResult {
969            report: fallow_output::HealthReport {
970                runtime_coverage: Some(fallow_output::RuntimeCoverageReport {
971                    schema_version: fallow_output::RuntimeCoverageSchemaVersion::V1,
972                    verdict: fallow_output::RuntimeCoverageReportVerdict::ColdCodeDetected,
973                    signals: Vec::new(),
974                    summary: fx_summary(1, 0, 1, 0),
975                    findings: vec![fallow_output::RuntimeCoverageFinding {
976                        id: "fallow:prod:lowtraffic".to_owned(),
977                        stable_id: None,
978                        path: PathBuf::from("/project/src/cold.ts"),
979                        function: "coldPath".to_owned(),
980                        line: 14,
981                        verdict: fallow_output::RuntimeCoverageVerdict::LowTraffic,
982                        invocations: Some(1),
983                        confidence: fallow_output::RuntimeCoverageConfidence::Low,
984                        evidence: fx_evidence("used", "not_covered", "tracked"),
985                        actions: vec![],
986                        source_hash: None,
987                        discriminators: None,
988                    }],
989                    hot_paths: vec![],
990                    blast_radius: vec![],
991                    importance: vec![],
992                    watermark: None,
993                    warnings: vec![],
994                    actionable: true,
995                    actionability_reason: None,
996                    actionability_verdict: None,
997                    provenance: fallow_output::RuntimeCoverageProvenance::default(),
998                }),
999                ..fallow_output::HealthReport::default()
1000            },
1001            grouping: None,
1002            group_resolver: None,
1003            config: test_resolved_config(),
1004            workspace_diagnostics: Vec::new(),
1005            elapsed: Duration::default(),
1006            timings: None,
1007            type_aware_meta: None,
1008            coverage_gaps_has_findings: false,
1009            should_fail_on_coverage_gaps: false,
1010        }
1011    }
1012
1013    #[test]
1014    fn print_health_result_fails_on_low_traffic_runtime_coverage() {
1015        let result = fx_low_traffic_runtime_result();
1016
1017        assert_eq!(
1018            print_health_result(
1019                &result,
1020                HealthPrintOptions {
1021                    quiet: true,
1022                    explain: false,
1023                    gates: HealthGateOptions::default(),
1024                    summary: false,
1025                    summary_heading: true,
1026                    show_explain_tip: true,
1027                    type_aware_scope: None,
1028                    skip_score_and_trend: false,
1029                    css_requested: false,
1030                    json_style: crate::json_style::JsonStyle::Compact,
1031                },
1032            ),
1033            ExitCode::from(1),
1034        );
1035    }
1036}