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 summary: opts.summary,
455 summary_heading: true,
456 show_explain_tip: true,
457 type_aware_scope: None,
458 skip_score_and_trend: false,
459 css_requested: opts.css,
460 json_style,
461 },
462 );
463 if code == ExitCode::SUCCESS && completeness_failed {
464 ExitCode::from(1)
465 } else {
466 code
467 }
468}
469
470pub struct ResolvedTypeAwareHealthOptions {
471 pub enabled: bool,
472 pub projects: Vec<std::path::PathBuf>,
473 pub require: fallow_config::TypeAwareRequire,
474}
475
476pub fn resolve_type_aware_health_options(
477 options: &TypeAwareHealthOptions<'_>,
478 config: &fallow_config::ResolvedConfig,
479) -> Result<ResolvedTypeAwareHealthOptions, String> {
480 let env_enabled = std::env::var("FALLOW_TYPE_AWARE")
481 .ok()
482 .map(|value| match value.trim().to_ascii_lowercase().as_str() {
483 "1" | "true" | "yes" | "on" => Ok(true),
484 "0" | "false" | "no" | "off" => Ok(false),
485 _ => Err(
486 "FALLOW_TYPE_AWARE must be one of true, false, 1, 0, yes, no, on, or off"
487 .to_string(),
488 ),
489 })
490 .transpose()?;
491 let enabled = options
492 .enabled
493 .or(env_enabled)
494 .unwrap_or(config.type_aware.enabled);
495 let projects = if !options.projects.is_empty() {
496 options.projects.to_vec()
497 } else if let Some(value) = std::env::var_os("FALLOW_TYPE_AWARE_PROJECTS") {
498 std::env::split_paths(&value).collect()
499 } else {
500 config
501 .type_aware
502 .projects
503 .iter()
504 .map(std::path::PathBuf::from)
505 .collect()
506 };
507 let require = if let Some(require) = options.require {
508 require
509 } else if let Ok(value) = std::env::var("FALLOW_TYPE_AWARE_REQUIRE") {
510 match value.trim().to_ascii_lowercase().as_str() {
511 "best-effort" => fallow_config::TypeAwareRequire::BestEffort,
512 "complete" => fallow_config::TypeAwareRequire::Complete,
513 _ => {
514 return Err("FALLOW_TYPE_AWARE_REQUIRE must be best-effort or complete".to_string());
515 }
516 }
517 } else {
518 config.type_aware.require
519 };
520 Ok(ResolvedTypeAwareHealthOptions {
521 enabled,
522 projects,
523 require,
524 })
525}
526
527pub type HealthResult =
529 fallow_engine::health::HealthAnalysisResult<crate::report::OwnershipResolver>;
530
531#[derive(Clone, Copy)]
551pub struct HealthPrintOptions {
552 pub quiet: bool,
553 pub explain: bool,
554 pub gates: HealthGateOptions,
555 pub summary: bool,
556 pub summary_heading: bool,
557 pub show_explain_tip: bool,
558 pub type_aware_scope: Option<&'static str>,
559 pub skip_score_and_trend: bool,
560 pub css_requested: bool,
564 pub json_style: crate::json_style::JsonStyle,
565}
566
567pub fn print_health_result(result: &HealthResult, options: HealthPrintOptions) -> ExitCode {
568 let ctx = health_report_context(result, options);
569 let report_code = report::print_health_report(
570 &result.report,
571 result.grouping.as_ref(),
572 result.group_resolver.as_ref(),
573 &ctx,
574 result.config.output,
575 );
576 if report_code != ExitCode::SUCCESS {
577 return report_code;
578 }
579
580 if options.gates.report_only {
581 return ExitCode::SUCCESS;
582 }
583
584 if health_exit_gate_failed(result, options) {
585 return ExitCode::from(1);
586 }
587 if result.should_fail_on_coverage_gaps && result.coverage_gaps_has_findings {
588 return ExitCode::from(1);
589 }
590 maybe_print_score_gate_note(result, options);
591
592 ExitCode::SUCCESS
593}
594
595fn health_report_context(
596 result: &HealthResult,
597 options: HealthPrintOptions,
598) -> report::ReportContext<'_> {
599 report::ReportContext {
600 root: &result.config.root,
601 rules: &result.config.rules,
602 workspace_diagnostics: &result.workspace_diagnostics,
603 elapsed: result.elapsed,
604 quiet: options.quiet,
605 explain: options.explain,
606 type_aware: result.type_aware_meta.as_ref(),
607 type_aware_scope: options.type_aware_scope,
608 group_by: None,
609 top: None,
610 summary: options.summary,
611 summary_heading: options.summary_heading,
612 show_explain_tip: options.show_explain_tip,
613 baseline_matched: None,
614 config_fixable: false,
615 skip_score_and_trend: options.skip_score_and_trend,
616 css_requested: options.css_requested,
617 json_style: options.json_style,
618 include_fragments: true,
619 }
620}
621
622fn health_exit_gate_failed(result: &HealthResult, options: HealthPrintOptions) -> bool {
623 score_gate_failed(result, options)
624 || findings_gate_failed(result, options)
625 || has_failing_runtime_coverage(result)
626}
627
628fn score_gate_failed(result: &HealthResult, options: HealthPrintOptions) -> bool {
629 let Some(threshold) = options.gates.min_score else {
630 return false;
631 };
632 let Some(ref hs) = result.report.health_score else {
633 return false;
634 };
635 if hs.score >= threshold {
636 return false;
637 }
638
639 if !options.quiet {
640 eprintln!(
641 "Health score {:.1} ({}) is below minimum threshold {:.0}",
642 hs.score, hs.grade, threshold
643 );
644 }
645 true
646}
647
648fn findings_gate_failed(result: &HealthResult, options: HealthPrintOptions) -> bool {
649 if let Some(min_sev) = options.gates.min_severity {
650 result.report.findings.iter().any(|f| f.severity >= min_sev)
651 } else if options.gates.min_score.is_none() {
652 !result.report.findings.is_empty()
653 } else {
654 false
655 }
656}
657
658fn has_failing_runtime_coverage(result: &HealthResult) -> bool {
659 result
660 .report
661 .runtime_coverage
662 .as_ref()
663 .is_some_and(|report| report.findings.iter().any(is_failing_runtime_coverage))
664}
665
666fn is_failing_runtime_coverage(finding: &fallow_output::RuntimeCoverageFinding) -> bool {
667 matches!(
668 finding.verdict,
669 fallow_output::RuntimeCoverageVerdict::SafeToDelete
670 | fallow_output::RuntimeCoverageVerdict::ReviewRequired
671 | fallow_output::RuntimeCoverageVerdict::LowTraffic
672 )
673}
674
675fn maybe_print_score_gate_note(result: &HealthResult, options: HealthPrintOptions) {
676 if options.gates.min_score.is_none()
677 || options.gates.min_severity.is_some()
678 || options.quiet
679 || result.report.findings.is_empty()
680 || !matches!(result.config.output, OutputFormat::Human)
681 {
682 return;
683 }
684
685 {
686 eprintln!(
687 "{}",
688 "Findings above are informational: --min-score gates on the score, not on findings."
689 .dimmed()
690 );
691 }
692}
693
694#[cfg(test)]
695mod tests {
696 use super::*;
697 use fallow_config::{FallowConfig, OutputFormat};
698 use fallow_output::{ComplexityViolation, ExceededThreshold, FindingSeverity};
699 use std::path::PathBuf;
700 use std::time::Duration;
701
702 fn make_finding(name: &str, exceeded: ExceededThreshold) -> ComplexityViolation {
703 ComplexityViolation {
704 path: PathBuf::from("/project/src/a.ts"),
705 name: name.to_string(),
706 line: 1,
707 col: 0,
708 cyclomatic: match exceeded {
709 ExceededThreshold::Cyclomatic
710 | ExceededThreshold::Both
711 | ExceededThreshold::CyclomaticCrap
712 | ExceededThreshold::All => 25,
713 _ => 8,
714 },
715 cognitive: match exceeded {
716 ExceededThreshold::Cognitive
717 | ExceededThreshold::Both
718 | ExceededThreshold::CognitiveCrap
719 | ExceededThreshold::All => 20,
720 _ => 5,
721 },
722 line_count: 10,
723 param_count: 0,
724 react_hook_count: 0,
725 react_jsx_max_depth: 0,
726 react_prop_count: 0,
727 react_hook_profile: None,
728 exceeded,
729 severity: FindingSeverity::Moderate,
730 crap: exceeded.includes_crap().then_some(30.0),
731 coverage_pct: None,
732 coverage_tier: None,
733 coverage_source: None,
734 inherited_from: None,
735 component_rollup: None,
736 contributions: Vec::new(),
737 effective_thresholds: None,
738 threshold_source: None,
739 }
740 }
741
742 fn test_resolved_config() -> fallow_config::ResolvedConfig {
743 FallowConfig::default().resolve(
744 PathBuf::from("/project"),
745 OutputFormat::Json,
746 1,
747 true,
748 true,
749 None,
750 )
751 }
752
753 fn fx_summary(
754 tracked: usize,
755 hit: usize,
756 unhit: usize,
757 untracked: usize,
758 ) -> fallow_output::RuntimeCoverageSummary {
759 #[expect(
760 clippy::cast_precision_loss,
761 reason = "test fixture totals are tiny, f64 precision is fine"
762 )]
763 let coverage_percent = if tracked == 0 {
764 0.0
765 } else {
766 (hit as f64 / tracked as f64) * 100.0
767 };
768 fallow_output::RuntimeCoverageSummary {
769 data_source: fallow_output::RuntimeCoverageDataSource::Local,
770 last_received_at: None,
771 functions_tracked: tracked,
772 functions_hit: hit,
773 functions_unhit: unhit,
774 functions_untracked: untracked,
775 coverage_percent,
776 trace_count: 512,
777 period_days: 7,
778 deployments_seen: 2,
779 capture_quality: None,
780 }
781 }
782
783 fn fx_evidence(
784 static_status: &str,
785 test_coverage: &str,
786 v8_tracking: &str,
787 ) -> fallow_output::RuntimeCoverageEvidence {
788 fallow_output::RuntimeCoverageEvidence {
789 static_status: static_status.to_owned(),
790 test_coverage: test_coverage.to_owned(),
791 test_only_reference: None,
792 v8_tracking: v8_tracking.to_owned(),
793 untracked_reason: None,
794 observation_days: 7,
795 deployments_observed: 2,
796 }
797 }
798
799 fn fx_health_score(score: f64, grade: &'static str) -> fallow_output::HealthScore {
800 fallow_output::HealthScore {
801 formula_version: 2,
802 score,
803 grade,
804 penalties: fallow_output::HealthScorePenalties {
805 dead_files: None,
806 dead_exports: None,
807 complexity: 0.0,
808 p90_complexity: 0.0,
809 maintainability: None,
810 hotspots: None,
811 unused_deps: None,
812 circular_deps: None,
813 unit_size: None,
814 coupling: None,
815 duplication: None,
816 prop_drilling: None,
817 },
818 }
819 }
820
821 fn fx_gate_result(
822 findings: Vec<fallow_output::HealthFinding>,
823 score: Option<fallow_output::HealthScore>,
824 ) -> HealthResult {
825 HealthResult {
826 branching_by_file: fallow_engine::health::BranchingByFile::default(),
827 report: fallow_output::HealthReport {
828 findings,
829 health_score: score,
830 ..fallow_output::HealthReport::default()
831 },
832 grouping: None,
833 group_resolver: None,
834 config: test_resolved_config(),
835 workspace_diagnostics: Vec::new(),
836 elapsed: Duration::default(),
837 timings: None,
838 type_aware_meta: None,
839 coverage_gaps_has_findings: false,
840 should_fail_on_coverage_gaps: false,
841 }
842 }
843
844 fn moderate_finding() -> fallow_output::HealthFinding {
845 make_finding("moderate", ExceededThreshold::Cyclomatic).into()
846 }
847
848 fn critical_finding() -> fallow_output::HealthFinding {
849 let mut v = make_finding("critical", ExceededThreshold::All);
850 v.severity = FindingSeverity::Critical;
851 v.into()
852 }
853
854 fn gate_exit(
856 result: &HealthResult,
857 min_score: Option<f64>,
858 min_severity: Option<FindingSeverity>,
859 report_only: bool,
860 ) -> ExitCode {
861 print_health_result(
862 result,
863 HealthPrintOptions {
864 quiet: true,
865 explain: false,
866 gates: HealthGateOptions {
867 min_score,
868 min_severity,
869 report_only,
870 },
871 summary: false,
872 summary_heading: true,
873 show_explain_tip: true,
874 type_aware_scope: None,
875 skip_score_and_trend: false,
876 css_requested: false,
877 json_style: crate::json_style::JsonStyle::Compact,
878 },
879 )
880 }
881
882 #[test]
883 fn plain_health_with_findings_fails() {
884 let result = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(87.5, "A")));
885 assert_eq!(gate_exit(&result, None, None, false), ExitCode::from(1));
886 }
887
888 #[test]
889 fn plain_health_with_no_findings_succeeds() {
890 let result = fx_gate_result(vec![], Some(fx_health_score(100.0, "A")));
891 assert_eq!(gate_exit(&result, None, None, false), ExitCode::SUCCESS);
892 }
893
894 #[test]
895 fn min_score_zero_never_fails_even_with_findings() {
896 let result = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(50.0, "D")));
897 assert_eq!(
898 gate_exit(&result, Some(0.0), None, false),
899 ExitCode::SUCCESS
900 );
901 }
902
903 #[test]
904 fn min_score_passing_demotes_findings_to_informational() {
905 let result = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(87.5, "A")));
906 assert_eq!(
907 gate_exit(&result, Some(80.0), None, false),
908 ExitCode::SUCCESS
909 );
910 }
911
912 #[test]
913 fn min_score_below_threshold_fails() {
914 let result = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(50.0, "D")));
915 assert_eq!(
916 gate_exit(&result, Some(80.0), None, false),
917 ExitCode::from(1)
918 );
919 }
920
921 #[test]
922 fn min_severity_gates_on_severity_independent_of_min_score() {
923 let only_moderate =
924 fx_gate_result(vec![moderate_finding()], Some(fx_health_score(87.5, "A")));
925 assert_eq!(
926 gate_exit(&only_moderate, None, Some(FindingSeverity::Critical), false),
927 ExitCode::SUCCESS,
928 );
929 let with_critical = fx_gate_result(
930 vec![moderate_finding(), critical_finding()],
931 Some(fx_health_score(87.5, "A")),
932 );
933 assert_eq!(
934 gate_exit(&with_critical, None, Some(FindingSeverity::Critical), false),
935 ExitCode::from(1),
936 );
937 }
938
939 #[test]
940 fn min_score_and_min_severity_compose_as_or() {
941 let pass = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(87.5, "A")));
942 assert_eq!(
943 gate_exit(&pass, Some(80.0), Some(FindingSeverity::Critical), false),
944 ExitCode::SUCCESS,
945 );
946 let low_score = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(50.0, "D")));
947 assert_eq!(
948 gate_exit(
949 &low_score,
950 Some(80.0),
951 Some(FindingSeverity::Critical),
952 false
953 ),
954 ExitCode::from(1),
955 );
956 let critical = fx_gate_result(vec![critical_finding()], Some(fx_health_score(87.5, "A")));
957 assert_eq!(
958 gate_exit(
959 &critical,
960 Some(80.0),
961 Some(FindingSeverity::Critical),
962 false
963 ),
964 ExitCode::from(1),
965 );
966 }
967
968 #[test]
969 fn report_only_never_fails_on_findings_or_low_score() {
970 let result = fx_gate_result(
971 vec![moderate_finding(), critical_finding()],
972 Some(fx_health_score(10.0, "F")),
973 );
974 assert_eq!(gate_exit(&result, None, None, true), ExitCode::SUCCESS);
975 }
976
977 #[test]
978 fn runtime_coverage_gate_independent_of_min_score() {
979 let result = fx_low_traffic_runtime_result();
980 assert_eq!(
981 gate_exit(&result, Some(0.0), None, false),
982 ExitCode::from(1)
983 );
984 assert_eq!(gate_exit(&result, None, None, true), ExitCode::SUCCESS);
985 }
986
987 fn fx_low_traffic_runtime_result() -> HealthResult {
988 HealthResult {
989 branching_by_file: fallow_engine::health::BranchingByFile::default(),
990 report: fallow_output::HealthReport {
991 runtime_coverage: Some(fallow_output::RuntimeCoverageReport {
992 schema_version: fallow_output::RuntimeCoverageSchemaVersion::V1,
993 verdict: fallow_output::RuntimeCoverageReportVerdict::ColdCodeDetected,
994 signals: Vec::new(),
995 summary: fx_summary(1, 0, 1, 0),
996 findings: vec![fallow_output::RuntimeCoverageFinding {
997 id: "fallow:prod:lowtraffic".to_owned(),
998 stable_id: None,
999 path: PathBuf::from("/project/src/cold.ts"),
1000 function: "coldPath".to_owned(),
1001 line: 14,
1002 verdict: fallow_output::RuntimeCoverageVerdict::LowTraffic,
1003 invocations: Some(1),
1004 confidence: fallow_output::RuntimeCoverageConfidence::Low,
1005 evidence: fx_evidence("used", "not_covered", "tracked"),
1006 actions: vec![],
1007 source_hash: None,
1008 discriminators: None,
1009 }],
1010 hot_paths: vec![],
1011 blast_radius: vec![],
1012 importance: vec![],
1013 watermark: None,
1014 warnings: vec![],
1015 actionable: true,
1016 actionability_reason: None,
1017 actionability_verdict: None,
1018 provenance: fallow_output::RuntimeCoverageProvenance::default(),
1019 }),
1020 ..fallow_output::HealthReport::default()
1021 },
1022 grouping: None,
1023 group_resolver: None,
1024 config: test_resolved_config(),
1025 workspace_diagnostics: Vec::new(),
1026 elapsed: Duration::default(),
1027 timings: None,
1028 type_aware_meta: None,
1029 coverage_gaps_has_findings: false,
1030 should_fail_on_coverage_gaps: false,
1031 }
1032 }
1033
1034 #[test]
1035 fn print_health_result_fails_on_low_traffic_runtime_coverage() {
1036 let result = fx_low_traffic_runtime_result();
1037
1038 assert_eq!(
1039 print_health_result(
1040 &result,
1041 HealthPrintOptions {
1042 quiet: true,
1043 explain: false,
1044 gates: HealthGateOptions::default(),
1045 summary: false,
1046 summary_heading: true,
1047 show_explain_tip: true,
1048 type_aware_scope: None,
1049 skip_score_and_trend: false,
1050 css_requested: false,
1051 json_style: crate::json_style::JsonStyle::Compact,
1052 },
1053 ),
1054 ExitCode::from(1),
1055 );
1056 }
1057}