Skip to main content

clm_rust_core/
error.rs

1use std::fmt;
2use thiserror::Error;
3
4/// Core Domain Error Hierarchy for CLM Kernel.
5///
6/// Implements structured domain errors with explicit error codes,
7/// domain categorizations, Satori/JSON-RPC serialization, and PTR Fiber failure modes.
8#[derive(Error, Debug)]
9pub enum ClmError {
10    #[error("Storage error [{0:?}]: {1}")]
11    Storage(StorageErrorCode, String),
12
13    #[error("CPN VM error [{0:?}]: {1}")]
14    Cpn(CpnErrorCode, String),
15
16    #[error("Authentication error [{0:?}]: {1}")]
17    Auth(AuthErrorCode, String),
18
19    #[error("Transport error [{0:?}]: {1}")]
20    Transport(TransportErrorCode, String),
21
22    #[error("Evaluator error [{0:?}]: {1}")]
23    Evaluator(EvaluatorErrorCode, String),
24
25    #[error("Manifest error [{0:?}]: {1}")]
26    Manifest(ManifestErrorCode, String),
27
28    #[error("Crypto error [{0:?}]: {1}")]
29    Crypto(CryptoErrorCode, String),
30
31    #[error("CRDT error [{0:?}]: {1}")]
32    Crdt(CrdtErrorCode, String),
33
34    #[error("Evaluation error: {0}")]
35    Evaluation(String),
36
37    #[error("YAML parse error: {0}")]
38    YamlParse(#[from] serde_yaml::Error),
39
40    #[error("JSON error: {0}")]
41    Json(#[from] serde_json::Error),
42
43    #[error("IO error: {0}")]
44    Io(#[from] std::io::Error),
45
46    #[cfg(any(feature = "native", feature = "db"))]
47    #[error("Database error: {0}")]
48    Database(#[from] rusqlite::Error),
49}
50
51// ─────────────────────────────────────────────────────────────────────────────
52// Domain Error Codes & Sub-Enums
53// ─────────────────────────────────────────────────────────────────────────────
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
56#[repr(u32)]
57pub enum StorageErrorCode {
58    CardNotFound = 1001,
59    CorruptedContent = 1002,
60    DatabaseUnavailable = 1003,
61    TransactionFailed = 1004,
62    SavepointFailed = 1005,
63    InvalidSchemaVersion = 1006,
64    QueryFailed = 1007,
65}
66
67impl fmt::Display for StorageErrorCode {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        write!(f, "{:?}({})", self, *self as u32)
70    }
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
74#[repr(u32)]
75pub enum CpnErrorCode {
76    Deadlock = 2001,
77    InvariantViolation = 2002,
78    InvalidTransition = 2003,
79    UnboundVariable = 2004,
80    TokenMismatch = 2005,
81    StateExplosion = 2006,
82}
83
84impl fmt::Display for CpnErrorCode {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        write!(f, "{:?}({})", self, *self as u32)
87    }
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
91#[repr(u32)]
92pub enum AuthErrorCode {
93    InvalidDid = 3001,
94    SignatureVerificationFailed = 3002,
95    ExpiredToken = 3003,
96    Unauthorized = 3004,
97    KeyGenerationFailed = 3005,
98    MalformedCredential = 3006,
99}
100
101impl fmt::Display for AuthErrorCode {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        write!(f, "{:?}({})", self, *self as u32)
104    }
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
108#[repr(u32)]
109pub enum TransportErrorCode {
110    ConnectionRefused = 4001,
111    HandshakeFailed = 4002,
112    Timeout = 4003,
113    TlsError = 4004,
114    ChannelClosed = 4005,
115    ProtocolViolation = 4006,
116}
117
118impl fmt::Display for TransportErrorCode {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        write!(f, "{:?}({})", self, *self as u32)
121    }
122}
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
125#[repr(u32)]
126pub enum EvaluatorErrorCode {
127    KernelPanic = 5001,
128    DispatchNotFound = 5002,
129    InvalidArguments = 5003,
130    FiberFailure = 5004,
131    PostconditionFailed = 5005,
132    PreconditionFailed = 5006,
133    SubprocessError = 5007,
134}
135
136impl fmt::Display for EvaluatorErrorCode {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        write!(f, "{:?}({})", self, *self as u32)
139    }
140}
141
142/// PTR Mathematical Fiber Failure Modes.
143///
144/// Models domain/codomain violations, identity unit collapse, and bottom executions (⊥).
145#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
146pub enum FiberError {
147    DomainViolation(String),
148    CodomainViolation(String),
149    UnitViolation(String),
150    BottomExecution(String),
151}
152
153impl fmt::Display for FiberError {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        match self {
156            FiberError::DomainViolation(s) => write!(f, "PTR Domain Violation: {}", s),
157            FiberError::CodomainViolation(s) => write!(f, "PTR Codomain Violation: {}", s),
158            FiberError::UnitViolation(s) => write!(f, "PTR Unit Law Violation: {}", s),
159            FiberError::BottomExecution(s) => write!(f, "PTR Bottom Execution (⊥): {}", s),
160        }
161    }
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
165#[repr(u32)]
166pub enum ManifestErrorCode {
167    ParseFailed = 6001,
168    MissingField = 6002,
169    HashMismatch = 6003,
170    CycleDetected = 6004,
171    InvalidVersion = 6005,
172}
173
174impl fmt::Display for ManifestErrorCode {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        write!(f, "{:?}({})", self, *self as u32)
177    }
178}
179
180#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
181#[repr(u32)]
182pub enum CryptoErrorCode {
183    KeyDerivationFailed = 7001,
184    DecryptionFailed = 7002,
185    InvalidCiphertext = 7003,
186    EntropyExhausted = 7004,
187    KeyEncodingFailed = 7005,
188}
189
190impl fmt::Display for CryptoErrorCode {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        write!(f, "{:?}({})", self, *self as u32)
193    }
194}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
197#[repr(u32)]
198pub enum CrdtErrorCode {
199    ClockDrift = 8001,
200    ConcurrentConflict = 8002,
201    MergeFailed = 8003,
202    StateDivergence = 8004,
203}
204
205impl fmt::Display for CrdtErrorCode {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        write!(f, "{:?}({})", self, *self as u32)
208    }
209}
210
211// ─────────────────────────────────────────────────────────────────────────────
212// Methods & Helper Constructors
213// ─────────────────────────────────────────────────────────────────────────────
214
215impl ClmError {
216    pub fn storage(code: StorageErrorCode, msg: impl Into<String>) -> Self {
217        ClmError::Storage(code, msg.into())
218    }
219
220    pub fn cpn(code: CpnErrorCode, msg: impl Into<String>) -> Self {
221        ClmError::Cpn(code, msg.into())
222    }
223
224    pub fn auth(code: AuthErrorCode, msg: impl Into<String>) -> Self {
225        ClmError::Auth(code, msg.into())
226    }
227
228    pub fn transport(code: TransportErrorCode, msg: impl Into<String>) -> Self {
229        ClmError::Transport(code, msg.into())
230    }
231
232    pub fn evaluator(code: EvaluatorErrorCode, msg: impl Into<String>) -> Self {
233        ClmError::Evaluator(code, msg.into())
234    }
235
236    pub fn fiber(err: FiberError) -> Self {
237        ClmError::Evaluator(EvaluatorErrorCode::FiberFailure, err.to_string())
238    }
239
240    pub fn manifest(code: ManifestErrorCode, msg: impl Into<String>) -> Self {
241        ClmError::Manifest(code, msg.into())
242    }
243
244    pub fn crypto(code: CryptoErrorCode, msg: impl Into<String>) -> Self {
245        ClmError::Crypto(code, msg.into())
246    }
247
248    pub fn crdt(code: CrdtErrorCode, msg: impl Into<String>) -> Self {
249        ClmError::Crdt(code, msg.into())
250    }
251
252    /// Numeric error code for the error variant.
253    pub fn code(&self) -> u32 {
254        match self {
255            ClmError::Storage(code, _) => *code as u32,
256            ClmError::Cpn(code, _) => *code as u32,
257            ClmError::Auth(code, _) => *code as u32,
258            ClmError::Transport(code, _) => *code as u32,
259            ClmError::Evaluator(code, _) => *code as u32,
260            ClmError::Manifest(code, _) => *code as u32,
261            ClmError::Crypto(code, _) => *code as u32,
262            ClmError::Crdt(code, _) => *code as u32,
263            ClmError::Evaluation(_) => 5000,
264            ClmError::YamlParse(_) => 6000,
265            ClmError::Json(_) => 6010,
266            ClmError::Io(_) => 9000,
267            #[cfg(any(feature = "native", feature = "db"))]
268            ClmError::Database(_) => 1000,
269        }
270    }
271
272    /// Canonical architectural domain category name.
273    pub fn domain(&self) -> &'static str {
274        match self {
275            ClmError::Storage(..) => "STORAGE",
276            ClmError::Cpn(..) => "CPN",
277            ClmError::Auth(..) => "AUTH",
278            ClmError::Transport(..) => "TRANSPORT",
279            ClmError::Evaluator(..) | ClmError::Evaluation(..) => "EVALUATOR",
280            ClmError::Manifest(..) | ClmError::YamlParse(..) | ClmError::Json(..) => "MANIFEST",
281            ClmError::Crypto(..) => "CRYPTO",
282            ClmError::Crdt(..) => "CRDT",
283            ClmError::Io(..) => "IO",
284            #[cfg(any(feature = "native", feature = "db"))]
285            ClmError::Database(..) => "STORAGE",
286        }
287    }
288
289    /// Maps errors to process exit codes.
290    pub fn to_exit_code(&self) -> i32 {
291        match self {
292            ClmError::Evaluator(EvaluatorErrorCode::KernelPanic, _) => 101,
293            ClmError::Evaluator(..) | ClmError::Evaluation(..) => 1,
294            ClmError::Auth(..) => 2,
295            ClmError::Storage(..) => 3,
296            ClmError::Transport(..) => 4,
297            ClmError::Cpn(..) => 5,
298            ClmError::Manifest(..) => 6,
299            _ => 1,
300        }
301    }
302
303    /// Serializes error to a structured JSON-RPC / Satori protocol payload.
304    pub fn to_payload(&self) -> serde_json::Value {
305        serde_json::json!({
306            "code": self.code(),
307            "domain": self.domain(),
308            "message": self.to_string(),
309            "data": {
310                "exit_code": self.to_exit_code(),
311            }
312        })
313    }
314}
315
316// ─────────────────────────────────────────────────────────────────────────────
317// Ergonomic Conversions
318// ─────────────────────────────────────────────────────────────────────────────
319
320impl From<String> for ClmError {
321    fn from(err: String) -> Self {
322        ClmError::Evaluation(err)
323    }
324}
325
326impl From<&str> for ClmError {
327    fn from(err: &str) -> Self {
328        ClmError::Evaluation(err.to_string())
329    }
330}
331
332// ─────────────────────────────────────────────────────────────────────────────
333// Result Extension Trait for Context Annotation
334// ─────────────────────────────────────────────────────────────────────────────
335
336#[allow(dead_code)]
337pub trait ResultExt<T> {
338    fn context<C: fmt::Display>(self, context: C) -> Result<T>;
339    fn with_context<C: fmt::Display, F: FnOnce() -> C>(self, f: F) -> Result<T>;
340}
341
342impl<T, E> ResultExt<T> for std::result::Result<T, E>
343where
344    E: Into<ClmError>,
345{
346    fn context<C: fmt::Display>(self, context: C) -> Result<T> {
347        self.map_err(|e| {
348            let clm_err = e.into();
349            ClmError::Evaluation(format!("{}: {}", context, clm_err))
350        })
351    }
352
353    fn with_context<C: fmt::Display, F: FnOnce() -> C>(self, f: F) -> Result<T> {
354        self.map_err(|e| {
355            let clm_err = e.into();
356            ClmError::Evaluation(format!("{}: {}", f(), clm_err))
357        })
358    }
359}
360
361pub type Result<T> = std::result::Result<T, ClmError>;
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    #[test]
368    fn test_error_code_and_domain() {
369        let err = ClmError::storage(StorageErrorCode::CardNotFound, "Card not found: 0000");
370        assert_eq!(err.code(), 1001);
371        assert_eq!(err.domain(), "STORAGE");
372        assert_eq!(err.to_exit_code(), 3);
373    }
374
375    #[test]
376    fn test_fiber_error_construction() {
377        let fiber_err = FiberError::DomainViolation("Input out of range [0, 1]".into());
378        let err = ClmError::fiber(fiber_err);
379        assert_eq!(err.code(), 5004);
380        assert_eq!(err.domain(), "EVALUATOR");
381        assert!(err.to_string().contains("PTR Domain Violation"));
382    }
383
384    #[test]
385    fn test_satori_payload_serialization() {
386        let err = ClmError::auth(AuthErrorCode::Unauthorized, "Missing bearer token");
387        let payload = err.to_payload();
388        assert_eq!(payload["code"], 3004);
389        assert_eq!(payload["domain"], "AUTH");
390        assert_eq!(payload["data"]["exit_code"], 2);
391    }
392
393    #[test]
394    fn test_result_ext_context() {
395        let res: std::result::Result<(), &str> = Err("underlying failure");
396        let wrapped = res.context("Step 1 failed");
397        assert!(wrapped.is_err());
398        assert_eq!(
399            wrapped.unwrap_err().to_string(),
400            "Evaluation error: Step 1 failed: Evaluation error: underlying failure"
401        );
402    }
403}