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