clm-kernel 0.0.16

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
//! Universal Structured Return Type (TypedValue).
//!
//! Sprint 454 / Invariant INV-454-01.
//! Every evaluator return, speech act, and agentic message is expressible as a
//! machine-verifiable TypedValue — a JSON-serializable algebraic type carrying
//! its MIME type, universe level, optional schema reference, the data payload,
//! and a content hash for integrity verification.

use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

/// Valid universe levels in the CLM Type Lattice.
pub const VALID_UNIVERSES: [&str; 6] = ["U0", "U1", "U2", "U3", "U4", "U5"];

/// Human-readable names for universe levels.
pub fn universe_name(universe: &str) -> &'static str {
    match universe {
        "U0" => "Kenotic Core",
        "U1" => "Petri Net VM",
        "U2" => "Storage Substrate",
        "U3" => "Dialectic Mesh",
        "U4" => "Interaction Membrane",
        "U5" => "Cognition Loop Gamma",
        _ => "Unknown",
    }
}

/// Errors raised when a TypedValue fails validation or construction.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum TypedValueError {
    #[error("Invalid universe '{0}'; must be one of [\"U0\", \"U1\", \"U2\", \"U3\", \"U4\", \"U5\"]")]
    InvalidUniverse(String),

    #[error("MIME type must be a non-empty string")]
    EmptyMime,

    #[error("Content hash mismatch: expected {expected}, computed {computed}")]
    ContentHashMismatch { expected: String, computed: String },

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

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

    #[error("Cannot lift from {from} to {to}; target must be strictly higher")]
    InvalidLift { from: String, to: String },
}

/// Universal structured return type for the CLM evaluator pipeline.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TypedValue {
    pub mime: String,
    pub universe: String,
    pub data: Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schema_ref: Option<String>,
    pub content_hash: String,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub metadata: BTreeMap<String, Value>,
}

/// Computes BLAKE3 digest of the canonical JSON representation of data.
pub fn compute_content_hash(data: &Value) -> String {
    let bytes = match data {
        Value::String(s) => s.as_bytes().to_vec(),
        other => match crate::layer0::codec::canonical_json(other) {
            Ok(json_str) => json_str.into_bytes(),
            Err(_) => other.to_string().into_bytes(),
        },
    };
    crate::layer0::hash::compute_blake3(&bytes)
}

impl TypedValue {
    /// Constructs and validates a new TypedValue.
    pub fn new(
        mime: impl Into<String>,
        universe: impl Into<String>,
        data: Value,
        schema_ref: Option<String>,
        metadata: Option<BTreeMap<String, Value>>,
    ) -> Result<Self, TypedValueError> {
        let mime = mime.into();
        let universe = universe.into();

        if !VALID_UNIVERSES.contains(&universe.as_str()) {
            return Err(TypedValueError::InvalidUniverse(universe));
        }

        if mime.trim().is_empty() {
            return Err(TypedValueError::EmptyMime);
        }

        let content_hash = compute_content_hash(&data);
        let metadata = metadata.unwrap_or_default();

        Ok(Self {
            mime,
            universe,
            data,
            schema_ref,
            content_hash,
            metadata,
        })
    }

    /// Convenience constructor from raw components with auto-computed content_hash.
    pub fn from_data(
        mime: impl Into<String>,
        universe: impl Into<String>,
        data: Value,
    ) -> Result<Self, TypedValueError> {
        Self::new(mime, universe, data, None, None)
    }

    /// Convenience factory for text/plain TypedValue.
    pub fn text(content: &str, universe: &str) -> Result<Self, TypedValueError> {
        Self::from_data("text/plain", universe, Value::String(content.to_string()))
    }

    /// Convenience factory for application/json TypedValue.
    pub fn json_value(
        data: Value,
        universe: &str,
        schema_ref: Option<String>,
    ) -> Result<Self, TypedValueError> {
        Self::new("application/json", universe, data, schema_ref, None)
    }

    /// Convenience factory for binary TypedValue (hex encoded in data).
    pub fn binary(
        data: &[u8],
        mime: Option<&str>,
        universe: Option<&str>,
    ) -> Result<Self, TypedValueError> {
        let mime = mime.unwrap_or("application/octet-stream");
        let universe = universe.unwrap_or("U0");
        let mut metadata = BTreeMap::new();
        metadata.insert("_encoding".to_string(), Value::String("hex".to_string()));

        Self::new(
            mime,
            universe,
            Value::String(hex::encode(data)),
            None,
            Some(metadata),
        )
    }

    /// Numeric universe level (0..=5).
    pub fn universe_level(&self) -> u8 {
        if self.universe.len() == 2 && self.universe.starts_with('U') {
            self.universe[1..2].parse::<u8>().unwrap_or(0)
        } else {
            0
        }
    }

    /// Human-readable universe name.
    pub fn universe_name(&self) -> &'static str {
        universe_name(&self.universe)
    }

    /// Lifts the TypedValue strictly upward to a higher universe stratum.
    pub fn lift(&self, target_universe: &str) -> Result<Self, TypedValueError> {
        if !VALID_UNIVERSES.contains(&target_universe) {
            return Err(TypedValueError::InvalidUniverse(target_universe.to_string()));
        }

        let target_level = target_universe[1..2].parse::<u8>().unwrap_or(0);
        let current_level = self.universe_level();

        if target_level <= current_level {
            return Err(TypedValueError::InvalidLift {
                from: self.universe.clone(),
                to: target_universe.to_string(),
            });
        }

        let mut new_meta = self.metadata.clone();
        new_meta.insert(
            "_lifted_from".to_string(),
            Value::String(self.universe.clone()),
        );

        Ok(Self {
            mime: self.mime.clone(),
            universe: target_universe.to_string(),
            data: self.data.clone(),
            schema_ref: self.schema_ref.clone(),
            content_hash: self.content_hash.clone(),
            metadata: new_meta,
        })
    }

    /// Validates the structural integrity and content hash of this TypedValue.
    pub fn validate(&self) -> Result<(), TypedValueError> {
        if !VALID_UNIVERSES.contains(&self.universe.as_str()) {
            return Err(TypedValueError::InvalidUniverse(self.universe.clone()));
        }
        if self.mime.trim().is_empty() {
            return Err(TypedValueError::EmptyMime);
        }
        let computed = compute_content_hash(&self.data);
        if self.content_hash != computed {
            return Err(TypedValueError::ContentHashMismatch {
                expected: self.content_hash.clone(),
                computed,
            });
        }
        Ok(())
    }

    /// Non-raising integrity check.
    pub fn verify_integrity(&self) -> bool {
        self.validate().is_ok()
    }

    /// Serializes to RFC 8785 canonical JSON string.
    pub fn to_json(&self) -> Result<String, TypedValueError> {
        crate::layer0::codec::canonical_json(self)
            .map_err(TypedValueError::SerializationError)
    }

    /// Deserializes from a JSON string and verifies content_hash integrity.
    pub fn from_json(s: &str) -> Result<Self, TypedValueError> {
        let val: Value = serde_json::from_str(s)
            .map_err(|e| TypedValueError::DeserializationError(e.to_string()))?;

        let obj = val.as_object().ok_or_else(|| {
            TypedValueError::DeserializationError("TypedValue JSON must be an object".to_string())
        })?;

        let mime = obj
            .get("mime")
            .and_then(|v| v.as_str())
            .ok_or_else(|| TypedValueError::DeserializationError("Missing 'mime'".to_string()))?
            .to_string();

        let universe = obj
            .get("universe")
            .and_then(|v| v.as_str())
            .unwrap_or("U0")
            .to_string();

        let data = obj
            .get("data")
            .cloned()
            .unwrap_or(Value::Null);

        let schema_ref = obj
            .get("schema_ref")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let stored_hash = obj
            .get("content_hash")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        let metadata = match obj.get("metadata") {
            Some(Value::Object(map)) => {
                let mut btree = BTreeMap::new();
                for (k, v) in map {
                    btree.insert(k.clone(), v.clone());
                }
                btree
            }
            _ => BTreeMap::new(),
        };

        let tv = Self::new(mime, universe, data, schema_ref, Some(metadata))?;

        if !stored_hash.is_empty() && tv.content_hash != stored_hash {
            return Err(TypedValueError::ContentHashMismatch {
                expected: stored_hash,
                computed: tv.content_hash,
            });
        }

        Ok(tv)
    }
}

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

    #[test]
    fn test_create_text_typed_value() {
        let tv = TypedValue::text("hello world", "U0").expect("should create");
        assert_eq!(tv.mime, "text/plain");
        assert_eq!(tv.universe, "U0");
        assert_eq!(tv.data, Value::String("hello world".to_string()));
        assert_eq!(tv.content_hash.len(), 64);
    }

    #[test]
    fn test_create_json_typed_value() {
        let payload = json!({"key": "value", "count": 42});
        let tv = TypedValue::json_value(payload.clone(), "U3", None).expect("should create");
        assert_eq!(tv.mime, "application/json");
        assert_eq!(tv.universe, "U3");
        assert_eq!(tv.data, payload);
        assert_eq!(tv.content_hash.len(), 64);
    }

    #[test]
    fn test_content_hash_deterministic() {
        let tv1 = TypedValue::text("same data", "U0").unwrap();
        let tv2 = TypedValue::text("same data", "U0").unwrap();
        assert_eq!(tv1.content_hash, tv2.content_hash);
    }

    #[test]
    fn test_different_data_different_hash() {
        let tv1 = TypedValue::text("data A", "U0").unwrap();
        let tv2 = TypedValue::text("data B", "U0").unwrap();
        assert_ne!(tv1.content_hash, tv2.content_hash);
    }

    #[test]
    fn test_invalid_universe_rejected() {
        let res = TypedValue::text("foo", "U9");
        assert!(res.is_err());
    }

    #[test]
    fn test_empty_mime_rejected() {
        let res = TypedValue::from_data("", "U0", json!("foo"));
        assert!(res.is_err());
    }

    #[test]
    fn test_roundtrip_json() {
        let payload = json!({"nested": {"value": 42}});
        let mut meta = BTreeMap::new();
        meta.insert("tag".to_string(), Value::String("roundtrip".to_string()));

        let tv = TypedValue::new(
            "application/json",
            "U3",
            payload,
            Some("test.schema.json".to_string()),
            Some(meta),
        )
        .unwrap();

        let json_str = tv.to_json().expect("to_json failed");
        let restored = TypedValue::from_json(&json_str).expect("from_json failed");

        assert_eq!(restored.mime, tv.mime);
        assert_eq!(restored.universe, tv.universe);
        assert_eq!(restored.data, tv.data);
        assert_eq!(restored.schema_ref, tv.schema_ref);
        assert_eq!(restored.content_hash, tv.content_hash);
        assert_eq!(restored.metadata, tv.metadata);
    }

    #[test]
    fn test_tampered_hash_rejected() {
        let tv = TypedValue::text("original", "U0").unwrap();
        let mut json_obj: serde_json::Map<String, Value> =
            serde_json::from_str(&tv.to_json().unwrap()).unwrap();
        json_obj.insert(
            "content_hash".to_string(),
            Value::String("0".repeat(64)),
        );
        let tampered_str = serde_json::to_string(&json_obj).unwrap();
        assert!(TypedValue::from_json(&tampered_str).is_err());
    }

    #[test]
    fn test_lift_universe() {
        let tv = TypedValue::text("lift me", "U1").unwrap();
        let lifted = tv.lift("U3").expect("lifting U1 -> U3 must succeed");
        assert_eq!(lifted.universe, "U3");
        assert_eq!(lifted.universe_level(), 3);
        assert_eq!(
            lifted.metadata.get("_lifted_from").unwrap().as_str().unwrap(),
            "U1"
        );

        // Downward or same lifting must fail
        assert!(tv.lift("U0").is_err());
        assert!(tv.lift("U1").is_err());
    }

    #[test]
    fn test_binary_creation() {
        let bytes = b"binary payload\x00\xff";
        let tv = TypedValue::binary(bytes, None, None).unwrap();
        assert_eq!(tv.mime, "application/octet-stream");
        assert_eq!(tv.universe, "U0");
        assert_eq!(
            tv.metadata.get("_encoding").unwrap().as_str().unwrap(),
            "hex"
        );
        assert_eq!(tv.data.as_str().unwrap(), hex::encode(bytes));
        assert!(tv.verify_integrity());
    }
}