clm-kernel 0.0.15

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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use std::fmt;
use std::ops::Deref;
use serde::{Deserialize, Serialize};
use subtle::ConstantTimeEq;
use zeroize::{Zeroize, ZeroizeOnDrop};
use crate::error::{ClmError, StorageErrorCode, AuthErrorCode};

/// 64-character lowercase hexadecimal hash (BLAKE3 / SHA-256).
///
/// Operationalizes Function-Number Duality: MCards are content-addressed numbers.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ContentHash(String);

impl ContentHash {
    pub fn parse(s: impl AsRef<str>) -> Result<Self, ClmError> {
        let s = s.as_ref().trim();
        if s.len() != 64 {
            return Err(ClmError::storage(
                StorageErrorCode::CorruptedContent,
                format!("Invalid ContentHash length: expected 64 hex characters, found {}", s.len()),
            ));
        }
        if !s.chars().all(|c| c.is_ascii_hexdigit()) {
            return Err(ClmError::storage(
                StorageErrorCode::CorruptedContent,
                format!("Invalid ContentHash characters: must be valid hex digits, found '{}'", s),
            ));
        }
        Ok(Self(s.to_ascii_lowercase()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Computes the cryptographic hash over arbitrary bytes using the central hash provider (BLAKE3).
    pub fn compute(bytes: &[u8]) -> Self {
        Self(crate::hash::raw_hash_bytes(bytes))
    }
}

impl Deref for ContentHash {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl AsRef<str> for ContentHash {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ContentHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl fmt::Debug for ContentHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ContentHash({})", self.0)
    }
}

impl TryFrom<String> for ContentHash {
    type Error = ClmError;
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl TryFrom<&str> for ContentHash {
    type Error = ClmError;
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl ConstantTimeEq for ContentHash {
    fn ct_eq(&self, other: &Self) -> subtle::Choice {
        self.0.as_bytes().ct_eq(other.0.as_bytes())
    }
}

impl Serialize for ContentHash {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for ContentHash {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Self::parse(&s).map_err(serde::de::Error::custom)
    }
}

/// Decentralized Identifier (DID) representing an Agent Identity.
///
/// Follows W3C DID Core specification: `did:<method>:<method-specific-id>`.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct AgentDid(String);

impl AgentDid {
    pub fn parse(s: impl AsRef<str>) -> Result<Self, ClmError> {
        let s = s.as_ref().trim();
        if !s.starts_with("did:") {
            return Err(ClmError::auth(
                AuthErrorCode::InvalidDid,
                format!("Invalid AgentDid: must start with 'did:', found '{}'", s),
            ));
        }
        let parts: Vec<&str> = s.split(':').collect();
        if parts.len() < 3 || parts[1].is_empty() || parts[2].is_empty() {
            return Err(ClmError::auth(
                AuthErrorCode::InvalidDid,
                format!("Invalid AgentDid format: must contain method and identifier, found '{}'", s),
            ));
        }
        Ok(Self(s.to_string()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn method(&self) -> &str {
        self.0.split(':').nth(1).unwrap_or("")
    }

    pub fn new(did: impl AsRef<str>) -> Result<Self, ClmError> {
        Self::parse(did)
    }

    pub fn new_unchecked(s: impl Into<String>) -> Self {
        Self(s.into())
    }
}

impl Deref for AgentDid {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl AsRef<str> for AgentDid {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for AgentDid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl fmt::Debug for AgentDid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "AgentDid({})", self.0)
    }
}

impl TryFrom<String> for AgentDid {
    type Error = ClmError;
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl TryFrom<&str> for AgentDid {
    type Error = ClmError;
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl Serialize for AgentDid {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for AgentDid {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Self::parse(&s).map_err(serde::de::Error::custom)
    }
}

/// MCard Handle Indirection Name.
///
/// Follows slug pattern `mcard:<category>/...` or `@namespace/name`.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Handle(String);

impl Handle {
    pub fn parse(s: impl AsRef<str>) -> Result<Self, ClmError> {
        let s = s.as_ref().trim();
        if s.is_empty() {
            return Err(ClmError::storage(
                StorageErrorCode::CardNotFound,
                "Handle cannot be empty",
            ));
        }
        if s.contains(' ') || s.contains('\t') || s.contains('\n') {
            return Err(ClmError::storage(
                StorageErrorCode::CorruptedContent,
                format!("Handle cannot contain whitespace: '{}'", s),
            ));
        }
        Ok(Self(s.to_string()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Deref for Handle {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl AsRef<str> for Handle {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for Handle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl fmt::Debug for Handle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Handle({})", self.0)
    }
}

impl TryFrom<String> for Handle {
    type Error = ClmError;
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl TryFrom<&str> for Handle {
    type Error = ClmError;
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl Serialize for Handle {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for Handle {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Self::parse(&s).map_err(serde::de::Error::custom)
    }
}

/// Petri Net Place Identifier.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PlaceId(pub String);

impl fmt::Display for PlaceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl fmt::Debug for PlaceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "PlaceId({})", self.0)
    }
}

/// Petri Net Transition Identifier.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct TransitionId(pub String);

impl fmt::Display for TransitionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl fmt::Debug for TransitionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "TransitionId({})", self.0)
    }
}

/// State Token Marking Hash.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct MarkingHash(pub String);

impl fmt::Display for MarkingHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl fmt::Debug for MarkingHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MarkingHash({})", self.0)
    }
}

/// Zeroize-on-drop Cryptographic Secret Key Buffer.
///
/// Prevents private keys from lingering in memory or appearing in debug traces.
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct SecretKeyBytes(pub Vec<u8>);

impl SecretKeyBytes {
    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
        Self(bytes.into())
    }

    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }
}

impl fmt::Debug for SecretKeyBytes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[REDACTED SECRET KEY]")
    }
}

impl fmt::Display for SecretKeyBytes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[REDACTED SECRET KEY]")
    }
}

/// Validated SQLite Savepoint Identifier.
///
/// Guarantees alphanumeric + underscore characters, preventing SQL injection
/// during zero-copy transactional rollbacks in Cordis fibers.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SavepointToken(String);

impl SavepointToken {
    /// Generates a unique, sanitized savepoint identifier with the given prefix.
    pub fn generate(prefix: &str) -> Self {
        let clean_prefix: String = prefix
            .chars()
            .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
            .collect();
        let id = uuid::Uuid::new_v4().simple().to_string();
        let short_id = if id.len() >= 12 { &id[..12] } else { &id };
        Self(format!("clm_sp_{}_{}", clean_prefix, short_id))
    }

    /// Parses and validates a savepoint identifier string.
    pub fn parse(s: &str) -> Result<Self, ClmError> {
        if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') && s.starts_with("clm_sp_") {
            Ok(Self(s.to_string()))
        } else {
            Err(ClmError::storage(
                StorageErrorCode::SavepointFailed,
                format!("Invalid savepoint token identifier: {}", s),
            ))
        }
    }

    /// Returns the raw identifier as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for SavepointToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Deref for SavepointToken {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

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

    #[test]
    fn test_content_hash_validation() {
        let valid = "2f9acb02faa121bb2a3621951f57b4c690655337edee2e5ac350be2b3be88ea8";
        let hash = ContentHash::parse(valid).expect("Valid hash should parse");
        assert_eq!(hash.as_str(), valid);

        // Invalid length
        assert!(ContentHash::parse("short_hash").is_err());
        // Invalid non-hex characters
        assert!(ContentHash::parse("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz").is_err());
    }

    #[test]
    fn test_content_hash_constant_time_equality() {
        let a = ContentHash::parse("2f9acb02faa121bb2a3621951f57b4c690655337edee2e5ac350be2b3be88ea8").unwrap();
        let b = ContentHash::parse("2f9acb02faa121bb2a3621951f57b4c690655337edee2e5ac350be2b3be88ea8").unwrap();
        let c = ContentHash::parse("0000000000000000000000000000000000000000000000000000000000000000").unwrap();

        assert_eq!(a.ct_eq(&b).unwrap_u8(), 1);
        assert_eq!(a.ct_eq(&c).unwrap_u8(), 0);
    }

    #[test]
    fn test_agent_did_validation() {
        let valid = "did:pkc:ca:darwin:root-agent";
        let did = AgentDid::parse(valid).expect("Valid DID should parse");
        assert_eq!(did.as_str(), valid);
        assert_eq!(did.method(), "pkc");

        assert!(AgentDid::parse("not_a_did").is_err());
        assert!(AgentDid::parse("did:").is_err());
    }

    #[test]
    fn test_handle_validation() {
        let valid = "mcard:token/dca/1234";
        let handle = Handle::parse(valid).expect("Valid handle should parse");
        assert_eq!(handle.as_str(), valid);

        assert!(Handle::parse("").is_err());
        assert!(Handle::parse("invalid handle with spaces").is_err());
    }

    #[test]
    fn test_secret_key_bytes_redaction() {
        let secret = SecretKeyBytes::new(vec![1, 2, 3, 4, 5]);
        let debug_str = format!("{:?}", secret);
        assert_eq!(debug_str, "[REDACTED SECRET KEY]");
        assert_eq!(secret.as_bytes(), &[1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_savepoint_token_generation_and_validation() {
        let token = SavepointToken::generate("eval_fiber");
        assert!(token.as_str().starts_with("clm_sp_eval_fiber_"));
        assert!(SavepointToken::parse(token.as_str()).is_ok());

        // Injection attempt with quotes or semicolons
        assert!(SavepointToken::parse("clm_sp_test; DROP TABLE card;--").is_err());
        assert!(SavepointToken::parse("malicious_no_prefix").is_err());
    }
}