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 or an index the engine reads a release from did not
64    /// answer.
65    RegistryUnreachable,
66    /// A fetched release bundle failed its verification against the
67    /// registry's own checksum, and nothing of it was kept.
68    BundleUnverified,
69    /// A stored plan is not ready: a required precondition does not hold
70    /// or a decision the operator owns waits, and nothing was written.
71    PlanNotReady,
72    /// An apply's writes landed and a postcondition then found the target
73    /// short of what the plan promised.
74    PostconditionFailed,
75    /// Another run holds the target, and this one wrote nothing.
76    TargetBusy,
77}
78
79/// Every reason, in declaration order; a test asserts against this so an
80/// addition is deliberate and a rename impossible.
81pub const REASONS: [Reason; 24] = [
82    Reason::Usage,
83    Reason::TargetNotFound,
84    Reason::ForgeUndetected,
85    Reason::ForgeUnsupported,
86    Reason::PrerequisiteUnmet,
87    Reason::ForgeAuthentication,
88    Reason::ForgePermission,
89    Reason::ForgeRateLimit,
90    Reason::ForgeTemporary,
91    Reason::RemoteConflict,
92    Reason::DestructiveRefusal,
93    Reason::StateDrift,
94    Reason::UnsupportedSchema,
95    Reason::JournalUnavailable,
96    Reason::SubprocessSpawn,
97    Reason::SubprocessFailed,
98    Reason::Io,
99    Reason::Internal,
100    Reason::ConfigInvalid,
101    Reason::RegistryUnreachable,
102    Reason::BundleUnverified,
103    Reason::PlanNotReady,
104    Reason::PostconditionFailed,
105    Reason::TargetBusy,
106];
107
108impl Reason {
109    /// The kebab-case wire form, identical to the serde rendering.
110    #[must_use]
111    pub const fn as_str(self) -> &'static str {
112        match self {
113            Self::Usage => "usage",
114            Self::TargetNotFound => "target-not-found",
115            Self::ForgeUndetected => "forge-undetected",
116            Self::ForgeUnsupported => "forge-unsupported",
117            Self::PrerequisiteUnmet => "prerequisite-unmet",
118            Self::ForgeAuthentication => "forge-authentication",
119            Self::ForgePermission => "forge-permission",
120            Self::ForgeRateLimit => "forge-rate-limit",
121            Self::ForgeTemporary => "forge-temporary",
122            Self::RemoteConflict => "remote-conflict",
123            Self::DestructiveRefusal => "destructive-refusal",
124            Self::StateDrift => "state-drift",
125            Self::UnsupportedSchema => "unsupported-schema",
126            Self::JournalUnavailable => "journal-unavailable",
127            Self::SubprocessSpawn => "subprocess-spawn",
128            Self::SubprocessFailed => "subprocess-failed",
129            Self::Io => "io",
130            Self::Internal => "internal",
131            Self::ConfigInvalid => "config-invalid",
132            Self::RegistryUnreachable => "registry-unreachable",
133            Self::BundleUnverified => "bundle-unverified",
134            Self::PlanNotReady => "plan-not-ready",
135            Self::PostconditionFailed => "postcondition-failed",
136            Self::TargetBusy => "target-busy",
137        }
138    }
139}
140
141/// One failure, with its parts named.
142///
143/// A hint that is not known is omitted rather than invented, so every
144/// optional field serializes only when present.
145#[derive(Debug, Clone, Serialize)]
146pub struct Diagnostic {
147    /// The shape version of the JSON rendering.
148    pub schema: &'static str,
149    /// One entry from the closed vocabulary.
150    pub reason: Reason,
151    /// What happened, one line.
152    pub message: String,
153    /// What would have had to be true.
154    #[serde(skip_serializing_if = "Option::is_none")]
155    pub expected: Option<String>,
156    /// The exact command or change that fixes it, when known.
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub action: Option<String>,
159    /// Whether rerunning as-is can succeed.
160    #[serde(skip_serializing_if = "Option::is_none")]
161    pub retry: Option<bool>,
162    /// What the run left behind, stated plainly.
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub target_state: Option<String>,
165    /// The step it happened in, where there is one.
166    #[serde(skip_serializing_if = "Option::is_none")]
167    pub step: Option<String>,
168    /// The run journal explaining it, where one was written.
169    #[serde(skip_serializing_if = "Option::is_none")]
170    pub run: Option<String>,
171}
172
173impl Diagnostic {
174    /// A diagnostic carrying only its reason and message; the builder
175    /// methods add what is actually known.
176    #[must_use]
177    pub fn new(reason: Reason, message: impl Into<String>) -> Self {
178        Self {
179            schema: DIAGNOSTIC_SCHEMA,
180            reason,
181            message: message.into(),
182            expected: None,
183            action: None,
184            retry: None,
185            target_state: None,
186            step: None,
187            run: None,
188        }
189    }
190
191    /// State what would have had to be true.
192    #[must_use]
193    pub fn expected(mut self, expected: impl Into<String>) -> Self {
194        self.expected = Some(expected.into());
195        self
196    }
197
198    /// Name the command or change that fixes it.
199    #[must_use]
200    pub fn action(mut self, action: impl Into<String>) -> Self {
201        self.action = Some(action.into());
202        self
203    }
204
205    /// State what the run left behind.
206    #[must_use]
207    pub fn target_state(mut self, state: impl Into<String>) -> Self {
208        self.target_state = Some(state.into());
209        self
210    }
211
212    /// Name the step the failure happened in.
213    #[must_use]
214    pub fn step(mut self, step: impl Into<String>) -> Self {
215        self.step = Some(step.into());
216        self
217    }
218
219    /// Name the run journal that explains the failure.
220    #[must_use]
221    pub fn run(mut self, run: impl Into<String>) -> Self {
222        self.run = Some(run.into());
223        self
224    }
225
226    /// The human rendering: the five questions in order — what happened,
227    /// what was expected, what to do, how to resume, what state the target
228    /// is in — with unknown lines absent rather than invented.
229    #[must_use]
230    pub fn render_human(&self) -> String {
231        use std::fmt::Write as _;
232        let mut text = format!("error: {}", self.message);
233        if let Some(expected) = &self.expected {
234            let _ = write!(text, "\n  expected  {expected}");
235        }
236        if let Some(action) = &self.action {
237            let _ = write!(text, "\n  next      {action}");
238        }
239        if let Some(retry) = self.retry {
240            let answer = if retry {
241                "rerunning as-is can succeed"
242            } else {
243                "rerunning as-is fails the same way"
244            };
245            let _ = write!(text, "\n  retry     {answer}");
246        }
247        if let Some(state) = &self.target_state {
248            let _ = write!(text, "\n  state     {state}");
249        }
250        if let Some(run) = &self.run {
251            let _ = write!(text, "\n  run       {run}");
252        }
253        text
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::{Diagnostic, REASONS, Reason};
260
261    /// The vocabulary is closed and append-only: this list is the one a
262    /// deliberate addition extends, and a rename fails here first.
263    #[test]
264    fn the_reason_vocabulary_is_closed() {
265        let wire: Vec<&str> = REASONS.iter().map(|reason| reason.as_str()).collect();
266        assert_eq!(
267            wire,
268            [
269                "usage",
270                "target-not-found",
271                "forge-undetected",
272                "forge-unsupported",
273                "prerequisite-unmet",
274                "forge-authentication",
275                "forge-permission",
276                "forge-rate-limit",
277                "forge-temporary",
278                "remote-conflict",
279                "destructive-refusal",
280                "state-drift",
281                "unsupported-schema",
282                "journal-unavailable",
283                "subprocess-spawn",
284                "subprocess-failed",
285                "io",
286                "internal",
287                "config-invalid",
288                "registry-unreachable",
289                "bundle-unverified",
290                "plan-not-ready",
291                "postcondition-failed",
292                "target-busy",
293            ]
294        );
295    }
296
297    #[test]
298    fn the_serde_rendering_and_the_wire_form_agree() {
299        for reason in REASONS {
300            let json = serde_json::to_string(&reason).expect("a reason serializes");
301            assert_eq!(json, format!("\"{}\"", reason.as_str()));
302        }
303    }
304
305    /// The `rk.diagnostic/1` schema, held by snapshot: a field rename or
306    /// removal fails here and becomes a schema-version bump instead of a
307    /// silent parser break at some agent.
308    #[test]
309    fn the_diagnostic_schema_snapshot_holds() {
310        let full = Diagnostic::new(Reason::StateDrift, "what happened")
311            .expected("what would have had to be true")
312            .action("the command that fixes it")
313            .target_state("what the run left behind");
314        assert_eq!(
315            serde_json::to_string(&full).expect("a diagnostic serializes"),
316            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"}"#
317        );
318        let bare = Diagnostic::new(Reason::Io, "disk fell over");
319        assert_eq!(
320            serde_json::to_string(&bare).expect("a diagnostic serializes"),
321            r#"{"schema":"rk.diagnostic/1","reason":"io","message":"disk fell over"}"#,
322            "an unknown hint must be omitted, not serialized as null"
323        );
324    }
325
326    #[test]
327    fn the_human_rendering_answers_only_what_is_known() {
328        let bare = Diagnostic::new(Reason::Io, "disk fell over");
329        assert_eq!(bare.render_human(), "error: disk fell over");
330        let full = Diagnostic::new(Reason::StateDrift, "the target drifted")
331            .expected("a clean target")
332            .action("rk init --apply")
333            .target_state("nothing was written");
334        assert_eq!(
335            full.render_human(),
336            "error: the target drifted\n  expected  a clean target\n  next      rk init --apply\n  state     nothing was written"
337        );
338    }
339}