fallow-cli 3.34.1

CLI for fallow, codebase intelligence for TypeScript and JavaScript
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
//! Builders for the envelope's `gate_outcomes`, one per command.
//!
//! Every `GateOutcome` of a CLI envelope is built in this module. A command
//! passes the values its exit path already computed, and the rule that a
//! standalone command and the combined run share (for example
//! `error-severity-findings` or `health-findings`) has one builder here.
//!
//! Each builder projects the rules the command's exit path already applies, so
//! the published verdict and the process status cannot disagree. Nothing here
//! evaluates a condition of its own: every outcome reads the same value the
//! gate reads, which is why the identity tests in `crates/cli/tests` can assert
//! `gate_outcomes[g].status` against the feature-local field beside it.
//!
//! # When an entry appears
//!
//! A gate entry appears when the gate was ARMED on this run: `--fail-on-issues`
//! arms [`GateName::ErrorSeverityFindings`] as an enforced rule, a loaded
//! baseline arms [`GateName::StaleBaseline`], `--threshold` arms
//! [`GateName::DuplicationThreshold`], and so on.
//!
//! The default exit rule of a command is always in its object, also when no
//! flag armed a gate: `error-severity-findings` on `dead-code`, `check` and the
//! combined run, `health-findings` on `health`, `security-advisory` on
//! `security` and `audit-verdict` on `audit`. A JSON reader then sees a failing
//! run without the exit code. `dupes` has no default rule, so a `dupes` run
//! that armed nothing publishes no object and always exits 0. On `dupes`,
//! `--fail-on-issues` arms [`GateName::DuplicationFindings`].
//!
//! A gate that is armed but cannot be enforced publishes its verdict with
//! `enforced: false` rather than hiding it: `health --report-only`, a
//! change-scoped baseline comparison and the combined machine formats without
//! `--fail-on-issues`.

use std::path::Path;

use fallow_config::{WorkspaceDiagnostic, WorkspaceDiagnosticKind};
use fallow_output::{GateFile, GateName, GateOutcome, GateOutcomes, GateStatus};

/// `pass` or `fail` from a plain predicate.
pub const fn status_of(failed: bool) -> GateStatus {
    if failed {
        GateStatus::Fail
    } else {
        GateStatus::Pass
    }
}

/// The regression gate's outcome, `None` when no regression comparison ran.
///
/// `Skipped` maps to [`GateStatus::Skipped`] rather than to `pass`: the
/// comparison stood down (a change-scoped run, typically), and reporting that
/// as a pass would assert a judgement nothing made.
pub fn regression_outcome(
    outcome: Option<&crate::regression::RegressionOutcome>,
    enforced: bool,
) -> Option<GateOutcome> {
    #[expect(
        clippy::cast_precision_loss,
        reason = "issue counts never approach the f64 integer limit"
    )]
    fn delta(baseline: usize, current: usize) -> f64 {
        current as f64 - baseline as f64
    }

    let outcome = outcome?;
    Some(match outcome {
        crate::regression::RegressionOutcome::Pass {
            baseline_total,
            current_total,
        } => GateOutcome {
            status: GateStatus::Pass,
            enforced,
            observed: Some(delta(*baseline_total, *current_total)),
            // A pass records no tolerance, matching `regression.tolerance`,
            // which is null on the same outcome.
            threshold: None,
            threshold_label: None,
            files: Vec::new(),
        },
        crate::regression::RegressionOutcome::Exceeded {
            baseline_total,
            current_total,
            tolerance,
            ..
        } => GateOutcome {
            status: GateStatus::Fail,
            enforced,
            observed: Some(delta(*baseline_total, *current_total)),
            // The allowance rather than the tolerance's own number: a
            // percentage tolerance beside an absolute delta renders "12 against
            // 50" for a 50% allowance on a baseline of 3, which is a comparison
            // the reader cannot make. `allowed_delta` mirrors the gate's own
            // rule, so the two numbers are the ones the gate compared.
            threshold: Some(tolerance.allowed_delta(*baseline_total)),
            // The spelling the user passed, so the unit survives onto the
            // grouped envelope, which carries no `regression` object to read
            // `tolerance_kind` from.
            threshold_label: Some(tolerance.label()),
            files: Vec::new(),
        },
        crate::regression::RegressionOutcome::Skipped { .. } => {
            GateOutcome::new(GateStatus::Skipped, enforced)
        }
    })
}

/// The stale-baseline gate's outcome, `None` when no baseline was loaded.
///
/// Reads `gate_trips` off the envelope object the run already publishes, so the
/// two can never drift. `enforced` is the opt-in flag: the verdict is published
/// either way, and only the flag decides whether it fails the run.
///
/// A narrowed run cannot judge a whole-project baseline and stands down, with one
/// exception: telling a file this command never wrote from one of its own needs
/// no whole-project run, so an unrecognised baseline is judged at any scope. That
/// keeps this status equal to `gate_trips`, which is the identity the object
/// exists for.
pub const fn stale_baseline_outcome(
    staleness: Option<&fallow_output::BaselineStaleness>,
    fail_on_stale_baseline: bool,
) -> Option<GateOutcome> {
    let Some(staleness) = staleness else {
        return None;
    };
    if staleness.change_scoped && !staleness.unrecognised_format {
        return Some(GateOutcome::new(GateStatus::Skipped, false));
    }
    Some(GateOutcome::new(
        status_of(staleness.gate_trips),
        fail_on_stale_baseline,
    ))
}

/// The type-aware completeness gate's outcome, `None` unless the `complete`
/// policy was requested.
pub fn type_aware_outcome(
    require: fallow_config::TypeAwareRequire,
    meta: Option<&fallow_types::envelope::TypeAwareMeta>,
) -> Option<GateOutcome> {
    if require != fallow_config::TypeAwareRequire::Complete {
        return None;
    }
    let incomplete = crate::report::ci::required_type_aware_incomplete(meta);
    Some(GateOutcome::new(status_of(incomplete), true))
}

/// The type-aware completeness gate's outcome, read from the metadata of the
/// type-aware pass. `None` unless the metadata records the `complete` policy.
///
/// `health` and `audit` record the policy they resolved in
/// `required_completeness`, and their exit path reads the same predicate,
/// [`crate::report::ci::required_type_aware_incomplete`], so the entry and the
/// exit code cannot disagree.
pub fn type_aware_meta_outcome(
    meta: Option<&fallow_types::envelope::TypeAwareMeta>,
) -> Option<GateOutcome> {
    let required = meta?.required_completeness
        == Some(fallow_types::semantic::SemanticCompletenessRequirement::Complete);
    required.then(|| {
        GateOutcome::new(
            status_of(crate::report::ci::required_type_aware_incomplete(meta)),
            true,
        )
    })
}

/// The files of a run that did not parse cleanly, sorted by path, for the
/// `parse-error` gate.
///
/// Reads the `source-parse-degraded` entries of the run's workspace
/// diagnostics, so the gate and `workspace_diagnostics[]` name the same files.
/// Other kinds that set `degrades_analysis` do not count: several of them fire
/// on clean projects.
pub fn parse_degraded_files(root: &Path, diagnostics: &[WorkspaceDiagnostic]) -> Vec<GateFile> {
    let mut files: Vec<GateFile> = diagnostics
        .iter()
        .filter_map(|diagnostic| match diagnostic.kind {
            WorkspaceDiagnosticKind::SourceParseDegraded {
                error_count,
                panicked,
            } => Some(GateFile {
                path: fallow_types::path_util::display_relative(root, &diagnostic.path),
                error_count,
                panicked,
            }),
            _ => None,
        })
        .collect();
    files.sort_by(|a, b| a.path.cmp(&b.path));
    files.dedup_by(|a, b| a.path == b.path);
    files
}

/// The `parse-error` gate's outcome, `None` unless `--fail-on-parse-error` or
/// the `failOnParseError` config key armed it.
///
/// The exit path reads [`GateOutcome::fails_run`] on this same value, so the
/// entry and the exit code cannot disagree.
pub fn parse_error_outcome(armed: bool, enforced: bool, files: &[GateFile]) -> Option<GateOutcome> {
    armed.then(|| GateOutcome::with_files(status_of(!files.is_empty()), enforced, files.to_vec()))
}

/// The `parse-error` gate of a run with several sections (the bare run and
/// `audit`), `None` unless a section's config arms it.
///
/// Each section is its resolved config and its workspace diagnostics. The flag
/// reaches the config of each section, so the gate is armed when any section
/// holds it, and the files are the union of the sections' degraded files. The
/// entry keeps `enforced: true`, because both callers apply the gate in every
/// output format.
pub fn sections_parse_error_outcome(
    sections: &[(&fallow_config::ResolvedConfig, &[WorkspaceDiagnostic])],
) -> Option<GateOutcome> {
    if !sections
        .iter()
        .any(|(config, _)| config.fail_on_parse_error)
    {
        return None;
    }
    let (first, _) = sections.first()?;
    let diagnostics: Vec<WorkspaceDiagnostic> = sections
        .iter()
        .flat_map(|(_, diagnostics)| diagnostics.iter().cloned())
        .collect();
    parse_error_outcome(true, true, &parse_degraded_files(&first.root, &diagnostics))
}

/// The one-line reason of a degraded file, for human text: the number of
/// parser errors and whether the parser stopped.
pub fn parse_error_reason(file: &GateFile) -> String {
    let errors = if file.error_count == 1 {
        "1 parser error".to_owned()
    } else {
        format!("{} parser errors", file.error_count)
    };
    let outcome = if file.panicked {
        "the parser stopped"
    } else {
        "the parser recovered"
    };
    format!("{errors}, {outcome}")
}

/// Print the stderr lines of a failed `parse-error` gate: one status line, then
/// one line per file with its parser outcome.
///
/// Printed also under `--quiet`, like the stale-baseline note: `--ci` implies
/// `--quiet`, and SARIF and CodeClimate have no place for the verdict, so
/// without these lines a CI log shows exit 1 and no reason.
pub fn print_parse_error_gate_failure(files: &[GateFile]) {
    if files.is_empty() {
        return;
    }
    let noun = if files.len() == 1 { "file" } else { "files" };
    eprintln!(
        "{}",
        crate::report::human_status_line(
            crate::report::HumanStatus::Failure,
            format_args!(
                "Parse-error gate failed: fallow could not parse {} {noun} cleanly.",
                files.len()
            )
        )
    );
    for file in files {
        eprintln!("  {}: {}", file.path, parse_error_reason(file));
    }
}

/// The severity rule that decides a dead-code, check or combined run's exit
/// code, whether or not `--fail-on-issues` was passed.
///
/// Severity-aware rather than a count: a project with a rule set to `warn`
/// reports findings and still passes, and `--fail-on-issues` is what promotes
/// those warns into the rule. It is always `enforced` on the standalone
/// commands, because this rule always decides their exit code.
///
/// It is the default exit rule, so it is in every `dead-code` and `check`
/// object. Without it, a run gated only on `--fail-on-regression` could exit 1
/// for an error-severity finding while every entry reported a pass.
///
/// `observed` is `error_findings`, the number of findings at `error`
/// severity, and `threshold_label` is `error`.
pub fn error_severity_outcome(error_findings: usize, enforced: bool) -> GateOutcome {
    error_count_outcome(error_findings, enforced)
}

/// A gate that fails on any finding at `error` severity, with the number of
/// these findings as `observed`.
fn error_count_outcome(error_findings: usize, enforced: bool) -> GateOutcome {
    #[expect(
        clippy::cast_precision_loss,
        reason = "a finding count never approaches the f64 integer limit"
    )]
    let observed = error_findings as f64;
    GateOutcome::counted(status_of(error_findings > 0), enforced, observed, "error")
}

/// The default exit rule of `health`: a complexity finding whose
/// `complexity-*` rule is `error` fails the run.
/// Also the verdict of the health section of the combined run.
///
/// `observed` is the number of findings at `error` severity, so a reader of
/// the envelope sees how many findings fail the run.
pub fn health_findings_outcome(blocking: usize, enforced: bool) -> GateOutcome {
    error_count_outcome(blocking, enforced)
}

/// What [`print_exit_reason`] needs to state why a run exits non-zero.
pub struct ExitReason<'a> {
    /// The gates the run evaluated.
    pub gates: Option<&'a GateOutcomes>,
    /// The exit code of the run.
    pub code: u8,
    /// `--fail-on-issues` or `--ci`: the hint then names the flag.
    pub fail_on_issues: bool,
    /// `--quiet`.
    pub quiet: bool,
    /// The output format.
    pub output: fallow_config::OutputFormat,
    /// The gates that already printed their own failure line in this run. The
    /// exit-reason line does not repeat them.
    pub own_lines: &'a [GateName],
}

/// The gates of a dead-code or check print that state their failure on their
/// own line when the run is not quiet: the regression outcome and the
/// type-aware completeness warning.
pub const LOUD_CHECK_GATES: [GateName; 2] = [GateName::Regression, GateName::TypeAwareRequire];

/// Print the line that names the gates behind a non-zero exit code.
///
/// Printed under `--quiet` and for every format except the human report, like
/// the parse-error and stale-baseline lines: `--ci` implies `--quiet`, and the
/// machine formats have no place for the verdict. A human report without
/// `--quiet` already shows the findings and the score, so it gets no line. The
/// line goes to stderr, so the machine output on stdout stays unchanged.
pub fn print_exit_reason(reason: &ExitReason<'_>) {
    if !reason.quiet && matches!(reason.output, fallow_config::OutputFormat::Human) {
        return;
    }
    if let Some(line) = crate::report::gate_outcome_text::exit_reason_line(
        reason.gates,
        reason.code,
        reason.fail_on_issues,
        reason.own_lines,
    ) {
        eprintln!(
            "{}",
            crate::report::human_status_line(crate::report::HumanStatus::Failure, line)
        );
    }
}

/// The duplication threshold gate, `None` when no threshold was configured.
///
/// A threshold of zero means "no limit", which is the CLI's own reading, so it
/// arms nothing.
pub fn duplication_threshold_outcome(
    threshold: f64,
    duplication_percentage: f64,
    enforced: bool,
) -> Option<GateOutcome> {
    if threshold <= 0.0 {
        return None;
    }
    Some(GateOutcome::measured(
        status_of(crate::dupes::exceeds_threshold(
            threshold,
            duplication_percentage,
        )),
        // Arming, not the verdict: `enforced` answers "would a failure here
        // fail the run", so a passing threshold gate on a command that exits
        // on it still reports true, exactly as the stale-baseline gate does.
        enforced,
        duplication_percentage,
        threshold,
    ))
}

/// The clone-group gate, `None` unless `--fail-on-issues` (or `--ci`) armed it.
///
/// `clone_groups` is the count after the baseline and suppression filters,
/// which is the count the report shows. Any clone group fails the gate.
/// Always enforced when armed: `dupes` and every format of the bare run exit
/// on it.
pub fn duplication_findings_outcome(
    clone_groups: usize,
    fail_on_issues: bool,
) -> Option<GateOutcome> {
    #[expect(
        clippy::cast_precision_loss,
        reason = "clone group counts never approach the f64 integer limit"
    )]
    let observed = clone_groups as f64;
    fail_on_issues.then(|| GateOutcome::measured(status_of(clone_groups > 0), true, observed, 0.0))
}

/// Collect the gates a dead-code or check run evaluated.
pub struct CheckGateInputs<'a> {
    /// The number of findings at `error` severity.
    pub error_findings: usize,
    pub regression: Option<&'a crate::regression::RegressionOutcome>,
    pub baseline_staleness: Option<&'a fallow_output::BaselineStaleness>,
    pub fail_on_stale_baseline: bool,
    pub type_aware_require: fallow_config::TypeAwareRequire,
    pub type_aware_meta: Option<&'a fallow_types::envelope::TypeAwareMeta>,
    /// The `parse-error` gate, when it is armed. See [`parse_error_outcome`].
    pub parse_error: Option<GateOutcome>,
}

/// Build the dead-code envelope's `gate_outcomes`. Always present, because the
/// severity rule always decides the exit code.
pub fn check_gate_outcomes(input: &CheckGateInputs<'_>) -> Option<GateOutcomes> {
    let mut gates = GateOutcomes::new();
    gates.insert_if(
        GateName::Regression,
        regression_outcome(input.regression, true),
    );
    gates.insert_if(
        GateName::StaleBaseline,
        stale_baseline_outcome(input.baseline_staleness, input.fail_on_stale_baseline),
    );
    gates.insert_if(
        GateName::BaselineGrowth,
        crate::baseline_growth::recorded_outcome(crate::baseline_growth::GrowthOwner::DeadCode),
    );
    gates.insert_if(
        GateName::TypeAwareRequire,
        type_aware_outcome(input.type_aware_require, input.type_aware_meta),
    );
    gates.insert_if(GateName::ParseError, input.parse_error.clone());
    gates.insert(
        GateName::ErrorSeverityFindings,
        error_severity_outcome(input.error_findings, true),
    );
    gates.into_option()
}

/// The gates a duplication run evaluated.
///
/// The threshold verdict is the same [`crate::dupes::exceeds_threshold`] call
/// that the exit path makes, so the published status and the process status
/// cannot disagree. `dupes` has no default rule: a run that arms no gate
/// publishes no object.
pub fn dupes_gate_outcomes(
    threshold: f64,
    duplication_percentage: f64,
    clone_groups: usize,
    fail_on_issues: bool,
    baseline_staleness: Option<&fallow_output::BaselineStaleness>,
    fail_on_stale_baseline: bool,
) -> Option<GateOutcomes> {
    let mut gates = GateOutcomes::new();
    gates.insert_if(
        GateName::DuplicationThreshold,
        // Armed, not the verdict: the standalone command exits on this gate,
        // so a passing threshold still reports `enforced: true`.
        duplication_threshold_outcome(threshold, duplication_percentage, true),
    );
    gates.insert_if(
        GateName::DuplicationFindings,
        duplication_findings_outcome(clone_groups, fail_on_issues),
    );
    gates.insert_if(
        GateName::StaleBaseline,
        stale_baseline_outcome(baseline_staleness, fail_on_stale_baseline),
    );
    gates.insert_if(
        GateName::BaselineGrowth,
        crate::baseline_growth::recorded_outcome(crate::baseline_growth::GrowthOwner::Dupes),
    );
    gates.into_option()
}

/// What a health run armed, for [`health_gate_outcomes`].
pub struct HealthGateInputs<'a> {
    /// `--report-only`: every entry keeps its verdict with `enforced: false`.
    pub report_only: bool,
    /// `--min-score` with the computed score, when the gate is armed. A
    /// missing score means that the caller asked for the gate without the
    /// score it compares.
    pub min_score: Option<(f64, Option<f64>)>,
    /// `--min-severity` with the number of blocking findings at or above the
    /// floor.
    pub min_severity: Option<(fallow_output::FindingSeverity, usize)>,
    /// The coverage-gap gate when it is armed: whether the run has gaps.
    pub coverage_gaps: Option<bool>,
    /// The runtime-coverage gate when a report is present: whether a finding
    /// fails it.
    pub runtime_coverage: Option<bool>,
    /// The loaded baseline, when one was loaded.
    pub baseline_staleness: Option<&'a fallow_output::BaselineStaleness>,
    /// `--fail-on-stale-baseline`.
    pub fail_on_stale_baseline: bool,
    /// The number of complexity findings whose `complexity-*` rule is
    /// `error`.
    pub blocking_findings: usize,
    /// The metadata of the type-aware coupling pass, when it ran.
    pub type_aware_meta: Option<&'a fallow_types::envelope::TypeAwareMeta>,
    /// The `parse-error` gate, when it is armed, built with `enforced: true`.
    /// `--report-only` clamps it like every health gate.
    pub parse_error: Option<GateOutcome>,
}

/// The gates a health run armed.
///
/// Every entry reads the same predicate the exit path reads. `--report-only`
/// makes the run exit 0 before any gate runs, so it clamps `enforced` to false
/// on every entry and keeps each verdict. `health-findings` is the default
/// exit rule, so it is always in the object, except when `--min-severity`
/// replaces it. The type-aware completeness gate is not a health gate:
/// `--report-only` does not stop it, so its entry stays `enforced`.
pub fn health_gate_outcomes(input: &HealthGateInputs<'_>) -> Option<GateOutcomes> {
    let enforced = !input.report_only;
    let mut gates = GateOutcomes::new();
    gates.insert_if(
        GateName::TypeAwareRequire,
        type_aware_meta_outcome(input.type_aware_meta),
    );

    if let Some((threshold, score)) = input.min_score {
        gates.insert(
            GateName::HealthMinScore,
            score.map_or_else(
                || GateOutcome::new(GateStatus::Skipped, false),
                |score| {
                    GateOutcome::measured(status_of(score < threshold), enforced, score, threshold)
                },
            ),
        );
    }

    if let Some((floor, reached)) = input.min_severity {
        gates.insert(
            GateName::HealthMinSeverity,
            GateOutcome::counted(
                status_of(reached > 0),
                enforced,
                #[expect(
                    clippy::cast_precision_loss,
                    reason = "a finding count never approaches the f64 integer limit"
                )]
                {
                    reached as f64
                },
                severity_floor_label(floor),
            ),
        );
    }

    if let Some(has_gaps) = input.coverage_gaps {
        gates.insert(
            GateName::HealthCoverageGaps,
            GateOutcome::new(status_of(has_gaps), enforced),
        );
    }

    // Armed by `--runtime-coverage`, so it sits with the flag-armed gates:
    // without it, a run whose only gate is runtime coverage exits 1 and
    // publishes nothing.
    if let Some(failing) = input.runtime_coverage {
        gates.insert(
            GateName::HealthRuntimeCoverage,
            GateOutcome::new(status_of(failing), enforced),
        );
    }

    gates.insert_if(
        GateName::StaleBaseline,
        stale_baseline_outcome(
            input.baseline_staleness,
            input.fail_on_stale_baseline && enforced,
        ),
    );
    gates.insert_if(
        GateName::BaselineGrowth,
        crate::baseline_growth::recorded_outcome(crate::baseline_growth::GrowthOwner::Health),
    );

    gates.insert_if(
        GateName::ParseError,
        input.parse_error.clone().map(|mut outcome| {
            outcome.enforced &= enforced;
            outcome
        }),
    );

    // With `--min-severity` the findings gate IS the severity gate, recorded
    // above under its own name.
    if input.min_severity.is_none() {
        gates.insert(
            GateName::HealthFindings,
            if input.min_score.is_some() {
                // `--min-score` alone turns the findings branch off: complexity
                // findings become informational.
                GateOutcome::new(GateStatus::Skipped, false)
            } else {
                health_findings_outcome(input.blocking_findings, enforced)
            },
        );
    }

    gates.into_option()
}

/// The wire spelling of a severity floor, for `threshold_label`.
const fn severity_floor_label(severity: fallow_output::FindingSeverity) -> &'static str {
    match severity {
        fallow_output::FindingSeverity::Moderate => "moderate",
        fallow_output::FindingSeverity::High => "high",
        fallow_output::FindingSeverity::Critical => "critical",
    }
}

/// The gates a security run evaluated.
///
/// `gate_failed` is the verdict of `--gate` when it is set. A configured gate
/// decides the exit code before the advisory, so the advisory is recorded as
/// `skipped`: a passing gate that hides an advisory backlog is visible.
/// Without `--gate`, the advisory is the default exit rule and is always in the
/// object. It is `enforced` only when `--fail-on-issues` or an `error` rule
/// severity lets it fail the run.
pub fn security_gate_outcomes(
    gate_failed: Option<bool>,
    advisory_failed: bool,
    advisory_enforced: bool,
) -> Option<GateOutcomes> {
    let mut gates = GateOutcomes::new();
    if let Some(gate_failed) = gate_failed {
        gates.insert(
            GateName::Security,
            GateOutcome::new(status_of(gate_failed), true),
        );
        gates.insert(
            GateName::SecurityAdvisory,
            GateOutcome::new(GateStatus::Skipped, false),
        );
        return gates.into_option();
    }
    gates.insert(
        GateName::SecurityAdvisory,
        GateOutcome::new(status_of(advisory_failed), advisory_enforced),
    );
    gates.into_option()
}

/// The audit verdict, for the envelope's `gate_outcomes`.
///
/// The only three-valued gate: the warn tier reports `warn` and does not
/// collapse onto `pass`. Always present, because `fallow audit` always reaches
/// a verdict. A loaded baseline adds a `skipped`, unenforced `stale-baseline`
/// entry: every audit narrows to the changed files, so a whole-project baseline
/// cannot be judged. One entry stands for up to three baselines. A dead-code
/// pass that ran under the `complete` type-aware policy adds a
/// `type-aware-require` entry, because that gate also decides the exit code.
/// An armed `parse-error` gate adds its entry for the same reason.
pub fn audit_gate_outcomes(
    verdict: GateStatus,
    loaded_any_baseline: bool,
    type_aware_meta: Option<&fallow_types::envelope::TypeAwareMeta>,
    parse_error: Option<GateOutcome>,
) -> Option<GateOutcomes> {
    let mut gates = GateOutcomes::new();
    gates.insert(GateName::AuditVerdict, GateOutcome::new(verdict, true));
    gates.insert_if(
        GateName::TypeAwareRequire,
        type_aware_meta_outcome(type_aware_meta),
    );
    gates.insert_if(GateName::ParseError, parse_error);
    gates.insert_if(
        GateName::BaselineGrowth,
        crate::baseline_growth::recorded_outcome(crate::baseline_growth::GrowthOwner::Audit),
    );
    if loaded_any_baseline {
        gates.insert(
            GateName::StaleBaseline,
            GateOutcome::new(GateStatus::Skipped, false),
        );
    }
    gates.into_option()
}

/// What the sections of a bare `fallow` run concluded, for
/// [`combined_gate_outcomes`].
pub struct CombinedGateInputs<'a> {
    /// The regression outcome of the dead-code section.
    pub regression: Option<&'a crate::regression::RegressionOutcome>,
    /// The baselines each section loaded: dead code, dupes, health.
    pub baselines: [Option<fallow_output::BaselineStaleness>; 3],
    /// `--fail-on-stale-baseline`.
    pub fail_on_stale_baseline: bool,
    /// The type-aware completeness gate when the run requested it: whether
    /// it failed.
    pub type_aware_failed: Option<bool>,
    /// The duplication threshold and the measured percentage, when the dupes
    /// section ran.
    pub duplication: Option<(f64, f64)>,
    /// The number of clone groups the dupes section reports, when it ran.
    pub clone_groups: Option<usize>,
    /// The number of findings at `error` severity in the dead-code section,
    /// when it ran.
    pub error_findings: Option<usize>,
    /// The number of findings in the health section whose `complexity-*`
    /// rule is `error`, when it ran.
    pub health_blocking_findings: Option<usize>,
    /// The `parse-error` gate, when it is armed. The combined run applies it
    /// in every output format, so it keeps `enforced: true`.
    pub parse_error: Option<GateOutcome>,
    /// `--fail-on-issues` (or `--ci`): the machine formats then exit on the
    /// findings rules and the duplication threshold too.
    pub fail_on_issues: bool,
}

/// The entries of a bare `fallow` run that `--fail-on-issues` enforces. The
/// combined machine exit path applies these entries itself. The other enforced
/// entries have their own place in the exit path.
pub const FAIL_ON_ISSUES_GATES: [GateName; 4] = [
    GateName::ErrorSeverityFindings,
    GateName::HealthFindings,
    GateName::DuplicationThreshold,
    GateName::DuplicationFindings,
];

/// The exit code that the [`FAIL_ON_ISSUES_GATES`] entries of `gates` give a
/// combined machine run: 1 when one of them fails and is enforced, else 0.
#[must_use]
pub fn fail_on_issues_exit_code(gates: Option<&GateOutcomes>) -> u8 {
    let Some(gates) = gates else {
        return 0;
    };
    FAIL_ON_ISSUES_GATES
        .iter()
        .filter_map(|name| gates.get(*name).map(|outcome| (*name, outcome)))
        .filter(|(_, outcome)| outcome.fails_run())
        .map(|(name, outcome)| crate::exit_codes::gate_exit_code(name, outcome.status))
        .max()
        .unwrap_or(0)
}

/// The verdicts of a bare `fallow` run, merged into one root-level object.
///
/// It carries the default exit rule of each section that ran:
/// `error-severity-findings` for dead code and `health-findings` for health.
/// Dupes has no default rule. With these rules in it, the `status` members say
/// whether the human run of the same flags fails.
///
/// Without `--fail-on-issues`, the combined machine renderers exit 0 for every
/// gate except the stale-baseline gate, the baseline-growth gate, the
/// regression gate, the type-aware completeness gate and the parse-error gate,
/// so every other entry here reports `enforced: false`. With the flag, the
/// findings rules and the duplication threshold are enforced too, and the
/// machine exit code follows them (see [`FAIL_ON_ISSUES_GATES`]).
pub fn combined_gate_outcomes(input: &CombinedGateInputs<'_>) -> Option<GateOutcomes> {
    let mut gates = GateOutcomes::new();
    gates.insert_if(
        GateName::Regression,
        regression_outcome(input.regression, true),
    );
    gates.insert_if(
        GateName::StaleBaseline,
        merged_stale_baseline_outcome(&input.baselines, input.fail_on_stale_baseline),
    );
    gates.insert_if(
        GateName::BaselineGrowth,
        crate::baseline_growth::recorded_outcome(crate::baseline_growth::GrowthOwner::Combined),
    );
    if let Some(failed) = input.type_aware_failed {
        gates.insert(
            GateName::TypeAwareRequire,
            GateOutcome::new(status_of(failed), true),
        );
    }
    gates.insert_if(GateName::ParseError, input.parse_error.clone());
    if let Some((threshold, percentage)) = input.duplication {
        gates.insert_if(
            GateName::DuplicationThreshold,
            duplication_threshold_outcome(threshold, percentage, input.fail_on_issues),
        );
    }
    if let Some(clone_groups) = input.clone_groups {
        gates.insert_if(
            GateName::DuplicationFindings,
            duplication_findings_outcome(clone_groups, input.fail_on_issues),
        );
    }
    if let Some(error_findings) = input.error_findings {
        gates.insert(
            GateName::ErrorSeverityFindings,
            error_severity_outcome(error_findings, input.fail_on_issues),
        );
    }
    if let Some(blocking) = input.health_blocking_findings {
        gates.insert(
            GateName::HealthFindings,
            health_findings_outcome(blocking, input.fail_on_issues),
        );
    }
    gates.into_option()
}

/// One stale-baseline verdict for several loaded baselines: `fail` when any
/// baseline trips, else `pass` when any was judged, else the first stand-down.
fn merged_stale_baseline_outcome(
    baselines: &[Option<fallow_output::BaselineStaleness>],
    fail_on_stale_baseline: bool,
) -> Option<GateOutcome> {
    let outcomes: Vec<GateOutcome> = baselines
        .iter()
        .filter_map(|staleness| stale_baseline_outcome(staleness.as_ref(), fail_on_stale_baseline))
        .collect();
    let judged = |status: GateStatus| {
        outcomes
            .iter()
            .find(|outcome| outcome.status == status)
            .cloned()
    };
    judged(GateStatus::Fail)
        .or_else(|| judged(GateStatus::Pass))
        .or_else(|| outcomes.first().cloned())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_run_that_arms_nothing_still_states_the_default_rule() {
        let gates = check_gate_outcomes(&CheckGateInputs {
            error_findings: 1,
            regression: None,
            baseline_staleness: None,
            fail_on_stale_baseline: false,
            type_aware_require: fallow_config::TypeAwareRequire::BestEffort,
            type_aware_meta: None,
            parse_error: None,
        })
        .expect("the default exit rule is always published");
        let outcome = gates
            .get(GateName::ErrorSeverityFindings)
            .expect("the default exit rule");
        assert_eq!(outcome.status, GateStatus::Fail);
        assert!(outcome.fails_run());
    }

    /// The object has to explain the exit code it sits beside, so once it
    /// exists the rule that actually decides that exit code is in it.
    #[test]
    fn the_object_always_carries_the_rule_that_decides_the_exit_code() {
        let gates = check_gate_outcomes(&CheckGateInputs {
            error_findings: 1,
            regression: Some(&crate::regression::RegressionOutcome::Pass {
                baseline_total: 1,
                current_total: 1,
            }),
            baseline_staleness: None,
            fail_on_stale_baseline: false,
            type_aware_require: fallow_config::TypeAwareRequire::BestEffort,
            type_aware_meta: None,
            parse_error: None,
        })
        .expect("the regression gate armed the object");
        assert_eq!(
            gates.get(GateName::Regression).expect("armed").status,
            GateStatus::Pass
        );
        let outcome = gates
            .get(GateName::ErrorSeverityFindings)
            .expect("the default exit rule joins the object");
        assert_eq!(outcome.status, GateStatus::Fail);
        assert!(outcome.enforced);
    }

    #[test]
    fn a_published_baseline_verdict_is_unenforced_without_the_flag() {
        let staleness = fallow_output::BaselineStaleness {
            baseline_entries: 8,
            matched_entries: 3,
            stale_entries: 5,
            current_findings: 0,
            remaining_findings: None,
            change_scoped: false,
            stale: false,
            warning: fallow_output::BaselineStalenessAdvisory::None,
            gate_trips: true,
            moved_entries: 0,
            unrecognised_format: false,
            saved_by: None,
            format: None,
            scope_reasons: fallow_output::BaselineScopeReasons::empty(),
        };
        let unarmed = stale_baseline_outcome(Some(&staleness), false).expect("verdict published");
        assert_eq!(unarmed.status, GateStatus::Fail);
        assert!(!unarmed.enforced);
        assert!(!unarmed.fails_run());

        let armed = stale_baseline_outcome(Some(&staleness), true).expect("verdict published");
        assert!(armed.fails_run());
    }

    #[test]
    fn a_change_scoped_baseline_run_stands_down() {
        let staleness = fallow_output::BaselineStaleness {
            baseline_entries: 8,
            matched_entries: 0,
            stale_entries: 8,
            current_findings: 0,
            remaining_findings: None,
            change_scoped: true,
            stale: false,
            warning: fallow_output::BaselineStalenessAdvisory::None,
            gate_trips: false,
            moved_entries: 0,
            unrecognised_format: false,
            saved_by: None,
            format: None,
            scope_reasons: fallow_output::BaselineScopeReasons::empty()
                .with(fallow_output::ScopeReason::Production),
        };
        let outcome = stale_baseline_outcome(Some(&staleness), true).expect("verdict published");
        assert_eq!(outcome.status, GateStatus::Skipped);
        assert!(!outcome.fails_run());
    }

    #[test]
    fn a_zero_threshold_arms_no_duplication_gate() {
        assert!(duplication_threshold_outcome(0.0, 100.0, true).is_none());
        let outcome = duplication_threshold_outcome(5.0, 100.0, true).expect("gate armed");
        assert_eq!(outcome.status, GateStatus::Fail);
        assert_eq!(outcome.observed, Some(100.0));
        assert_eq!(outcome.threshold, Some(5.0));
    }

    #[test]
    fn a_skipped_regression_comparison_is_not_a_pass() {
        let outcome = regression_outcome(
            Some(&crate::regression::RegressionOutcome::Skipped {
                reason: "changed-since",
            }),
            true,
        )
        .expect("comparison ran");
        assert_eq!(outcome.status, GateStatus::Skipped);
    }

    fn type_aware_meta(
        required: fallow_types::semantic::SemanticCompletenessRequirement,
        completeness: fallow_types::semantic::SemanticCompleteness,
    ) -> fallow_types::envelope::TypeAwareMeta {
        fallow_types::envelope::TypeAwareMeta {
            required_completeness: Some(required),
            identity: Some(fallow_types::semantic::SemanticAnalysisIdentity {
                completeness,
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    #[test]
    fn the_type_aware_entry_follows_the_recorded_policy() {
        use fallow_types::semantic::{SemanticCompleteness, SemanticCompletenessRequirement};

        assert_eq!(type_aware_meta_outcome(None), None);
        let best_effort = type_aware_meta(
            SemanticCompletenessRequirement::BestEffort,
            SemanticCompleteness::Partial,
        );
        assert_eq!(type_aware_meta_outcome(Some(&best_effort)), None);

        let complete = type_aware_meta(
            SemanticCompletenessRequirement::Complete,
            SemanticCompleteness::Complete,
        );
        let partial = type_aware_meta(
            SemanticCompletenessRequirement::Complete,
            SemanticCompleteness::Partial,
        );
        for (meta, status) in [(&complete, GateStatus::Pass), (&partial, GateStatus::Fail)] {
            let outcome = type_aware_meta_outcome(Some(meta)).expect("the policy arms the gate");
            assert_eq!(outcome.status, status);
            assert!(outcome.enforced);
            assert_eq!(
                crate::exit_codes::gate_exit_code(GateName::TypeAwareRequire, outcome.status),
                u8::from(crate::report::ci::required_type_aware_incomplete(Some(
                    meta
                ))),
                "the entry and the exit path read one predicate"
            );
        }
    }

    fn degraded(root: &std::path::Path, file: &str, panicked: bool) -> WorkspaceDiagnostic {
        WorkspaceDiagnostic::new(
            root,
            root.join(file),
            WorkspaceDiagnosticKind::SourceParseDegraded {
                error_count: 2,
                panicked,
            },
        )
    }

    #[test]
    fn only_parse_degraded_files_count_and_they_come_sorted_and_relative() {
        let root = std::path::Path::new("/project");
        let diagnostics = vec![
            degraded(root, "src/z.ts", false),
            WorkspaceDiagnostic::new(
                root,
                root.join("node_modules"),
                WorkspaceDiagnosticKind::NodeModulesMissing,
            ),
            degraded(root, "src/a.tsx", true),
            degraded(root, "src/a.tsx", true),
        ];
        let files = parse_degraded_files(root, &diagnostics);
        assert_eq!(
            files,
            vec![
                GateFile {
                    path: "src/a.tsx".to_owned(),
                    error_count: 2,
                    panicked: true,
                },
                GateFile {
                    path: "src/z.ts".to_owned(),
                    error_count: 2,
                    panicked: false,
                },
            ]
        );
        assert_eq!(
            parse_error_reason(&files[0]),
            "2 parser errors, the parser stopped"
        );
    }

    #[test]
    fn an_unarmed_parse_error_gate_publishes_nothing() {
        let files = [GateFile {
            path: "src/a.ts".to_owned(),
            error_count: 1,
            panicked: false,
        }];
        assert_eq!(parse_error_outcome(false, true, &files), None);
        let armed = parse_error_outcome(true, true, &files).expect("armed");
        assert!(armed.fails_run());
        assert_eq!(armed.observed, Some(1.0));
        let clean = parse_error_outcome(true, true, &[]).expect("armed");
        assert_eq!(clean.status, GateStatus::Pass);
    }

    #[test]
    fn report_only_clamps_the_parse_error_entry() {
        let files = vec![GateFile {
            path: "src/a.ts".to_owned(),
            error_count: 1,
            panicked: false,
        }];
        let gates = health_gate_outcomes(&HealthGateInputs {
            report_only: true,
            min_score: None,
            min_severity: None,
            coverage_gaps: None,
            runtime_coverage: None,
            baseline_staleness: None,
            fail_on_stale_baseline: false,
            blocking_findings: 0,
            type_aware_meta: None,
            parse_error: parse_error_outcome(true, true, &files),
        })
        .expect("health always states its default rule");
        let entry = gates.get(GateName::ParseError).expect("armed");
        assert_eq!(entry.status, GateStatus::Fail);
        assert!(!entry.fails_run());
    }

    #[test]
    fn report_only_keeps_the_type_aware_entry_enforced() {
        use fallow_types::semantic::{SemanticCompleteness, SemanticCompletenessRequirement};

        let partial = type_aware_meta(
            SemanticCompletenessRequirement::Complete,
            SemanticCompleteness::Partial,
        );
        let gates = health_gate_outcomes(&HealthGateInputs {
            report_only: true,
            min_score: None,
            min_severity: None,
            coverage_gaps: None,
            runtime_coverage: None,
            baseline_staleness: None,
            fail_on_stale_baseline: false,
            blocking_findings: 0,
            type_aware_meta: Some(&partial),
            parse_error: None,
        })
        .expect("health always states its default rule");
        let json = serde_json::to_value(&gates).expect("gate outcomes serialize");
        assert_eq!(
            json["type-aware-require"],
            serde_json::json!({ "status": "fail", "enforced": true })
        );
        assert_eq!(json["health-findings"]["enforced"], false);
    }

    fn combined_inputs(fail_on_issues: bool) -> CombinedGateInputs<'static> {
        CombinedGateInputs {
            regression: None,
            baselines: [None, None, None],
            fail_on_stale_baseline: false,
            type_aware_failed: None,
            duplication: Some((1.0, 40.0)),
            clone_groups: Some(3),
            error_findings: Some(1),
            health_blocking_findings: Some(1),
            parse_error: None,
            fail_on_issues,
        }
    }

    #[test]
    fn fail_on_issues_enforces_the_combined_findings_entries() {
        for fail_on_issues in [false, true] {
            let gates = combined_gate_outcomes(&combined_inputs(fail_on_issues))
                .expect("the combined run states its default rules");
            for name in FAIL_ON_ISSUES_GATES {
                // Only `--fail-on-issues` arms the clone-group gate.
                if name == GateName::DuplicationFindings && !fail_on_issues {
                    assert!(gates.get(name).is_none());
                    continue;
                }
                let entry = gates.get(name).expect("every entry is armed here");
                assert_eq!(entry.status, GateStatus::Fail, "{name:?}");
                assert_eq!(entry.enforced, fail_on_issues, "{name:?}");
            }
            assert_eq!(
                fail_on_issues_exit_code(Some(&gates)),
                u8::from(fail_on_issues)
            );
        }
    }

    #[test]
    fn fail_on_issues_exits_zero_when_its_entries_pass() {
        let gates = combined_gate_outcomes(&CombinedGateInputs {
            duplication: Some((50.0, 10.0)),
            clone_groups: Some(0),
            error_findings: Some(0),
            health_blocking_findings: Some(0),
            ..combined_inputs(true)
        })
        .expect("the combined run states its default rules");
        assert_eq!(fail_on_issues_exit_code(Some(&gates)), 0);
        assert_eq!(fail_on_issues_exit_code(None), 0);
    }
}