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