Skip to main content

fallow_cli/health/
mod.rs

1//! `fallow health` complexity / health command.
2//!
3//! The command-neutral analysis pipeline (scoring, hotspots, targets, grouping,
4//! coverage gaps, vital signs, report assembly) lives in
5//! `fallow_engine::health` API. This module owns the CLI orchestration that the
6//! engine intentionally does not: command option validation, workspace /
7//! changed-file / shared-diff scope resolution, CODEOWNERS-backed
8//! grouping-resolver construction, the runtime coverage sidecar seam,
9//! telemetry recording, exit-code gating, and human / machine rendering.
10
11pub mod coverage;
12pub mod optimization_target;
13
14/// Health scoring helpers, re-exported from the engine for CLI consumers that
15/// still address them through `crate::health::scoring`.
16pub use fallow_engine::health::scoring;
17
18use std::process::ExitCode;
19use std::time::Instant;
20
21use colored::Colorize;
22use fallow_config::OutputFormat;
23use fallow_engine::health::{
24    HealthError, HealthExecutionOptions, HealthGateOptions, HealthGroupResolver,
25    HealthPipelineInputs, HealthScopeInputs, HealthSeams, HealthSharedParseData, HealthSort,
26    RuntimeCoverageSeamInput, execute_health_inner, validate_health_churn_file,
27};
28
29use crate::check::resolve_workspace_scope;
30use crate::error::emit_error;
31use crate::report;
32use crate::report::OwnershipResolver;
33
34/// Sort criteria for complexity output.
35#[derive(Clone, clap::ValueEnum)]
36pub enum SortBy {
37    Severity,
38    Cyclomatic,
39    Cognitive,
40    Lines,
41}
42
43impl From<SortBy> for HealthSort {
44    fn from(sort: SortBy) -> Self {
45        match sort {
46            SortBy::Severity => Self::Severity,
47            SortBy::Cyclomatic => Self::Cyclomatic,
48            SortBy::Cognitive => Self::Cognitive,
49            SortBy::Lines => Self::Lines,
50        }
51    }
52}
53
54pub type HealthOptions<'a> = HealthExecutionOptions<'a>;
55
56/// CLI-only semantic overlay options for `health --type-coupling`.
57pub struct TypeAwareHealthOptions<'a> {
58    /// CLI override: `Some(true)` for `--type-aware`, `Some(false)` for
59    /// `--no-type-aware`, `None` when neither flag was passed.
60    pub enabled: Option<bool>,
61    pub requested: bool,
62    pub unfiltered: bool,
63    pub projects: &'a [std::path::PathBuf],
64    pub require: Option<fallow_config::TypeAwareRequire>,
65}
66
67impl HealthGroupResolver for OwnershipResolver {
68    fn mode_label(&self) -> &'static str {
69        OwnershipResolver::mode_label(self)
70    }
71
72    fn resolve_with_rule(&self, rel_path: &std::path::Path) -> (String, Option<String>) {
73        OwnershipResolver::resolve_with_rule(self, rel_path)
74    }
75
76    fn section_owners_of(&self, rel_path: &std::path::Path) -> Option<&[String]> {
77        OwnershipResolver::section_owners_of(self, rel_path)
78    }
79}
80
81/// Resolve the diff index for a health run: an explicit `--diff-file` index
82/// wins, otherwise the process-shared diff cache when the caller opted in.
83fn health_diff_index<'a>(opts: &HealthOptions<'a>) -> Option<&'a fallow_output::DiffIndex> {
84    match opts.diff_index {
85        Some(index) => Some(index),
86        None if opts.use_shared_diff_index => crate::report::ci::diff_filter::shared_diff_index(),
87        None => None,
88    }
89}
90
91/// Build the CODEOWNERS / package-backed grouping resolver for `--group-by`.
92fn build_health_group_resolver(
93    opts: &HealthOptions<'_>,
94    config: &fallow_config::ResolvedConfig,
95) -> Result<Option<OwnershipResolver>, ExitCode> {
96    crate::runtime_support::build_ownership_resolver_for_mode(
97        opts.group_by,
98        opts.root,
99        config.codeowners.as_deref(),
100        opts.output,
101    )
102}
103
104/// Record health telemetry from the finished report. Mirrors the per-analysis
105/// telemetry the other commands record; lives in the CLI because the telemetry
106/// sinks are process-global CLI state.
107fn record_health_telemetry(report: &fallow_output::HealthReport, coverage_gaps_has_findings: bool) {
108    if coverage_gaps_has_findings && report.findings.is_empty() {
109        crate::telemetry::note_findings_present(true);
110    } else {
111        crate::telemetry::note_result_count(report.findings.len());
112    }
113    crate::telemetry::note_analysis_scale(
114        Some(report.summary.files_analyzed),
115        Some(report.summary.functions_analyzed),
116    );
117}
118
119/// Build the engine seam callbacks: the runtime coverage sidecar adapter and
120/// the graph-structure telemetry hook.
121fn health_seams<'a>() -> HealthSeams<'a> {
122    HealthSeams {
123        runtime_coverage_analyzer: &runtime_coverage_seam,
124        note_graph_structure: &|module_count, edge_count| {
125            crate::telemetry::note_graph_structure_counts(module_count, edge_count);
126        },
127    }
128}
129
130/// Adapt the engine's runtime coverage seam input to the CLI coverage module,
131/// which owns the closed-source sidecar (license verification, subprocess
132/// spawning, signal handling).
133#[expect(
134    clippy::needless_pass_by_value,
135    reason = "by-value input matches the engine RuntimeCoverageAnalyzer seam signature"
136)]
137fn runtime_coverage_seam(
138    options: &fallow_engine::health::RuntimeCoverageOptions,
139    input: RuntimeCoverageSeamInput<'_>,
140) -> Result<fallow_output::RuntimeCoverageReport, u8> {
141    coverage::analyze(
142        options,
143        &coverage::RuntimeCoverageAnalysisInput {
144            root: input.root,
145            modules: input.modules,
146            analysis_output: input.analysis_output,
147            istanbul_coverage: input.istanbul_coverage,
148            file_paths: input.file_paths,
149            ignore_set: input.ignore_set,
150            changed_files: input.changed_files,
151            ws_roots: input.ws_roots,
152            top: input.top,
153            codeowners_path: input.codeowners_path,
154            quiet: input.quiet,
155            output: input.output,
156        },
157    )
158}
159
160/// Resolve the command-neutral scope inputs the engine needs: changed files,
161/// the diff index, workspace roots, and the grouping resolver.
162///
163/// `files` is the analyzed set, which sizes the scope an applied
164/// `--changed-since` leaves.
165fn build_health_scope_inputs<'a>(
166    opts: &HealthOptions<'a>,
167    config: &fallow_config::ResolvedConfig,
168    files: &[fallow_types::discover::DiscoveredFile],
169) -> Result<HealthScopeInputs<'a, OwnershipResolver>, ExitCode> {
170    let changed_files = opts
171        .changed_since
172        .and_then(|git_ref| crate::requests::resolve_changed_since(opts.root, git_ref));
173    crate::requests::measure_changed_since_scope(files);
174    let diff_index = health_diff_index(opts);
175    let mut ws_roots = resolve_workspace_scope(
176        opts.root,
177        opts.workspace,
178        opts.changed_workspaces,
179        opts.output,
180    )?;
181    if let Some(scope) = opts.scope.as_ref() {
182        ws_roots.get_or_insert_with(Vec::new).push(scope.clone());
183    }
184    let group_resolver = build_health_group_resolver(opts, config)?;
185    Ok(HealthScopeInputs {
186        changed_files,
187        diff_index,
188        ws_roots,
189        group_resolver,
190    })
191}
192
193/// Translate an engine [`HealthError`] into a CLI exit code at the command
194/// boundary. `Message` is rendered here (the engine no longer prints fatal
195/// errors); `Printed` was already emitted by a lower layer (the runtime-coverage
196/// seam), so its exit code is honored without a second error document.
197fn health_err_to_exit(error: HealthError, output: OutputFormat) -> ExitCode {
198    match error {
199        HealthError::Message { message, exit_code } => emit_error(&message, exit_code, output),
200        HealthError::Printed(code) => ExitCode::from(code),
201    }
202}
203
204/// Load config for a health run, validating coverage-root and churn-file inputs
205/// and the baseline destination up front (loud exit 2 on a malformed input).
206pub fn load_health_config(
207    opts: &HealthOptions<'_>,
208) -> Result<(fallow_config::ResolvedConfig, f64), ExitCode> {
209    if let Some(code) = crate::baseline_gate::refuse_save_before_analysis(
210        opts.save_baseline,
211        fallow_engine::baseline::BaselineKind::Health,
212        opts.output,
213    ) {
214        return Err(code);
215    }
216    fallow_engine::health::validate_coverage_root_absolute(opts.coverage_inputs.coverage_root)
217        .map_err(|e| emit_error(&e, 2, opts.output))?;
218    validate_health_churn_file(opts).map_err(|e| health_err_to_exit(e, opts.output))?;
219    let t = Instant::now();
220    let mut config = crate::load_config_for_analysis(
221        opts.root,
222        opts.config_path,
223        crate::ConfigLoadOptions {
224            output: opts.output,
225            no_cache: opts.no_cache,
226            threads: opts.threads,
227            production_override:
228                fallow_engine::project_config::ProductionFlags::single_analysis_override(
229                    opts.production,
230                    opts.production_override,
231                ),
232            quiet: opts.quiet,
233            allow_remote_extends: opts.allow_remote_extends,
234        },
235        fallow_config::ProductionAnalysis::Health,
236    )?;
237    if opts.gates.fail_on_parse_error {
238        config.fail_on_parse_error = true;
239    }
240    let config_ms = t.elapsed().as_secs_f64() * 1000.0;
241    Ok((config, config_ms))
242}
243
244/// Run health analysis using pre-parsed modules from the dead-code pipeline.
245///
246/// Skips file discovery and parsing (saves ~1.9s on 21K-file projects).
247/// `pre_computed_duplication` is a duplication report over the same files and
248/// duplicates config; health then skips its own duplicate detection.
249pub fn execute_health_with_shared_parse(
250    opts: &HealthOptions<'_>,
251    shared: HealthSharedParseData,
252    pre_computed_duplication: Option<fallow_engine::duplicates::DuplicationReport>,
253) -> Result<HealthResult, ExitCode> {
254    let (config, config_ms) = load_health_config(opts)?;
255    let scope_inputs = build_health_scope_inputs(opts, &config, &shared.files)?;
256    let workspace_diagnostics = fallow_config::workspace_diagnostics_for(&config.root);
257    let workspaces = shared.workspaces;
258    let seams = health_seams();
259    let result = execute_health_inner(
260        opts,
261        HealthPipelineInputs {
262            config,
263            files: shared.files,
264            modules: shared.modules,
265            config_ms,
266            discover_ms: 0.0,
267            parse_ms: 0.0,
268            parse_cpu_ms: 0.0,
269            shared_parse: true,
270            pre_computed_analysis: shared.analysis_output,
271            dead_code_results: shared.dead_code_results,
272            styling_artifacts: None,
273            pre_computed_duplication,
274            workspaces,
275            workspace_diagnostics,
276        },
277        scope_inputs,
278        &seams,
279    )
280    .map_err(|e| health_err_to_exit(e, opts.output))?;
281    record_health_telemetry(&result.report, result.coverage_gaps_has_findings);
282    Ok(result)
283}
284
285pub fn execute_health(opts: &HealthOptions<'_>) -> Result<HealthResult, ExitCode> {
286    let (config, config_ms) = load_health_config(opts)?;
287    execute_health_with_config(opts, config, config_ms)
288}
289
290pub fn execute_health_with_config(
291    opts: &HealthOptions<'_>,
292    config: fallow_config::ResolvedConfig,
293    config_ms: f64,
294) -> Result<HealthResult, ExitCode> {
295    let seams = health_seams();
296    let result = execute_health_with_config_and_seams(opts, config, config_ms, &seams)?;
297    record_health_telemetry(&result.report, result.coverage_gaps_has_findings);
298    Ok(result)
299}
300
301fn execute_health_with_config_and_seams(
302    opts: &HealthOptions<'_>,
303    config: fallow_config::ResolvedConfig,
304    config_ms: f64,
305    seams: &HealthSeams<'_>,
306) -> Result<HealthResult, ExitCode> {
307    let t = Instant::now();
308    let session = fallow_engine::session::AnalysisSession::from_resolved_config(config)
309        .map_err(|e| emit_error(&format!("analysis failed: {e}"), 2, opts.output))?;
310    let discover_ms = t.elapsed().as_secs_f64() * 1000.0;
311    let parts = session.parsed_parts_uncached(true);
312    let pre_computed_analysis =
313        fallow_engine::health::should_precompute_dead_code_analysis(opts, session.config())
314            .then(|| session.analyze_dead_code_with_parsed_modules(&parts.modules))
315            .transpose()
316            .map_err(|e| emit_error(&format!("analysis failed: {e}"), 2, opts.output))?;
317    let config = parts.config;
318    let files = parts.files;
319    let modules = parts.modules;
320    let workspaces = parts.workspaces;
321    let workspace_diagnostics = if pre_computed_analysis.is_some() {
322        session.current_workspace_diagnostics()
323    } else {
324        parts.workspace_diagnostics
325    };
326    let parse_ms = parts.parse_ms;
327    let parse_cpu_ms = parts.parse_cpu_ms;
328
329    let scope_inputs = build_health_scope_inputs(opts, &config, &files)?;
330    execute_health_inner(
331        opts,
332        HealthPipelineInputs {
333            config,
334            files,
335            modules,
336            config_ms,
337            discover_ms,
338            parse_ms,
339            parse_cpu_ms,
340            shared_parse: false,
341            dead_code_results: None,
342            styling_artifacts: None,
343            pre_computed_analysis,
344            pre_computed_duplication: None,
345            workspaces,
346            workspace_diagnostics,
347        },
348        scope_inputs,
349        seams,
350    )
351    .map_err(|e| health_err_to_exit(e, opts.output))
352}
353
354pub fn benchmark_execute_health_with_response(
355    opts: &HealthOptions<'_>,
356    response_bytes: &[u8],
357    request_len: &std::cell::Cell<usize>,
358) -> Result<HealthResult, ExitCode> {
359    let analyzer = |options: &fallow_engine::health::RuntimeCoverageOptions,
360                    input: RuntimeCoverageSeamInput<'_>| {
361        coverage::analyze_with_transport(
362            options,
363            &coverage::RuntimeCoverageAnalysisInput {
364                root: input.root,
365                modules: input.modules,
366                analysis_output: input.analysis_output,
367                istanbul_coverage: input.istanbul_coverage,
368                file_paths: input.file_paths,
369                ignore_set: input.ignore_set,
370                changed_files: input.changed_files,
371                ws_roots: input.ws_roots,
372                top: input.top,
373                codeowners_path: input.codeowners_path,
374                quiet: input.quiet,
375                output: input.output,
376            },
377            |request, _quiet, output| {
378                let (response, len) =
379                    coverage::in_process_response_transport(request, response_bytes, output)?;
380                request_len.set(len);
381                Ok(response)
382            },
383        )
384    };
385    let seams = HealthSeams {
386        runtime_coverage_analyzer: &analyzer,
387        note_graph_structure: &|_module_count, _edge_count| {},
388    };
389    let (config, config_ms) = load_health_config(opts)?;
390    execute_health_with_config_and_seams(opts, config, config_ms, &seams)
391}
392
393pub fn run_health(
394    opts: &HealthOptions<'_>,
395    json_style: crate::json_style::JsonStyle,
396    type_aware: &TypeAwareHealthOptions<'_>,
397) -> ExitCode {
398    let (config, config_ms) = match load_health_config(opts) {
399        Ok(config) => config,
400        Err(code) => return code,
401    };
402    let resolved_type_aware = match resolve_type_aware_health_options(type_aware, &config) {
403        Ok(options) => options,
404        Err(message) => return emit_error(&message, 2, opts.output),
405    };
406    let requested = type_aware.requested || (type_aware.unfiltered && resolved_type_aware.enabled);
407    let mut degraded_meta = None;
408    let semantic = if requested {
409        let enabled = resolved_type_aware.enabled;
410        if !enabled {
411            return emit_error(
412                "--type-coupling requires --type-aware or typeAware.enabled in config",
413                2,
414                opts.output,
415            );
416        }
417        let projects = resolved_type_aware.projects;
418        let require = resolved_type_aware.require;
419        match fallow_api::analyze_type_coupling(opts.root, &projects, &[]) {
420            Ok(outcome) => Some(outcome),
421            Err(error) => {
422                match crate::type_aware_degrade::degrade_or_fail(
423                    &crate::type_aware_degrade::DegradeContext {
424                        root: opts.root,
425                        error: &error.to_string(),
426                        failure_label: "Type-aware coupling failed",
427                        require,
428                        quiet: opts.quiet,
429                        output: opts.output,
430                    },
431                ) {
432                    Ok(meta) => degraded_meta = Some(meta),
433                    Err(code) => return code,
434                }
435                None
436            }
437        }
438    } else {
439        None
440    };
441    let mut execution_opts = opts.clone();
442    if let Some(identity) = semantic
443        .as_ref()
444        .and_then(|outcome| outcome.type_aware.meta.identity.clone())
445    {
446        execution_opts.analysis_identity = identity;
447    }
448    let mut result = match execute_health_with_config(&execution_opts, config, config_ms) {
449        Ok(result) => result,
450        Err(code) => return code,
451    };
452    // The policy this run resolved from the flag, the environment or the
453    // config. The config alone misses `--type-aware-require`.
454    let required_completeness = resolved_type_aware.require.into();
455    result.type_aware_meta = semantic
456        .map(|outcome| {
457            let mut meta = outcome.type_aware.meta;
458            meta.required_completeness = Some(required_completeness);
459            meta
460        })
461        .or(degraded_meta);
462    if let Some(ref timings) = result.timings {
463        report::print_health_performance(timings, opts.output, json_style);
464    }
465    report_loaded_baseline(&mut result, opts.baseline);
466    // The standalone run owns the parse-error gate. The config already holds
467    // the flag, and it also holds the `failOnParseError` key.
468    let gates = fallow_engine::health::HealthGateOptions {
469        fail_on_parse_error: result.config.fail_on_parse_error,
470        ..opts.gates
471    };
472    let code = print_health_result(
473        &result,
474        HealthPrintOptions {
475            quiet: opts.quiet,
476            explain: opts.explain,
477            gates,
478            baseline_path: opts.baseline,
479            summary: opts.summary,
480            summary_heading: true,
481            show_explain_tip: true,
482            type_aware_scope: None,
483            skip_score_and_trend: false,
484            css_requested: opts.css,
485            json_style,
486        },
487    );
488    if code != ExitCode::SUCCESS {
489        return code;
490    }
491    // The envelope states this gate through `type-aware-require`, which reads
492    // the same predicate.
493    ExitCode::from(crate::exit_codes::gate_failed_exit_code(
494        fallow_output::GateName::TypeAwareRequire,
495        crate::report::ci::required_type_aware_incomplete(result.type_aware_meta.as_ref()),
496    ))
497}
498
499pub struct ResolvedTypeAwareHealthOptions {
500    pub enabled: bool,
501    pub projects: Vec<std::path::PathBuf>,
502    pub require: fallow_config::TypeAwareRequire,
503}
504
505pub fn resolve_type_aware_health_options(
506    options: &TypeAwareHealthOptions<'_>,
507    config: &fallow_config::ResolvedConfig,
508) -> Result<ResolvedTypeAwareHealthOptions, String> {
509    let env_enabled = std::env::var("FALLOW_TYPE_AWARE")
510        .ok()
511        .map(|value| match value.trim().to_ascii_lowercase().as_str() {
512            "1" | "true" | "yes" | "on" => Ok(true),
513            "0" | "false" | "no" | "off" => Ok(false),
514            _ => Err(
515                "FALLOW_TYPE_AWARE must be one of true, false, 1, 0, yes, no, on, or off"
516                    .to_string(),
517            ),
518        })
519        .transpose()?;
520    let enabled = options
521        .enabled
522        .or(env_enabled)
523        .unwrap_or(config.type_aware.enabled);
524    let projects = if !options.projects.is_empty() {
525        options.projects.to_vec()
526    } else if let Some(value) = std::env::var_os("FALLOW_TYPE_AWARE_PROJECTS") {
527        std::env::split_paths(&value).collect()
528    } else {
529        config
530            .type_aware
531            .projects
532            .iter()
533            .map(std::path::PathBuf::from)
534            .collect()
535    };
536    let require = if let Some(require) = options.require {
537        require
538    } else if let Ok(value) = std::env::var("FALLOW_TYPE_AWARE_REQUIRE") {
539        match value.trim().to_ascii_lowercase().as_str() {
540            "best-effort" => fallow_config::TypeAwareRequire::BestEffort,
541            "complete" => fallow_config::TypeAwareRequire::Complete,
542            _ => {
543                return Err("FALLOW_TYPE_AWARE_REQUIRE must be best-effort or complete".to_string());
544            }
545        }
546    } else {
547        config.type_aware.require
548    };
549    Ok(ResolvedTypeAwareHealthOptions {
550        enabled,
551        projects,
552        require,
553    })
554}
555
556/// Result of executing health analysis without printing.
557pub type HealthResult =
558    fallow_engine::health::HealthAnalysisResult<crate::report::OwnershipResolver>;
559
560/// Print health results and return appropriate exit code.
561///
562/// When called from combined mode (`fallow --score` / `fallow --trend`),
563/// `skip_score_and_trend` MUST be `true`: the orientation header already
564/// renders both blocks and rendering them a second time here would duplicate
565/// the lines. Standalone `fallow health` invocations pass `false`.
566///
567/// Exit-code gating (when `report_only` is `false`): the score gate
568/// (`--min-score`), the findings gate (`--min-severity`, or any finding when
569/// no gate flag is set), the runtime-coverage gate, the opt-in stale-baseline
570/// gate (`--fail-on-stale-baseline`) and the coverage-gap gate are
571/// OR-combined. `report_only` short-circuits all of them to
572/// `ExitCode::SUCCESS` after rendering. Combined and audit callers pass
573/// `report_only: false` (they own their own gate semantics).
574///
575/// Callers that pass `min_score: Some(_)` must ensure
576/// `result.report.health_score` is `Some` (the CLI guarantees this because
577/// `--min-score` implies `--score`). If the score is missing the score gate
578/// cannot evaluate, so a direct API caller that requests a score gate without
579/// computing the score would get a permissive `ExitCode::SUCCESS`.
580#[derive(Clone, Copy)]
581pub struct HealthPrintOptions<'a> {
582    pub quiet: bool,
583    pub explain: bool,
584    pub gates: HealthGateOptions,
585    /// Loaded `--baseline` path, so the stale-baseline gate can name the file
586    /// to re-save. `None` when no baseline was loaded, which makes the gate
587    /// inert.
588    pub baseline_path: Option<&'a std::path::Path>,
589    pub summary: bool,
590    pub summary_heading: bool,
591    pub show_explain_tip: bool,
592    pub type_aware_scope: Option<&'static str>,
593    pub skip_score_and_trend: bool,
594    /// Whether `--css` was requested. Forwarded to the human renderer so an empty
595    /// CSS result (no import-reachable stylesheet) is explained rather than
596    /// silently omitted. Defaults `false` for callers that do not request CSS.
597    pub css_requested: bool,
598    pub json_style: crate::json_style::JsonStyle,
599}
600
601pub fn print_health_result(result: &HealthResult, options: HealthPrintOptions<'_>) -> ExitCode {
602    let ctx = health_report_context(result, options);
603    let report_code = report::print_health_report(
604        &result.report,
605        result.grouping.as_ref(),
606        result.group_resolver.as_ref(),
607        &ctx,
608        result.config.output,
609    );
610    if report_code != ExitCode::SUCCESS {
611        return report_code;
612    }
613
614    if options.gates.report_only {
615        note_stale_baseline_gate_stood_down(result, options);
616        return ExitCode::SUCCESS;
617    }
618
619    let code = health_exit_code(result, options);
620    if code == 0 {
621        maybe_print_score_gate_note(result, options);
622    }
623    crate::exit_codes::run_exit_code([code])
624}
625
626fn health_report_context<'a>(
627    result: &'a HealthResult,
628    options: HealthPrintOptions<'a>,
629) -> report::ReportContext<'a> {
630    report::ReportContext {
631        package_baselines: &[],
632        root: &result.config.root,
633        rules: &result.config.rules,
634        workspace_diagnostics: &result.workspace_diagnostics,
635        elapsed: result.elapsed,
636        quiet: options.quiet,
637        explain: options.explain,
638        type_aware: result.type_aware_meta.as_ref(),
639        type_aware_scope: options.type_aware_scope,
640        group_by: None,
641        top: None,
642        summary: options.summary,
643        summary_heading: options.summary_heading,
644        show_explain_tip: options.show_explain_tip,
645        baseline_matched: None,
646        baseline_staleness: None,
647        finding_id_query: None,
648        gate_outcomes: health_gate_outcomes(result, options),
649        config_fixable: false,
650        failed_parse_files: 0,
651        skip_score_and_trend: options.skip_score_and_trend,
652        css_requested: options.css_requested,
653        json_style: options.json_style,
654        include_fragments: true,
655    }
656}
657
658/// The gates a health run armed, for the envelope's `gate_outcomes`. The
659/// verdicts read the same values as the exit path.
660fn health_gate_outcomes(
661    result: &HealthResult,
662    options: HealthPrintOptions<'_>,
663) -> Option<fallow_output::GateOutcomes> {
664    crate::gates::health_gate_outcomes(&crate::gates::HealthGateInputs {
665        report_only: options.gates.report_only,
666        min_score: options.gates.min_score.map(|threshold| {
667            (
668                threshold,
669                result.report.health_score.as_ref().map(|score| score.score),
670            )
671        }),
672        min_severity: options.gates.min_severity.map(|floor| {
673            (
674                floor,
675                blocking_findings(result)
676                    .filter(|finding| finding.severity >= floor)
677                    .count(),
678            )
679        }),
680        coverage_gaps: result
681            .should_fail_on_coverage_gaps
682            .then_some(result.coverage_gaps_has_findings),
683        runtime_coverage: result
684            .report
685            .runtime_coverage
686            .is_some()
687            .then(|| has_failing_runtime_coverage(result)),
688        baseline_staleness: result.report.summary.baseline_staleness.as_ref(),
689        fail_on_stale_baseline: options.gates.fail_on_stale_baseline,
690        has_findings: blocking_findings(result).next().is_some(),
691        type_aware_meta: result.type_aware_meta.as_ref(),
692        parse_error: health_parse_error_outcome(result, options),
693    })
694}
695
696/// The `parse-error` gate of a health run, `None` unless this print owns the
697/// gate and the gate is armed. Built with `enforced: true`; the gate builder
698/// clamps it under `--report-only`.
699fn health_parse_error_outcome(
700    result: &HealthResult,
701    options: HealthPrintOptions<'_>,
702) -> Option<fallow_output::GateOutcome> {
703    crate::gates::parse_error_outcome(
704        options.gates.fail_on_parse_error,
705        true,
706        &crate::gates::parse_degraded_files(&result.config.root, &result.workspace_diagnostics),
707    )
708}
709
710/// The exit code of every health exit gate, with each gate evaluated before
711/// the codes are combined so that none of them can swallow another's stderr
712/// line.
713///
714/// The baseline gate is why this is not a short-circuiting chain: the score and
715/// findings gates have their condition printed in the report, a stale baseline
716/// has it nowhere, so a run that already fails the findings gate would exit 1
717/// with nothing about the baseline the user explicitly gated on.
718fn health_exit_code(result: &HealthResult, options: HealthPrintOptions<'_>) -> u8 {
719    use crate::exit_codes::gate_failed_exit_code;
720    use fallow_output::GateName;
721
722    let findings_gate = if options.gates.min_severity.is_some() {
723        GateName::HealthMinSeverity
724    } else {
725        GateName::HealthFindings
726    };
727    let parse_error = health_parse_error_outcome(result, options);
728    let parse_error_failed = parse_error
729        .as_ref()
730        .is_some_and(fallow_output::GateOutcome::fails_run);
731    if let Some(outcome) = parse_error.as_ref().filter(|_| parse_error_failed) {
732        crate::gates::print_parse_error_gate_failure(&outcome.files);
733    }
734    [
735        gate_failed_exit_code(GateName::HealthMinScore, score_gate_failed(result, options)),
736        gate_failed_exit_code(findings_gate, findings_gate_failed(result, options)),
737        gate_failed_exit_code(
738            GateName::HealthRuntimeCoverage,
739            has_failing_runtime_coverage(result),
740        ),
741        gate_failed_exit_code(
742            GateName::StaleBaseline,
743            stale_baseline_gate_failed(result, options),
744        ),
745        gate_failed_exit_code(
746            GateName::HealthCoverageGaps,
747            result.should_fail_on_coverage_gaps && result.coverage_gaps_has_findings,
748        ),
749        gate_failed_exit_code(GateName::ParseError, parse_error_failed),
750    ]
751    .into_iter()
752    .max()
753    .unwrap_or(0)
754}
755
756/// Say what this run made of the loaded baseline, and record it for the
757/// `recheck-baseline` next step.
758///
759/// Both happen here rather than at the engine's load site, which cannot reach
760/// CLI runtime state or print a CLI note, and only for the standalone command:
761/// `audit` and the combined run build their next steps from their own builders
762/// and would otherwise offer a `health` path on an envelope that is not
763/// health's.
764/// The note also records the writer in `baseline_staleness.saved_by`, which
765/// the gate line reads, so the note, the gate line and the envelope agree.
766fn report_loaded_baseline(result: &mut HealthResult, baseline_path: Option<&std::path::Path>) {
767    let Some(path) = baseline_path else {
768        return;
769    };
770    note_unrecognised_health_baseline(result, baseline_path, "--baseline");
771    let Some(staleness) = result.report.summary.baseline_staleness.as_ref() else {
772        return;
773    };
774    crate::output_runtime::set_loaded_baseline(crate::output_runtime::LoadedBaselineRecheck {
775        command: "health",
776        path: path.display().to_string(),
777        baseline_entries: staleness.baseline_entries,
778        scope_reasons: staleness.scope_reasons,
779    });
780}
781
782/// Say that the loaded baseline is not a health baseline.
783///
784/// Split from [`report_loaded_baseline`] because `fallow audit` needs the note
785/// and must not get the `recheck-baseline` record beside it: the audit envelope
786/// is not health's, so a `fallow health` next step on it would point at the
787/// wrong report. `dupes` and `dead-code` reach their notes through their own
788/// load sites, which audit shares.
789///
790/// `flag` is the argument that carried the path: `--health-baseline` on an audit
791/// and `--baseline` on the standalone command.
792///
793/// The engine classifies the file as a health baseline only, and the bytes are
794/// gone when the CLI prints. So this function reads the file one time, finds
795/// the known command that saved it, and writes that command into
796/// `baseline_staleness.saved_by`. The note, the gate line and the envelope all
797/// read that one value.
798pub fn note_unrecognised_health_baseline(
799    result: &mut HealthResult,
800    baseline_path: Option<&std::path::Path>,
801    flag: &str,
802) {
803    let Some(path) = baseline_path else {
804        return;
805    };
806    let Some(staleness) = result.report.summary.baseline_staleness.as_mut() else {
807        return;
808    };
809    if !staleness.unrecognised_format {
810        return;
811    }
812    let saved_by = saved_by_another_command(path);
813    staleness.saved_by = saved_by.map(fallow_engine::baseline::BaselineKind::as_str);
814    crate::baseline_gate::note_unrecognised_baseline(
815        Some(path),
816        true,
817        saved_by,
818        fallow_engine::baseline::BaselineKind::Health,
819        flag,
820    );
821}
822
823/// The known command that saved a baseline file, when it is not `health`.
824/// `None` for a file that names no known writer, which includes every baseline
825/// saved before `kind` existed, and for a file that can no longer be read.
826fn saved_by_another_command(
827    path: &std::path::Path,
828) -> Option<fallow_engine::baseline::BaselineKind> {
829    let content = std::fs::read_to_string(path).ok()?;
830    fallow_engine::baseline::classify_baseline_file(
831        &content,
832        fallow_engine::baseline::BaselineKind::Health,
833    )
834    .saved_by()
835}
836
837/// Say that `--report-only` suppressed the gate, so a job that passes both
838/// flags learns its baseline was never judged instead of going green forever.
839///
840/// `--report-only` is an explicit request never to fail the run, so the gate
841/// obeys it rather than overriding it; it just does not obey it in silence.
842fn note_stale_baseline_gate_stood_down(result: &HealthResult, options: HealthPrintOptions<'_>) {
843    let Some(staleness) = result.report.summary.baseline_staleness.as_ref() else {
844        return;
845    };
846    // A baseline with no entries gives the gate nothing to judge, so no gate
847    // stands down. A file this command cannot read as its own carries the same
848    // zero, and there the gate rule holds. `--report-only` then suppresses a real
849    // verdict, and it must say so.
850    if staleness.baseline_entries == 0 && !staleness.unrecognised_format {
851        return;
852    }
853    crate::baseline_gate::note_stood_down(
854        options.baseline_path,
855        options.gates.fail_on_stale_baseline,
856        "--report-only never fails a run",
857    );
858}
859
860/// The opt-in `--fail-on-stale-baseline` gate. Reads the staleness the engine
861/// already put in the report, so no extra plumbing crosses the engine boundary.
862fn stale_baseline_gate_failed(result: &HealthResult, options: HealthPrintOptions<'_>) -> bool {
863    let Some(staleness) = result.report.summary.baseline_staleness.as_ref() else {
864        return false;
865    };
866    crate::baseline_gate::gate_failed_from_envelope(
867        staleness,
868        options.baseline_path,
869        options.gates.fail_on_stale_baseline,
870        fallow_engine::baseline::BaselineKind::Health,
871    )
872}
873
874fn score_gate_failed(result: &HealthResult, options: HealthPrintOptions<'_>) -> bool {
875    let Some(threshold) = options.gates.min_score else {
876        return false;
877    };
878    let Some(ref hs) = result.report.health_score else {
879        return false;
880    };
881    if hs.score >= threshold {
882        return false;
883    }
884
885    if !options.quiet {
886        eprintln!(
887            "Health score {:.1} ({}) is below minimum threshold {:.0}",
888            hs.score, hs.grade, threshold
889        );
890    }
891    true
892}
893
894fn findings_gate_failed(result: &HealthResult, options: HealthPrintOptions<'_>) -> bool {
895    if let Some(min_sev) = options.gates.min_severity {
896        blocking_findings(result).any(|f| f.severity >= min_sev)
897    } else if options.gates.min_score.is_none() {
898        blocking_findings(result).next().is_some()
899    } else {
900        false
901    }
902}
903
904/// The findings whose `complexity-*` rule is `error`.
905///
906/// The rule applies first. `--min-severity` then filters these findings by
907/// band, so a `warn` finding never fails the run, whatever its band.
908fn blocking_findings(result: &HealthResult) -> impl Iterator<Item = &fallow_output::HealthFinding> {
909    result
910        .report
911        .findings
912        .iter()
913        .filter(|finding| finding.blocks())
914}
915
916fn has_failing_runtime_coverage(result: &HealthResult) -> bool {
917    result
918        .report
919        .runtime_coverage
920        .as_ref()
921        .is_some_and(|report| report.findings.iter().any(is_failing_runtime_coverage))
922}
923
924fn is_failing_runtime_coverage(finding: &fallow_output::RuntimeCoverageFinding) -> bool {
925    matches!(
926        finding.verdict,
927        fallow_output::RuntimeCoverageVerdict::SafeToDelete
928            | fallow_output::RuntimeCoverageVerdict::ReviewRequired
929            | fallow_output::RuntimeCoverageVerdict::LowTraffic
930    )
931}
932
933fn maybe_print_score_gate_note(result: &HealthResult, options: HealthPrintOptions<'_>) {
934    if options.gates.min_score.is_none()
935        || options.gates.min_severity.is_some()
936        || options.quiet
937        || result.report.findings.is_empty()
938        || !matches!(result.config.output, OutputFormat::Human)
939    {
940        return;
941    }
942
943    {
944        eprintln!(
945            "{}",
946            "Findings above are informational: --min-score gates on the score, not on findings."
947                .dimmed()
948        );
949    }
950}
951
952#[cfg(test)]
953mod tests {
954    use super::*;
955    use fallow_config::{FallowConfig, OutputFormat};
956    use fallow_output::{ComplexityViolation, ExceededThreshold, FindingSeverity};
957    use std::path::PathBuf;
958    use std::time::Duration;
959
960    fn make_finding(name: &str, exceeded: ExceededThreshold) -> ComplexityViolation {
961        ComplexityViolation {
962            path: PathBuf::from("/project/src/a.ts"),
963            name: name.to_string(),
964            line: 1,
965            col: 0,
966            cyclomatic: match exceeded {
967                ExceededThreshold::Cyclomatic
968                | ExceededThreshold::Both
969                | ExceededThreshold::CyclomaticCrap
970                | ExceededThreshold::All => 25,
971                _ => 8,
972            },
973            cognitive: match exceeded {
974                ExceededThreshold::Cognitive
975                | ExceededThreshold::Both
976                | ExceededThreshold::CognitiveCrap
977                | ExceededThreshold::All => 20,
978                _ => 5,
979            },
980            line_count: 10,
981            param_count: 0,
982            react_hook_count: 0,
983            react_jsx_max_depth: 0,
984            react_prop_count: 0,
985            react_hook_profile: None,
986            exceeded,
987            effective_severity: None,
988            severity: FindingSeverity::Moderate,
989            crap: exceeded.includes_crap().then_some(30.0),
990            coverage_pct: None,
991            coverage_tier: None,
992            coverage_source: None,
993            inherited_from: None,
994            component_rollup: None,
995            contributions: Vec::new(),
996            effective_thresholds: None,
997            threshold_source: None,
998        }
999    }
1000
1001    fn test_resolved_config() -> fallow_config::ResolvedConfig {
1002        FallowConfig::default().resolve(
1003            PathBuf::from("/project"),
1004            OutputFormat::Json,
1005            1,
1006            true,
1007            true,
1008            None,
1009        )
1010    }
1011
1012    fn fx_summary(
1013        tracked: usize,
1014        hit: usize,
1015        unhit: usize,
1016        untracked: usize,
1017    ) -> fallow_output::RuntimeCoverageSummary {
1018        #[expect(
1019            clippy::cast_precision_loss,
1020            reason = "test fixture totals are tiny, f64 precision is fine"
1021        )]
1022        let coverage_percent = if tracked == 0 {
1023            0.0
1024        } else {
1025            (hit as f64 / tracked as f64) * 100.0
1026        };
1027        fallow_output::RuntimeCoverageSummary {
1028            data_source: fallow_output::RuntimeCoverageDataSource::Local,
1029            last_received_at: None,
1030            functions_tracked: tracked,
1031            functions_hit: hit,
1032            functions_unhit: unhit,
1033            functions_untracked: untracked,
1034            coverage_percent,
1035            trace_count: 512,
1036            period_days: 7,
1037            deployments_seen: 2,
1038            capture_quality: None,
1039        }
1040    }
1041
1042    fn fx_evidence(
1043        static_status: &str,
1044        test_coverage: &str,
1045        v8_tracking: &str,
1046    ) -> fallow_output::RuntimeCoverageEvidence {
1047        fallow_output::RuntimeCoverageEvidence {
1048            static_status: static_status.to_owned(),
1049            test_coverage: test_coverage.to_owned(),
1050            test_only_reference: None,
1051            v8_tracking: v8_tracking.to_owned(),
1052            untracked_reason: None,
1053            observation_days: 7,
1054            deployments_observed: 2,
1055        }
1056    }
1057
1058    fn fx_health_score(score: f64, grade: &'static str) -> fallow_output::HealthScore {
1059        fallow_output::HealthScore {
1060            formula_version: 2,
1061            score,
1062            grade,
1063            penalties: fallow_output::HealthScorePenalties {
1064                dead_files: None,
1065                dead_exports: None,
1066                complexity: 0.0,
1067                p90_complexity: 0.0,
1068                maintainability: None,
1069                hotspots: None,
1070                unused_deps: None,
1071                circular_deps: None,
1072                unit_size: None,
1073                coupling: None,
1074                duplication: None,
1075                prop_drilling: None,
1076            },
1077        }
1078    }
1079
1080    fn fx_gate_result(
1081        findings: Vec<fallow_output::HealthFinding>,
1082        score: Option<fallow_output::HealthScore>,
1083    ) -> HealthResult {
1084        HealthResult {
1085            branching_by_file: fallow_engine::health::BranchingByFile::default(),
1086            report: fallow_output::HealthReport {
1087                findings,
1088                health_score: score,
1089                ..fallow_output::HealthReport::default()
1090            },
1091            grouping: None,
1092            group_resolver: None,
1093            config: test_resolved_config(),
1094            workspace_diagnostics: Vec::new(),
1095            elapsed: Duration::default(),
1096            timings: None,
1097            type_aware_meta: None,
1098            coverage_gaps_has_findings: false,
1099            should_fail_on_coverage_gaps: false,
1100            changed_files_analyzed: None,
1101        }
1102    }
1103
1104    fn moderate_finding() -> fallow_output::HealthFinding {
1105        make_finding("moderate", ExceededThreshold::Cyclomatic).into()
1106    }
1107
1108    fn critical_finding() -> fallow_output::HealthFinding {
1109        let mut v = make_finding("critical", ExceededThreshold::All);
1110        v.severity = FindingSeverity::Critical;
1111        v.into()
1112    }
1113
1114    /// Helper: run the gate with the given flags, quiet, no report-only.
1115    fn gate_exit(
1116        result: &HealthResult,
1117        min_score: Option<f64>,
1118        min_severity: Option<FindingSeverity>,
1119        report_only: bool,
1120    ) -> ExitCode {
1121        print_health_result(
1122            result,
1123            HealthPrintOptions {
1124                quiet: true,
1125                explain: false,
1126                gates: HealthGateOptions {
1127                    min_score,
1128                    min_severity,
1129                    report_only,
1130                    fail_on_stale_baseline: false,
1131                    fail_on_parse_error: false,
1132                    fail_on_issues: false,
1133                },
1134                baseline_path: None,
1135                summary: false,
1136                summary_heading: true,
1137                show_explain_tip: true,
1138                type_aware_scope: None,
1139                skip_score_and_trend: false,
1140                css_requested: false,
1141                json_style: crate::json_style::JsonStyle::Compact,
1142            },
1143        )
1144    }
1145
1146    #[test]
1147    fn plain_health_with_findings_fails() {
1148        let result = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(87.5, "A")));
1149        assert_eq!(gate_exit(&result, None, None, false), ExitCode::from(1));
1150    }
1151
1152    #[test]
1153    fn plain_health_with_no_findings_succeeds() {
1154        let result = fx_gate_result(vec![], Some(fx_health_score(100.0, "A")));
1155        assert_eq!(gate_exit(&result, None, None, false), ExitCode::SUCCESS);
1156    }
1157
1158    #[test]
1159    fn min_score_zero_never_fails_even_with_findings() {
1160        let result = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(50.0, "D")));
1161        assert_eq!(
1162            gate_exit(&result, Some(0.0), None, false),
1163            ExitCode::SUCCESS
1164        );
1165    }
1166
1167    #[test]
1168    fn min_score_passing_demotes_findings_to_informational() {
1169        let result = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(87.5, "A")));
1170        assert_eq!(
1171            gate_exit(&result, Some(80.0), None, false),
1172            ExitCode::SUCCESS
1173        );
1174    }
1175
1176    #[test]
1177    fn min_score_below_threshold_fails() {
1178        let result = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(50.0, "D")));
1179        assert_eq!(
1180            gate_exit(&result, Some(80.0), None, false),
1181            ExitCode::from(1)
1182        );
1183    }
1184
1185    #[test]
1186    fn min_severity_gates_on_severity_independent_of_min_score() {
1187        let only_moderate =
1188            fx_gate_result(vec![moderate_finding()], Some(fx_health_score(87.5, "A")));
1189        assert_eq!(
1190            gate_exit(&only_moderate, None, Some(FindingSeverity::Critical), false),
1191            ExitCode::SUCCESS,
1192        );
1193        let with_critical = fx_gate_result(
1194            vec![moderate_finding(), critical_finding()],
1195            Some(fx_health_score(87.5, "A")),
1196        );
1197        assert_eq!(
1198            gate_exit(&with_critical, None, Some(FindingSeverity::Critical), false),
1199            ExitCode::from(1),
1200        );
1201    }
1202
1203    #[test]
1204    fn min_score_and_min_severity_compose_as_or() {
1205        let pass = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(87.5, "A")));
1206        assert_eq!(
1207            gate_exit(&pass, Some(80.0), Some(FindingSeverity::Critical), false),
1208            ExitCode::SUCCESS,
1209        );
1210        let low_score = fx_gate_result(vec![moderate_finding()], Some(fx_health_score(50.0, "D")));
1211        assert_eq!(
1212            gate_exit(
1213                &low_score,
1214                Some(80.0),
1215                Some(FindingSeverity::Critical),
1216                false
1217            ),
1218            ExitCode::from(1),
1219        );
1220        let critical = fx_gate_result(vec![critical_finding()], Some(fx_health_score(87.5, "A")));
1221        assert_eq!(
1222            gate_exit(
1223                &critical,
1224                Some(80.0),
1225                Some(FindingSeverity::Critical),
1226                false
1227            ),
1228            ExitCode::from(1),
1229        );
1230    }
1231
1232    #[test]
1233    fn report_only_never_fails_on_findings_or_low_score() {
1234        let result = fx_gate_result(
1235            vec![moderate_finding(), critical_finding()],
1236            Some(fx_health_score(10.0, "F")),
1237        );
1238        assert_eq!(gate_exit(&result, None, None, true), ExitCode::SUCCESS);
1239    }
1240
1241    #[test]
1242    fn runtime_coverage_gate_independent_of_min_score() {
1243        let result = fx_low_traffic_runtime_result();
1244        assert_eq!(
1245            gate_exit(&result, Some(0.0), None, false),
1246            ExitCode::from(1)
1247        );
1248        assert_eq!(gate_exit(&result, None, None, true), ExitCode::SUCCESS);
1249    }
1250
1251    fn fx_low_traffic_runtime_result() -> HealthResult {
1252        HealthResult {
1253            branching_by_file: fallow_engine::health::BranchingByFile::default(),
1254            report: fallow_output::HealthReport {
1255                runtime_coverage: Some(fallow_output::RuntimeCoverageReport {
1256                    schema_version: fallow_output::RuntimeCoverageSchemaVersion::V1,
1257                    verdict: fallow_output::RuntimeCoverageReportVerdict::ColdCodeDetected,
1258                    signals: Vec::new(),
1259                    summary: fx_summary(1, 0, 1, 0),
1260                    findings: vec![fallow_output::RuntimeCoverageFinding {
1261                        id: "fallow:prod:lowtraffic".to_owned(),
1262                        stable_id: None,
1263                        path: PathBuf::from("/project/src/cold.ts"),
1264                        function: "coldPath".to_owned(),
1265                        line: 14,
1266                        verdict: fallow_output::RuntimeCoverageVerdict::LowTraffic,
1267                        invocations: Some(1),
1268                        confidence: fallow_output::RuntimeCoverageConfidence::Low,
1269                        evidence: fx_evidence("used", "not_covered", "tracked"),
1270                        actions: vec![],
1271                        source_hash: None,
1272                        discriminators: None,
1273                    }],
1274                    hot_paths: vec![],
1275                    blast_radius: vec![],
1276                    importance: vec![],
1277                    watermark: None,
1278                    warnings: vec![],
1279                    actionable: true,
1280                    actionability_reason: None,
1281                    actionability_verdict: None,
1282                    provenance: fallow_output::RuntimeCoverageProvenance::default(),
1283                }),
1284                ..fallow_output::HealthReport::default()
1285            },
1286            grouping: None,
1287            group_resolver: None,
1288            config: test_resolved_config(),
1289            workspace_diagnostics: Vec::new(),
1290            elapsed: Duration::default(),
1291            timings: None,
1292            type_aware_meta: None,
1293            coverage_gaps_has_findings: false,
1294            should_fail_on_coverage_gaps: false,
1295            changed_files_analyzed: None,
1296        }
1297    }
1298
1299    #[test]
1300    fn print_health_result_fails_on_low_traffic_runtime_coverage() {
1301        let result = fx_low_traffic_runtime_result();
1302
1303        assert_eq!(
1304            print_health_result(
1305                &result,
1306                HealthPrintOptions {
1307                    quiet: true,
1308                    explain: false,
1309                    gates: HealthGateOptions::default(),
1310                    baseline_path: None,
1311                    summary: false,
1312                    summary_heading: true,
1313                    show_explain_tip: true,
1314                    type_aware_scope: None,
1315                    skip_score_and_trend: false,
1316                    css_requested: false,
1317                    json_style: crate::json_style::JsonStyle::Compact,
1318                },
1319            ),
1320            ExitCode::from(1),
1321        );
1322    }
1323
1324    /// A type-aware metadata block that asks for the `complete` policy and
1325    /// holds a partial query, so the completeness gate fails.
1326    fn incomplete_required_type_aware_meta() -> fallow_types::envelope::TypeAwareMeta {
1327        fallow_types::envelope::TypeAwareMeta {
1328            required_completeness: Some(
1329                fallow_types::semantic::SemanticCompletenessRequirement::Complete,
1330            ),
1331            queries: vec![fallow_types::semantic::SemanticQuerySummary {
1332                query_id: 0,
1333                capability: fallow_types::semantic::SemanticCapability::TypeCoupling,
1334                assertion: "type coupling".to_string(),
1335                status: fallow_types::semantic::SemanticCompleteness::Partial,
1336                reason_code: None,
1337                total_evidence_count: 0,
1338                truncated: false,
1339                omissions: Vec::new(),
1340                actions: Vec::new(),
1341            }],
1342            ..Default::default()
1343        }
1344    }
1345
1346    #[test]
1347    fn the_envelope_states_a_failed_type_aware_completeness_gate() {
1348        let mut result = fx_gate_result(vec![], Some(fx_health_score(100.0, "A")));
1349        result.type_aware_meta = Some(incomplete_required_type_aware_meta());
1350        let options = HealthPrintOptions {
1351            quiet: true,
1352            explain: false,
1353            gates: HealthGateOptions::default(),
1354            baseline_path: None,
1355            summary: false,
1356            summary_heading: true,
1357            show_explain_tip: true,
1358            type_aware_scope: None,
1359            skip_score_and_trend: false,
1360            css_requested: false,
1361            json_style: crate::json_style::JsonStyle::Compact,
1362        };
1363        let gates = serde_json::to_value(health_gate_outcomes(&result, options))
1364            .expect("gate outcomes serialize");
1365        assert_eq!(
1366            gates["type-aware-require"],
1367            serde_json::json!({ "status": "fail", "enforced": true }),
1368            "the run exits 1 on this gate, so the envelope must state it: {gates}"
1369        );
1370    }
1371}