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