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