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