Skip to main content

fallow_report_protocol/
gate.rs

1//! The verdict of one gate on one run.
2//!
3//! A gate is a rule that can fail a run. Each fallow tool keys these values by
4//! its own gate names.
5
6use serde::Serialize;
7
8/// What a gate concluded on this run.
9///
10/// Four-valued rather than a boolean because audit's verdict has a warn tier
11/// (`crates/cli/src/cli_report.rs` maps it onto three conclusions) and because
12/// a gate can stand down without passing. Widening a published boolean later
13/// would retype a required field and bump every carrying envelope, so the width
14/// is decided here.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
16#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
17#[serde(rename_all = "kebab-case")]
18pub enum GateStatus {
19    /// The gate ran and its condition did not hold.
20    Pass,
21    /// The gate ran and reached a warn tier that does not fail the run. Only
22    /// `audit-verdict` can report this today.
23    Warn,
24    /// The gate ran and its condition held.
25    Fail,
26    /// The gate could not judge this run and deliberately stood down: a
27    /// change-scoped baseline comparison, `health --report-only`, or a security
28    /// advisory shadowed by a configured gate. Distinct from `pass`, which
29    /// asserts the condition was evaluated and did not hold.
30    Skipped,
31}
32
33/// One gate's verdict on one run.
34///
35/// `status` and `enforced` answer different questions and legitimately
36/// disagree. `status` is what the rule concluded; `enforced` is whether a
37/// `fail` from this gate would make the run exit non-zero. A
38/// `health --report-only` run is an explicit request never to fail, so a
39/// failing gate there reports `status: fail` with `enforced: false`, and a
40/// stale-baseline verdict published without `--fail-on-stale-baseline` reports
41/// the same pair.
42///
43/// **A gate fails the build when `status` is `fail` AND `enforced` is true.**
44/// Neither member decides it alone: `enforced` is true on every armed gate,
45/// including the ones that passed, so gating on it by itself fails every run
46/// that armed anything. Read `status` on its own to decide what to say, and
47/// remember that `warn` and `skipped` are neither a pass nor a failure.
48#[derive(Debug, Clone, PartialEq, Serialize)]
49#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
50pub struct GateOutcome {
51    /// What the rule concluded.
52    pub status: GateStatus,
53    /// True when a `fail` from this gate makes the run exit non-zero. False
54    /// when the verdict is published for information only: the gate was never
55    /// armed, the run was told never to fail, or the combined machine formats
56    /// exit 0 for the gate (bare `fallow` without `--fail-on-issues`).
57    pub enforced: bool,
58    /// The measured value the gate compared, when there is one: the duplication
59    /// percentage, the health score, the number of findings at or above the
60    /// severity floor, the number of `error` findings of `health-findings` and
61    /// of `error-severity-findings`, or
62    /// the number of files in `files`. Whole numbers are
63    /// carried as JSON numbers, so a count of three reads as `3.0`. Absent for
64    /// gates that compare no number.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub observed: Option<f64>,
67    /// The configured limit `observed` was compared against, when there is one.
68    /// Absent for gates that compare no number.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub threshold: Option<f64>,
71    /// How the limit was spelled, for a gate whose `threshold` number does not
72    /// carry its own unit. `health-min-severity` sets it to the severity floor
73    /// (`moderate`, `high` or `critical`); `health-findings` and
74    /// `error-severity-findings` set it to `error`, the rule severity they
75    /// count; `regression` sets it to the
76    /// tolerance as the user wrote it (`"50%"` or `"5"`), because `threshold`
77    /// there is the allowance in issues and the percentage would otherwise be
78    /// unrecoverable on the grouped envelope, which carries no `regression`
79    /// object. Absent for gates whose numbers speak for themselves.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub threshold_label: Option<String>,
82    /// The files the gate judged, for a gate that judges files rather than a
83    /// number. Only `parse-error` sets it: one item per file that did not
84    /// parse cleanly, sorted by path. Absent when the list is empty.
85    #[serde(default, skip_serializing_if = "Vec::is_empty")]
86    pub files: Vec<GateFile>,
87}
88
89/// One file a file-judging gate names, with the reason the gate counted it.
90///
91/// Today only `parse-error` emits it. The item carries the same facts as the
92/// `source-parse-degraded` entry in `workspace_diagnostics[]` for that file,
93/// so a consumer can act on the gate without a join. With `reason` set, the
94/// count and the parser outcome are placeholders.
95#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
96#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
97pub struct GateFile {
98    /// The file path, relative to the project root, with `/` separators.
99    pub path: String,
100    /// The number of parser errors for the file. `1` when `reason` is set.
101    pub error_count: u32,
102    /// True when the parser stopped in the file instead of recovering, so the
103    /// analysis saw only the part before the error. `true` when `reason` is set.
104    pub panicked: bool,
105    /// Why the file counts when it is not a parser error. Absent for a parser
106    /// error, the only reason before this field existed.
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub reason: Option<GateFileReason>,
109}
110
111/// Why a file counts for the `parse-error` gate, other than a parser error.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
113#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
114#[serde(rename_all = "kebab-case")]
115pub enum GateFileReason {
116    /// The file nests too deep to parse, so it was not parsed
117    /// (`source-nesting-too-deep`).
118    NestingTooDeep,
119}
120
121impl GateOutcome {
122    /// A gate that ran, compared no number, and was armed.
123    #[must_use]
124    pub const fn new(status: GateStatus, enforced: bool) -> Self {
125        Self {
126            status,
127            enforced,
128            observed: None,
129            threshold: None,
130            threshold_label: None,
131            files: Vec::new(),
132        }
133    }
134
135    /// A gate that compared `observed` against `threshold`.
136    #[must_use]
137    pub const fn measured(
138        status: GateStatus,
139        enforced: bool,
140        observed: f64,
141        threshold: f64,
142    ) -> Self {
143        Self {
144            status,
145            enforced,
146            observed: Some(observed),
147            threshold: Some(threshold),
148            threshold_label: None,
149            files: Vec::new(),
150        }
151    }
152
153    /// A gate that counted `observed` items at or above a named floor.
154    #[must_use]
155    pub fn counted(
156        status: GateStatus,
157        enforced: bool,
158        observed: f64,
159        threshold_label: &str,
160    ) -> Self {
161        Self {
162            status,
163            enforced,
164            observed: Some(observed),
165            threshold: None,
166            threshold_label: Some(threshold_label.to_owned()),
167            files: Vec::new(),
168        }
169    }
170
171    /// A gate that judged files: `observed` is the number of files it named.
172    #[must_use]
173    pub fn with_files(status: GateStatus, enforced: bool, files: Vec<GateFile>) -> Self {
174        #[expect(
175            clippy::cast_precision_loss,
176            reason = "a file count never approaches the f64 integer limit"
177        )]
178        let observed = files.len() as f64;
179        Self {
180            status,
181            enforced,
182            observed: Some(observed),
183            threshold: None,
184            threshold_label: None,
185            files,
186        }
187    }
188
189    /// Whether this outcome should make the run exit non-zero.
190    #[must_use]
191    pub const fn fails_run(&self) -> bool {
192        self.enforced && matches!(self.status, GateStatus::Fail)
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199
200    #[test]
201    fn an_unenforced_failure_does_not_fail_the_run() {
202        let outcome = GateOutcome::new(GateStatus::Fail, false);
203        assert!(!outcome.fails_run());
204        let enforced = GateOutcome::new(GateStatus::Fail, true);
205        assert!(enforced.fails_run());
206    }
207
208    #[test]
209    fn a_skipped_gate_never_fails_the_run() {
210        assert!(!GateOutcome::new(GateStatus::Skipped, true).fails_run());
211        assert!(!GateOutcome::new(GateStatus::Warn, true).fails_run());
212    }
213}