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