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