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        /// **Which check saw it** (RFC 030 amendment A3): the change-token comparison, or commit's
95        /// worktree re-read. Only the check that failed knows, and the words a user reads differ,
96        /// because a worktree change is not a repository change (`C-T2b`).
97        cause: StaleCause,
98    },
99    /// The confirmation evidence supplied did not satisfy the tier's requirement: a missing explicit
100    /// yes, or a typed name that does not exactly match the confirmation summary's target (design
101    /// `FR-121`; RFC 013 §4). Distinct from [`StikkError::Stale`] (nothing about the repository moved)
102    /// and from [`StikkError::NotReady`] (capability and read-only mode were both sufficient — the
103    /// *evidence itself* was not). Belongs inside the confirmation surface that asked for the evidence,
104    /// never a separate popup (`Presentation::InConfirmation`) — the user is still mid-confirmation, not
105    /// facing a new failure.
106    Declined {
107        /// What was required and what was supplied, in stikk's own words.
108        detail: String,
109    },
110    /// A commit refused because the active WAL's queue targets a different ref than the one requested
111    /// (design RFC 014 F2/decision 2). **Never [`StikkError::LockConflict`]**, even though prikk words
112    /// it as one (`"lock conflict: active WAL is owned by …; requested ref …"`) — nothing is locked, no
113    /// other writer is active, and `LockConflict` will grow a jump to a lock inspector (`FR-102`) that
114    /// would show this condition no lock to find (RFC 012 F-b's overloaded-class shape, again). stikk
115    /// prevents this client-side before arming a commit (`Orientation::queued_target`); this class
116    /// exists for the race where the queue moves between preview and execute. `message` is prikk's own
117    /// wording, preserved verbatim (`ER-02`) — the same discipline as [`StikkError::Refusal`].
118    CrossRef {
119        /// prikk's verbatim cross-ref refusal message.
120        message: String,
121    },
122}
123
124impl StikkError {
125    /// Construct an [`StikkError::Environment`] from a description and an underlying cause.
126    #[must_use]
127    pub fn environment(
128        detail: impl Into<String>,
129        source: impl std::error::Error + Send + Sync + 'static,
130    ) -> Self {
131        Self::Environment {
132            detail: detail.into(),
133            source: Some(Box::new(source)),
134        }
135    }
136
137    /// Construct an [`StikkError::Environment`] with no underlying cause.
138    #[must_use]
139    pub fn environment_msg(detail: impl Into<String>) -> Self {
140        Self::Environment {
141            detail: detail.into(),
142            source: None,
143        }
144    }
145
146    /// The stable machine-readable class name, for the report format (design CL-07) and for tests.
147    #[must_use]
148    pub const fn class(&self) -> &'static str {
149        match self {
150            Self::Refusal { .. } => "refusal",
151            Self::LockConflict { .. } => "lock-conflict",
152            Self::NotReady { .. } => "not-ready",
153            Self::IntegrityFinding { .. } => "integrity-finding",
154            Self::Limits { .. } => "limits",
155            Self::Environment { .. } => "environment",
156            Self::Internal { .. } => "stikk-internal",
157            Self::Stale { .. } => "stale",
158            Self::Declined { .. } => "declined",
159            Self::CrossRef { .. } => "cross-ref",
160        }
161    }
162
163    /// True when this class must never be auto-retried (design NFR-S04): a refusal, a lock conflict, a
164    /// not-ready condition, a stale precondition, declined evidence, or a cross-ref conflict is the
165    /// user's to resolve, never stikk's to retry silently. `Stale` in particular must never be retried
166    /// as-is — its whole point is that retrying the same execution is exactly the prohibited thing (RFC
167    /// 013 decision 3); the user's only correct next step is a fresh preview.
168    #[must_use]
169    pub const fn is_user_resolved(&self) -> bool {
170        matches!(
171            self,
172            Self::Refusal { .. }
173                | Self::LockConflict { .. }
174                | Self::NotReady { .. }
175                | Self::Stale { .. }
176                | Self::Declined { .. }
177                | Self::CrossRef { .. }
178        )
179    }
180}
181
182/// Which check found a preview stale (RFC 030 amendment A3).
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub enum StaleCause {
185    /// The change-token comparison, in `confirm` or `execute`: a branch or a tag, the queue, or — on
186    /// prikk ≥ 0.42 — prikk's current branch moved.
187    Repository,
188    /// Commit's worktree re-read: what prikk reports about the worktree — paths, their status, prikk's
189    /// verdict on them, or rename declarations — no longer matches what the preview listed. Refs, tags
190    /// and the queue may be exactly as they were.
191    Worktree,
192}
193
194impl fmt::Display for StikkError {
195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196        match self {
197            Self::Refusal { message }
198            | Self::LockConflict { message }
199            | Self::IntegrityFinding { message }
200            | Self::Limits { message }
201            | Self::CrossRef { message } => write!(f, "{}: {message}", self.class()),
202            Self::NotReady { detail } | Self::Internal { detail } | Self::Declined { detail } => {
203                write!(f, "{}: {detail}", self.class())
204            }
205            Self::Environment { detail, .. } => write!(f, "environment: {detail}"),
206            Self::Stale { operation, cause } => {
207                let what = match cause {
208                    StaleCause::Repository => "the repository",
209                    StaleCause::Worktree => "the worktree",
210                };
211                write!(f, "stale: {operation}'s preview no longer matches {what}")
212            }
213        }
214    }
215}
216
217impl std::error::Error for StikkError {
218    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
219        match self {
220            Self::Environment {
221                source: Some(cause),
222                ..
223            } => Some(cause.as_ref()),
224            _ => None,
225        }
226    }
227}
228
229#[cfg(test)]
230mod tests;