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