Skip to main content

release_kit/
diagnostic.rs

1//! Diagnostics as data: the closed reason vocabulary and the typed error
2//! report.
3//!
4//! An error is a value with named parts, rendered at the boundary — never
5//! a pre-formatted string assembled where the failure happened. The exit
6//! code stays the coarse machine signal; the `reason` beside it is the
7//! fine one, drawn from one closed vocabulary agents can branch on the
8//! way scripts branch on exit codes. The vocabulary is append-only: a
9//! reason is never renamed and never reused.
10
11use serde::Serialize;
12
13/// The version of the JSON diagnostic's shape.
14pub const DIAGNOSTIC_SCHEMA: &str = "rk.diagnostic/1";
15
16/// The closed reason vocabulary, the machine twin of the exit-code matrix.
17///
18/// Many reasons map to one exit code — that is the point: the code carries
19/// the category, the reason carries the instance. Classification is honest
20/// or absent: a failure nothing can classify further stays [`Reason::Io`]
21/// or [`Reason::Internal`] rather than guessing.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
23#[serde(rename_all = "kebab-case")]
24pub enum Reason {
25    /// Semantically invalid arguments or names.
26    Usage,
27    /// The named target does not exist or is not usable as a target.
28    TargetNotFound,
29    /// No forge could be detected from the repository's remote.
30    ForgeUndetected,
31    /// The detected or named forge is not one the binary supports.
32    ForgeUnsupported,
33    /// A prerequisite probe failed before any side effect.
34    PrerequisiteUnmet,
35    /// The forge CLI is present and not authenticated.
36    ForgeAuthentication,
37    /// The forge refused the caller's permissions.
38    ForgePermission,
39    /// The forge rate-limited the call.
40    ForgeRateLimit,
41    /// The forge failed in a way a retry can cure.
42    ForgeTemporary,
43    /// The remote state changed under the run.
44    RemoteConflict,
45    /// The command refused an action it judged destructive.
46    DestructiveRefusal,
47    /// The state found differs from what would permit the action.
48    StateDrift,
49    /// A record or document declares a schema this binary does not know.
50    UnsupportedSchema,
51    /// A mutating run could not create its journal.
52    JournalUnavailable,
53    /// A child process could not be spawned.
54    SubprocessSpawn,
55    /// A child process ran and failed without a finer classification.
56    SubprocessFailed,
57    /// Filesystem failure.
58    Io,
59    /// A defect in this binary.
60    Internal,
61    /// A hand-authored target configuration is invalid.
62    ConfigInvalid,
63    /// A registry did not answer. No live path emits it; the vocabulary
64    /// is append-only, so the word stays.
65    RegistryUnreachable,
66    /// A fetched artifact failed its verification. No live path emits
67    /// it; the vocabulary is append-only, so the word stays.
68    BundleUnverified,
69    /// A precondition did not hold before a write. No live path emits
70    /// it; the vocabulary is append-only, so the word stays.
71    PlanNotReady,
72    /// A postcondition found the target short after a write. No live
73    /// path emits it; the vocabulary is append-only, so the word stays.
74    PostconditionFailed,
75    /// Another run holds the target, and this one wrote nothing.
76    TargetBusy,
77    /// A read-only observation could not decide a step from where it ran,
78    /// and found no step wrong.
79    ObservationIncomplete,
80}
81
82/// Every reason, in declaration order; a test asserts against this so an
83/// addition is deliberate and a rename impossible.
84pub const REASONS: [Reason; 25] = [
85    Reason::Usage,
86    Reason::TargetNotFound,
87    Reason::ForgeUndetected,
88    Reason::ForgeUnsupported,
89    Reason::PrerequisiteUnmet,
90    Reason::ForgeAuthentication,
91    Reason::ForgePermission,
92    Reason::ForgeRateLimit,
93    Reason::ForgeTemporary,
94    Reason::RemoteConflict,
95    Reason::DestructiveRefusal,
96    Reason::StateDrift,
97    Reason::UnsupportedSchema,
98    Reason::JournalUnavailable,
99    Reason::SubprocessSpawn,
100    Reason::SubprocessFailed,
101    Reason::Io,
102    Reason::Internal,
103    Reason::ConfigInvalid,
104    Reason::RegistryUnreachable,
105    Reason::BundleUnverified,
106    Reason::PlanNotReady,
107    Reason::PostconditionFailed,
108    Reason::TargetBusy,
109    Reason::ObservationIncomplete,
110];
111
112impl Reason {
113    /// The kebab-case wire form, identical to the serde rendering.
114    #[must_use]
115    pub const fn as_str(self) -> &'static str {
116        match self {
117            Self::Usage => "usage",
118            Self::TargetNotFound => "target-not-found",
119            Self::ForgeUndetected => "forge-undetected",
120            Self::ForgeUnsupported => "forge-unsupported",
121            Self::PrerequisiteUnmet => "prerequisite-unmet",
122            Self::ForgeAuthentication => "forge-authentication",
123            Self::ForgePermission => "forge-permission",
124            Self::ForgeRateLimit => "forge-rate-limit",
125            Self::ForgeTemporary => "forge-temporary",
126            Self::RemoteConflict => "remote-conflict",
127            Self::DestructiveRefusal => "destructive-refusal",
128            Self::StateDrift => "state-drift",
129            Self::UnsupportedSchema => "unsupported-schema",
130            Self::JournalUnavailable => "journal-unavailable",
131            Self::SubprocessSpawn => "subprocess-spawn",
132            Self::SubprocessFailed => "subprocess-failed",
133            Self::Io => "io",
134            Self::Internal => "internal",
135            Self::ConfigInvalid => "config-invalid",
136            Self::RegistryUnreachable => "registry-unreachable",
137            Self::BundleUnverified => "bundle-unverified",
138            Self::PlanNotReady => "plan-not-ready",
139            Self::PostconditionFailed => "postcondition-failed",
140            Self::TargetBusy => "target-busy",
141            Self::ObservationIncomplete => "observation-incomplete",
142        }
143    }
144}
145
146/// One failure, with its parts named.
147///
148/// A hint that is not known is omitted rather than invented, so every
149/// optional field serializes only when present.
150#[derive(Debug, Clone, Serialize)]
151pub struct Diagnostic {
152    /// The shape version of the JSON rendering.
153    pub schema: &'static str,
154    /// One entry from the closed vocabulary.
155    pub reason: Reason,
156    /// What happened, one line.
157    pub message: String,
158    /// What would have had to be true.
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub expected: Option<String>,
161    /// The exact command or change that fixes it, when known.
162    #[serde(skip_serializing_if = "Option::is_none")]
163    pub action: Option<String>,
164    /// Whether rerunning as-is can succeed.
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub retry: Option<bool>,
167    /// What the run left behind, stated plainly.
168    #[serde(skip_serializing_if = "Option::is_none")]
169    pub target_state: Option<String>,
170    /// The step it happened in, where there is one.
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub step: Option<String>,
173    /// The run journal explaining it, where one was written.
174    #[serde(skip_serializing_if = "Option::is_none")]
175    pub run: Option<String>,
176}
177
178impl Diagnostic {
179    /// A diagnostic carrying only its reason and message; the builder
180    /// methods add what is actually known.
181    #[must_use]
182    pub fn new(reason: Reason, message: impl Into<String>) -> Self {
183        Self {
184            schema: DIAGNOSTIC_SCHEMA,
185            reason,
186            message: message.into(),
187            expected: None,
188            action: None,
189            retry: None,
190            target_state: None,
191            step: None,
192            run: None,
193        }
194    }
195
196    /// State what would have had to be true.
197    #[must_use]
198    pub fn expected(mut self, expected: impl Into<String>) -> Self {
199        self.expected = Some(expected.into());
200        self
201    }
202
203    /// Name the command or change that fixes it.
204    #[must_use]
205    pub fn action(mut self, action: impl Into<String>) -> Self {
206        self.action = Some(action.into());
207        self
208    }
209
210    /// State what the run left behind.
211    #[must_use]
212    pub fn target_state(mut self, state: impl Into<String>) -> Self {
213        self.target_state = Some(state.into());
214        self
215    }
216
217    /// Name the step the failure happened in.
218    #[must_use]
219    pub fn step(mut self, step: impl Into<String>) -> Self {
220        self.step = Some(step.into());
221        self
222    }
223
224    /// Name the run journal that explains the failure.
225    #[must_use]
226    pub fn run(mut self, run: impl Into<String>) -> Self {
227        self.run = Some(run.into());
228        self
229    }
230
231    /// The human rendering: the five questions in order — what happened,
232    /// what was expected, what to do, how to resume, what state the target
233    /// is in — with unknown lines absent rather than invented.
234    #[must_use]
235    pub fn render_human(&self) -> String {
236        use std::fmt::Write as _;
237        let mut text = format!("error: {}", self.message);
238        if let Some(expected) = &self.expected {
239            let _ = write!(text, "\n  expected  {expected}");
240        }
241        if let Some(action) = &self.action {
242            let _ = write!(text, "\n  next      {action}");
243        }
244        if let Some(retry) = self.retry {
245            let answer = if retry {
246                "rerunning as-is can succeed"
247            } else {
248                "rerunning as-is fails the same way"
249            };
250            let _ = write!(text, "\n  retry     {answer}");
251        }
252        if let Some(state) = &self.target_state {
253            let _ = write!(text, "\n  state     {state}");
254        }
255        if let Some(run) = &self.run {
256            let _ = write!(text, "\n  run       {run}");
257        }
258        text
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::{Diagnostic, REASONS, Reason};
265
266    /// The vocabulary is closed and append-only: this list is the one a
267    /// deliberate addition extends, and a rename fails here first.
268    #[test]
269    fn the_reason_vocabulary_is_closed() {
270        let wire: Vec<&str> = REASONS.iter().map(|reason| reason.as_str()).collect();
271        assert_eq!(
272            wire,
273            [
274                "usage",
275                "target-not-found",
276                "forge-undetected",
277                "forge-unsupported",
278                "prerequisite-unmet",
279                "forge-authentication",
280                "forge-permission",
281                "forge-rate-limit",
282                "forge-temporary",
283                "remote-conflict",
284                "destructive-refusal",
285                "state-drift",
286                "unsupported-schema",
287                "journal-unavailable",
288                "subprocess-spawn",
289                "subprocess-failed",
290                "io",
291                "internal",
292                "config-invalid",
293                "registry-unreachable",
294                "bundle-unverified",
295                "plan-not-ready",
296                "postcondition-failed",
297                "target-busy",
298                "observation-incomplete",
299            ]
300        );
301    }
302
303    #[test]
304    fn the_serde_rendering_and_the_wire_form_agree() {
305        for reason in REASONS {
306            let json = serde_json::to_string(&reason).expect("a reason serializes");
307            assert_eq!(json, format!("\"{}\"", reason.as_str()));
308        }
309    }
310
311    /// The `rk.diagnostic/1` schema, held by snapshot: a field rename or
312    /// removal fails here and becomes a schema-version bump instead of a
313    /// silent parser break at some agent.
314    #[test]
315    fn the_diagnostic_schema_snapshot_holds() {
316        let full = Diagnostic::new(Reason::StateDrift, "what happened")
317            .expected("what would have had to be true")
318            .action("the command that fixes it")
319            .target_state("what the run left behind");
320        assert_eq!(
321            serde_json::to_string(&full).expect("a diagnostic serializes"),
322            r#"{"schema":"rk.diagnostic/1","reason":"state-drift","message":"what happened","expected":"what would have had to be true","action":"the command that fixes it","target_state":"what the run left behind"}"#
323        );
324        let bare = Diagnostic::new(Reason::Io, "disk fell over");
325        assert_eq!(
326            serde_json::to_string(&bare).expect("a diagnostic serializes"),
327            r#"{"schema":"rk.diagnostic/1","reason":"io","message":"disk fell over"}"#,
328            "an unknown hint must be omitted, not serialized as null"
329        );
330    }
331
332    #[test]
333    fn the_human_rendering_answers_only_what_is_known() {
334        let bare = Diagnostic::new(Reason::Io, "disk fell over");
335        assert_eq!(bare.render_human(), "error: disk fell over");
336        let full = Diagnostic::new(Reason::StateDrift, "the target drifted")
337            .expected("a clean target")
338            .action("rk init --apply")
339            .target_state("nothing was written");
340        assert_eq!(
341            full.render_human(),
342            "error: the target drifted\n  expected  a clean target\n  next      rk init --apply\n  state     nothing was written"
343        );
344    }
345}