Skip to main content

stikk_model/
error.rs

1//! The single stikk error type and its seven presentation classes.
2//!
3//! Design `stikk-04` ER-01/ER-02, threat model `stikk-03` OP-03/CT-04. Two lessons from the 2026
4//! prikk audit are applied here to stikk's own error type: it implements [`std::error::Error::source`]
5//! so causes are inspectable, and it is `#[non_exhaustive]` so adding a class is not a breaking
6//! change. The load-bearing rule is [`StikkError::Refusal`] and friends **preserve prikk's message
7//! verbatim** — no layer above rewrites it (NFR-I03); a localized gloss is added beside it, never in
8//! place of it.
9
10use std::fmt;
11
12/// Convenience alias for a fallible stikk operation.
13pub type Result<T> = std::result::Result<T, StikkError>;
14
15/// Every error stikk surfaces, tagged with the class that decides how it is presented (design
16/// `stikk-04` CT-04). The class is the whole point: a refusal opens the explanation overlay, a lock
17/// conflict is a banner, a not-ready is inline guidance, and so on — one mapping, both frontends.
18///
19/// `#[non_exhaustive]`: adding a class later is not a breaking change to downstream matchers.
20#[derive(Debug)]
21#[non_exhaustive]
22pub enum StikkError {
23    /// prikk semantically refused an operation (a non-confluent merge, a TOFU key conflict, a
24    /// path/ref validation refusal). `message` is prikk's own wording, preserved verbatim.
25    Refusal {
26        /// prikk's verbatim refusal message. Never rewritten by a layer above.
27        message: String,
28    },
29    /// Another writer holds a lock, or a CAS precondition failed. Presented as "another writer is
30    /// active", never as corruption (design FR-106). prikk distinguishes a genuine lock from a
31    /// ref-CAS mismatch; both arrive here and the message carries which.
32    LockConflict {
33        /// prikk's verbatim conflict message.
34        message: String,
35    },
36    /// A signing or trust prerequisite is absent — no AUTHOR/MAINTAINER readiness, or the maintainer
37    /// key is not adopted. Presented as inline guidance toward the trust/keys surface (FR-104).
38    NotReady {
39        /// What is missing, in stikk's own words (this class is stikk-originated, not prikk's).
40        detail: String,
41    },
42    /// A verify/doctor finding — repository-content diagnostics. Routed into the verify/doctor views,
43    /// never a popup (design OP-03). **Currently unconstructible**: the seam's own arm that used to
44    /// build this (`is_integrity_finding`) had no captured message behind any of its three strings and
45    /// was removed rather than kept on a guess (RFC 017 F2/§3) — nothing in the workspace constructs
46    /// this variant today. It stays in the taxonomy because `present()`'s `RoutedIntoView` mapping is
47    /// the right forward shape for `FR-100`'s still-unbuilt Verify view, and a future classifier arm
48    /// grounded on real `verify`/`doctor` output will need somewhere to route to.
49    IntegrityFinding {
50        /// prikk's verbatim finding text.
51        message: String,
52    },
53    /// An input ceiling was (or would be) exceeded — a bundle/exchange/summary limit. Surfaced in the
54    /// pre-execution confirmation, not after failure (threat model C-D2a).
55    Limits {
56        /// prikk's verbatim limit message.
57        message: String,
58    },
59    /// An environment problem: I/O, permissions, a missing or wrong `prikk` binary, version skew, or
60    /// an unparseable prikk output shape. Carries a stikk-authored description plus any underlying
61    /// cause via [`std::error::Error::source`].
62    Environment {
63        /// What went wrong, in stikk's own words.
64        detail: String,
65        /// The underlying cause, if any (e.g. a `std::io::Error`), preserved for `source()`.
66        source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
67    },
68    /// A stikk-internal fault (a bug). The repository was not touched — only the seam writes, and only
69    /// on an explicit confirmed mutation — so a fault here can never be a repository write (design
70    /// ER-04). Session state is already flushed; the user may continue read-only.
71    Internal {
72        /// A description of the internal invariant that was violated.
73        detail: String,
74    },
75    /// The repository changed between a preview and its confirmation, or between confirmation and
76    /// execution (design `OPL-02`/`CT-05`; RFC 013 decision 3). **`prikk` did not refuse this — stikk
77    /// did**, on comparing the change token stamped at preview time against a freshly-read one. Never
78    /// `Refusal` (that would put stikk's own words in prikk's voice) and never `LockConflict` (nothing
79    /// is locked). The user's next action is to look again: `present()` routes this to a re-preview
80    /// prompt, and no next-step it offers may re-run the execution (`NFR-S04`).
81    Stale {
82        /// The operation whose preview or confirmation no longer matches the repository's current
83        /// state — stikk's own short name for it (e.g. `"commit"`), never prikk's words.
84        operation: String,
85    },
86    /// The confirmation evidence supplied did not satisfy the tier's requirement: a missing explicit
87    /// yes, or a typed name that does not exactly match the confirmation summary's target (design
88    /// `FR-121`; RFC 013 §4). Distinct from [`StikkError::Stale`] (nothing about the repository moved)
89    /// and from [`StikkError::NotReady`] (capability and read-only mode were both sufficient — the
90    /// *evidence itself* was not). Belongs inside the confirmation surface that asked for the evidence,
91    /// never a separate popup (`Presentation::InConfirmation`) — the user is still mid-confirmation, not
92    /// facing a new failure.
93    Declined {
94        /// What was required and what was supplied, in stikk's own words.
95        detail: String,
96    },
97    /// A commit refused because the active WAL's queue targets a different ref than the one requested
98    /// (design RFC 014 F2/decision 2). **Never [`StikkError::LockConflict`]**, even though prikk words
99    /// it as one (`"lock conflict: active WAL is owned by …; requested ref …"`) — nothing is locked, no
100    /// other writer is active, and `LockConflict` will grow a jump to a lock inspector (`FR-102`) that
101    /// would show this condition no lock to find (RFC 012 F-b's overloaded-class shape, again). stikk
102    /// prevents this client-side before arming a commit (`Orientation::queued_target`); this class
103    /// exists for the race where the queue moves between preview and execute. `message` is prikk's own
104    /// wording, preserved verbatim (`ER-02`) — the same discipline as [`StikkError::Refusal`].
105    CrossRef {
106        /// prikk's verbatim cross-ref refusal message.
107        message: String,
108    },
109}
110
111impl StikkError {
112    /// Construct an [`StikkError::Environment`] from a description and an underlying cause.
113    #[must_use]
114    pub fn environment(
115        detail: impl Into<String>,
116        source: impl std::error::Error + Send + Sync + 'static,
117    ) -> Self {
118        Self::Environment {
119            detail: detail.into(),
120            source: Some(Box::new(source)),
121        }
122    }
123
124    /// Construct an [`StikkError::Environment`] with no underlying cause.
125    #[must_use]
126    pub fn environment_msg(detail: impl Into<String>) -> Self {
127        Self::Environment {
128            detail: detail.into(),
129            source: None,
130        }
131    }
132
133    /// The stable machine-readable class name, for the report format (design CL-07) and for tests.
134    #[must_use]
135    pub const fn class(&self) -> &'static str {
136        match self {
137            Self::Refusal { .. } => "refusal",
138            Self::LockConflict { .. } => "lock-conflict",
139            Self::NotReady { .. } => "not-ready",
140            Self::IntegrityFinding { .. } => "integrity-finding",
141            Self::Limits { .. } => "limits",
142            Self::Environment { .. } => "environment",
143            Self::Internal { .. } => "stikk-internal",
144            Self::Stale { .. } => "stale",
145            Self::Declined { .. } => "declined",
146            Self::CrossRef { .. } => "cross-ref",
147        }
148    }
149
150    /// True when this class must never be auto-retried (design NFR-S04): a refusal, a lock conflict, a
151    /// not-ready condition, a stale precondition, declined evidence, or a cross-ref conflict is the
152    /// user's to resolve, never stikk's to retry silently. `Stale` in particular must never be retried
153    /// as-is — its whole point is that retrying the same execution is exactly the prohibited thing (RFC
154    /// 013 decision 3); the user's only correct next step is a fresh preview.
155    #[must_use]
156    pub const fn is_user_resolved(&self) -> bool {
157        matches!(
158            self,
159            Self::Refusal { .. }
160                | Self::LockConflict { .. }
161                | Self::NotReady { .. }
162                | Self::Stale { .. }
163                | Self::Declined { .. }
164                | Self::CrossRef { .. }
165        )
166    }
167}
168
169impl fmt::Display for StikkError {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        match self {
172            Self::Refusal { message }
173            | Self::LockConflict { message }
174            | Self::IntegrityFinding { message }
175            | Self::Limits { message }
176            | Self::CrossRef { message } => write!(f, "{}: {message}", self.class()),
177            Self::NotReady { detail } | Self::Internal { detail } | Self::Declined { detail } => {
178                write!(f, "{}: {detail}", self.class())
179            }
180            Self::Environment { detail, .. } => write!(f, "environment: {detail}"),
181            Self::Stale { operation } => {
182                write!(
183                    f,
184                    "stale: {operation}'s preview no longer matches the repository"
185                )
186            }
187        }
188    }
189}
190
191impl std::error::Error for StikkError {
192    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
193        match self {
194            Self::Environment {
195                source: Some(cause),
196                ..
197            } => Some(cause.as_ref()),
198            _ => None,
199        }
200    }
201}
202
203#[cfg(test)]
204mod tests;