clm-kernel 0.0.12

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::fmt;
use thiserror::Error;

/// Core Domain Error Hierarchy for CLM Kernel.
///
/// Implements structured domain errors with explicit error codes,
/// domain categorizations, Satori/JSON-RPC serialization, and PTR Fiber failure modes.
#[derive(Error, Debug)]
pub enum ClmError {
    #[error("Storage error [{0:?}]: {1}")]
    Storage(StorageErrorCode, String),

    #[error("CPN VM error [{0:?}]: {1}")]
    Cpn(CpnErrorCode, String),

    #[error("Authentication error [{0:?}]: {1}")]
    Auth(AuthErrorCode, String),

    #[error("Transport error [{0:?}]: {1}")]
    Transport(TransportErrorCode, String),

    #[error("Evaluator error [{0:?}]: {1}")]
    Evaluator(EvaluatorErrorCode, String),

    #[error("Manifest error [{0:?}]: {1}")]
    Manifest(ManifestErrorCode, String),

    #[error("Crypto error [{0:?}]: {1}")]
    Crypto(CryptoErrorCode, String),

    #[error("CRDT error [{0:?}]: {1}")]
    Crdt(CrdtErrorCode, String),

    #[error("Evaluation error: {0}")]
    Evaluation(String),

    #[error("YAML parse error: {0}")]
    YamlParse(#[from] serde_yaml::Error),

    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[cfg(any(feature = "native", feature = "db"))]
    #[error("Database error: {0}")]
    Database(#[from] rusqlite::Error),
}

// ─────────────────────────────────────────────────────────────────────────────
// Domain Error Codes & Sub-Enums
// ─────────────────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum StorageErrorCode {
    CardNotFound = 1001,
    CorruptedContent = 1002,
    DatabaseUnavailable = 1003,
    TransactionFailed = 1004,
    SavepointFailed = 1005,
    InvalidSchemaVersion = 1006,
    QueryFailed = 1007,
}

impl fmt::Display for StorageErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}({})", self, *self as u32)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum CpnErrorCode {
    Deadlock = 2001,
    InvariantViolation = 2002,
    InvalidTransition = 2003,
    UnboundVariable = 2004,
    TokenMismatch = 2005,
    StateExplosion = 2006,
}

impl fmt::Display for CpnErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}({})", self, *self as u32)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum AuthErrorCode {
    InvalidDid = 3001,
    SignatureVerificationFailed = 3002,
    ExpiredToken = 3003,
    Unauthorized = 3004,
    KeyGenerationFailed = 3005,
    MalformedCredential = 3006,
}

impl fmt::Display for AuthErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}({})", self, *self as u32)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum TransportErrorCode {
    ConnectionRefused = 4001,
    HandshakeFailed = 4002,
    Timeout = 4003,
    TlsError = 4004,
    ChannelClosed = 4005,
    ProtocolViolation = 4006,
}

impl fmt::Display for TransportErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}({})", self, *self as u32)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum EvaluatorErrorCode {
    KernelPanic = 5001,
    DispatchNotFound = 5002,
    InvalidArguments = 5003,
    FiberFailure = 5004,
    PostconditionFailed = 5005,
    PreconditionFailed = 5006,
    SubprocessError = 5007,
}

impl fmt::Display for EvaluatorErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}({})", self, *self as u32)
    }
}

/// PTR Mathematical Fiber Failure Modes.
///
/// Models domain/codomain violations, identity unit collapse, and bottom executions (⊥).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub enum FiberError {
    DomainViolation(String),
    CodomainViolation(String),
    UnitViolation(String),
    BottomExecution(String),
}

impl fmt::Display for FiberError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FiberError::DomainViolation(s) => write!(f, "PTR Domain Violation: {}", s),
            FiberError::CodomainViolation(s) => write!(f, "PTR Codomain Violation: {}", s),
            FiberError::UnitViolation(s) => write!(f, "PTR Unit Law Violation: {}", s),
            FiberError::BottomExecution(s) => write!(f, "PTR Bottom Execution (⊥): {}", s),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum ManifestErrorCode {
    ParseFailed = 6001,
    MissingField = 6002,
    HashMismatch = 6003,
    CycleDetected = 6004,
    InvalidVersion = 6005,
}

impl fmt::Display for ManifestErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}({})", self, *self as u32)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum CryptoErrorCode {
    KeyDerivationFailed = 7001,
    DecryptionFailed = 7002,
    InvalidCiphertext = 7003,
    EntropyExhausted = 7004,
    KeyEncodingFailed = 7005,
}

impl fmt::Display for CryptoErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}({})", self, *self as u32)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum CrdtErrorCode {
    ClockDrift = 8001,
    ConcurrentConflict = 8002,
    MergeFailed = 8003,
    StateDivergence = 8004,
}

impl fmt::Display for CrdtErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}({})", self, *self as u32)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Methods & Helper Constructors
// ─────────────────────────────────────────────────────────────────────────────

impl ClmError {
    pub fn storage(code: StorageErrorCode, msg: impl Into<String>) -> Self {
        ClmError::Storage(code, msg.into())
    }

    pub fn cpn(code: CpnErrorCode, msg: impl Into<String>) -> Self {
        ClmError::Cpn(code, msg.into())
    }

    pub fn auth(code: AuthErrorCode, msg: impl Into<String>) -> Self {
        ClmError::Auth(code, msg.into())
    }

    pub fn transport(code: TransportErrorCode, msg: impl Into<String>) -> Self {
        ClmError::Transport(code, msg.into())
    }

    pub fn evaluator(code: EvaluatorErrorCode, msg: impl Into<String>) -> Self {
        ClmError::Evaluator(code, msg.into())
    }

    pub fn fiber(err: FiberError) -> Self {
        ClmError::Evaluator(EvaluatorErrorCode::FiberFailure, err.to_string())
    }

    pub fn manifest(code: ManifestErrorCode, msg: impl Into<String>) -> Self {
        ClmError::Manifest(code, msg.into())
    }

    pub fn crypto(code: CryptoErrorCode, msg: impl Into<String>) -> Self {
        ClmError::Crypto(code, msg.into())
    }

    pub fn crdt(code: CrdtErrorCode, msg: impl Into<String>) -> Self {
        ClmError::Crdt(code, msg.into())
    }

    /// Numeric error code for the error variant.
    pub fn code(&self) -> u32 {
        match self {
            ClmError::Storage(code, _) => *code as u32,
            ClmError::Cpn(code, _) => *code as u32,
            ClmError::Auth(code, _) => *code as u32,
            ClmError::Transport(code, _) => *code as u32,
            ClmError::Evaluator(code, _) => *code as u32,
            ClmError::Manifest(code, _) => *code as u32,
            ClmError::Crypto(code, _) => *code as u32,
            ClmError::Crdt(code, _) => *code as u32,
            ClmError::Evaluation(_) => 5000,
            ClmError::YamlParse(_) => 6000,
            ClmError::Json(_) => 6010,
            ClmError::Io(_) => 9000,
            #[cfg(any(feature = "native", feature = "db"))]
            ClmError::Database(_) => 1000,
        }
    }

    /// Canonical architectural domain category name.
    pub fn domain(&self) -> &'static str {
        match self {
            ClmError::Storage(..) => "STORAGE",
            ClmError::Cpn(..) => "CPN",
            ClmError::Auth(..) => "AUTH",
            ClmError::Transport(..) => "TRANSPORT",
            ClmError::Evaluator(..) | ClmError::Evaluation(..) => "EVALUATOR",
            ClmError::Manifest(..) | ClmError::YamlParse(..) | ClmError::Json(..) => "MANIFEST",
            ClmError::Crypto(..) => "CRYPTO",
            ClmError::Crdt(..) => "CRDT",
            ClmError::Io(..) => "IO",
            #[cfg(any(feature = "native", feature = "db"))]
            ClmError::Database(..) => "STORAGE",
        }
    }

    /// Maps errors to process exit codes.
    pub fn to_exit_code(&self) -> i32 {
        match self {
            ClmError::Evaluator(EvaluatorErrorCode::KernelPanic, _) => 101,
            ClmError::Evaluator(..) | ClmError::Evaluation(..) => 1,
            ClmError::Auth(..) => 2,
            ClmError::Storage(..) => 3,
            ClmError::Transport(..) => 4,
            ClmError::Cpn(..) => 5,
            ClmError::Manifest(..) => 6,
            _ => 1,
        }
    }

    /// Serializes error to a structured JSON-RPC / Satori protocol payload.
    pub fn to_payload(&self) -> serde_json::Value {
        serde_json::json!({
            "code": self.code(),
            "domain": self.domain(),
            "message": self.to_string(),
            "data": {
                "exit_code": self.to_exit_code(),
            }
        })
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Ergonomic Conversions
// ─────────────────────────────────────────────────────────────────────────────

impl From<String> for ClmError {
    fn from(err: String) -> Self {
        ClmError::Evaluation(err)
    }
}

impl From<&str> for ClmError {
    fn from(err: &str) -> Self {
        ClmError::Evaluation(err.to_string())
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Result Extension Trait for Context Annotation
// ─────────────────────────────────────────────────────────────────────────────

#[allow(dead_code)]
pub trait ResultExt<T> {
    fn context<C: fmt::Display>(self, context: C) -> Result<T>;
    fn with_context<C: fmt::Display, F: FnOnce() -> C>(self, f: F) -> Result<T>;
}

impl<T, E> ResultExt<T> for std::result::Result<T, E>
where
    E: Into<ClmError>,
{
    fn context<C: fmt::Display>(self, context: C) -> Result<T> {
        self.map_err(|e| {
            let clm_err = e.into();
            ClmError::Evaluation(format!("{}: {}", context, clm_err))
        })
    }

    fn with_context<C: fmt::Display, F: FnOnce() -> C>(self, f: F) -> Result<T> {
        self.map_err(|e| {
            let clm_err = e.into();
            ClmError::Evaluation(format!("{}: {}", f(), clm_err))
        })
    }
}

pub type Result<T> = std::result::Result<T, ClmError>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_code_and_domain() {
        let err = ClmError::storage(StorageErrorCode::CardNotFound, "Card not found: 0000");
        assert_eq!(err.code(), 1001);
        assert_eq!(err.domain(), "STORAGE");
        assert_eq!(err.to_exit_code(), 3);
    }

    #[test]
    fn test_fiber_error_construction() {
        let fiber_err = FiberError::DomainViolation("Input out of range [0, 1]".into());
        let err = ClmError::fiber(fiber_err);
        assert_eq!(err.code(), 5004);
        assert_eq!(err.domain(), "EVALUATOR");
        assert!(err.to_string().contains("PTR Domain Violation"));
    }

    #[test]
    fn test_satori_payload_serialization() {
        let err = ClmError::auth(AuthErrorCode::Unauthorized, "Missing bearer token");
        let payload = err.to_payload();
        assert_eq!(payload["code"], 3004);
        assert_eq!(payload["domain"], "AUTH");
        assert_eq!(payload["data"]["exit_code"], 2);
    }

    #[test]
    fn test_result_ext_context() {
        let res: std::result::Result<(), &str> = Err("underlying failure");
        let wrapped = res.context("Step 1 failed");
        assert!(wrapped.is_err());
        assert_eq!(
            wrapped.unwrap_err().to_string(),
            "Evaluation error: Step 1 failed: Evaluation error: underlying failure"
        );
    }
}