clm-kernel 0.0.22

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
//! Layer 1 All-MCard Token Ontology & Cordis Function-Number Duality (Sprint 507).
//!
//! Implements the All-MCard Petri Net Triad where every Petri Net element is an
//! immutable content-addressed `MCardRecord` (`card(hash, content, g_time)`):
//! - `TokenMCard`: Value MCard <-> Cordis `PrimitivePCard` (`1 -> X`)
//! - `PlaceMCard`: Guard MCard <-> Type Lattice `BooleanPCard` (`X -> 2`)
//! - `TransitionMCard`: Operator MCard <-> Cordis `DynamicPCard` (`A -> B`) with `CordisCoeffects`
//! - `NetMCard`: Valk's Object Petri Nets (Nets-Within-Nets) serialized as a `TokenMCard`

use crate::layer0::vocabulary::{DETERMINISTIC_EPOCH_TOKEN, HANDLE_MCARD_HASH_2, URI_SCHEME_MCARD};
#[allow(unused_imports)]
use std::collections::BTreeMap;
use std::sync::OnceLock;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::domain::{
    to_canonical_json_bytes, BailVerdict, BooleanPCard, CordisCoeffects,
    InvariantPhase, MCard, MCardPayload, PrimitivePCard,
};
use crate::layer0::mcard_record::{verify_record, MCardRecord, RecordVerification};
#[allow(unused_imports)]
use crate::types::{AgentDid, ContentHash};

/// Default canonical ISO-8601 timestamp for deterministic Layer 1 MCard minting.
pub const DEFAULT_TIMESTAMP: &str = DETERMINISTIC_EPOCH_TOKEN;
/// Default canonical locale tag for `g_time`.
pub const DEFAULT_LOCALE: &str = "UTC";

/// Transparent lazy cache for qualified `algorithm:hex` references.
#[derive(Default)]
pub struct MemoizedQualifiedRef(OnceLock<String>);

impl MemoizedQualifiedRef {
    #[inline]
    pub fn get_or_init<F: FnOnce() -> String>(&self, f: F) -> &str {
        self.0.get_or_init(f).as_str()
    }
}

impl std::fmt::Debug for MemoizedQualifiedRef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("MemoizedQualifiedRef").field(&self.0.get()).finish()
    }
}

impl Clone for MemoizedQualifiedRef {
    fn clone(&self) -> Self {
        let lock = OnceLock::new();
        if let Some(val) = self.0.get() {
            let _ = lock.set(val.clone());
        }
        Self(lock)
    }
}

impl PartialEq for MemoizedQualifiedRef {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for MemoizedQualifiedRef {}

impl PartialOrd for MemoizedQualifiedRef {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for MemoizedQualifiedRef {
    fn cmp(&self, _other: &Self) -> std::cmp::Ordering {
        std::cmp::Ordering::Equal
    }
}

impl std::hash::Hash for MemoizedQualifiedRef {
    fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
}

/// Creates a deterministic `MCardRecord` from a `serde_json::Value` serialized as canonical JSON.
pub fn record_from_canonical_json(
    envelope: &Value,
    algorithm: Option<&str>,
    timestamp: Option<&str>,
) -> Result<MCardRecord, String> {
    let algo = algorithm.unwrap_or(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3).trim().trim_end_matches(':').to_lowercase();
    let ts = timestamp.unwrap_or(DEFAULT_TIMESTAMP);
    let bytes = to_canonical_json_bytes(envelope);
    MCardRecord::create_at(&bytes, Some(&algo), Some(ts), DEFAULT_LOCALE)
}

pub fn record_algorithm(record: &MCardRecord) -> Result<String, String> {
    match verify_record(record) {
        RecordVerification::DeclaredOk { algorithm } => Ok(algorithm),
        verdict => Err(format!("unverified MCard reference: {verdict:?}")),
    }
}

pub fn qualified_record_hash(record: &MCardRecord) -> Result<String, String> {
    let algorithm = record_algorithm(record)?;
    let raw = record.hash.split_once(':').map_or(record.hash.as_str(), |(_, hash)| hash);
    Ok(format!("{algorithm}:{raw}"))
}

pub fn verify_envelope<T: Serialize>(record: &MCardRecord, model: &T, kind: &str) -> bool {
    if record_algorithm(record).is_err() { return false; }
    let Ok(mut view) = model_fields(model) else { return false; };
    view.insert("kind".into(), Value::String(kind.into()));
    serde_json::from_slice::<Value>(&record.content).is_ok_and(|stored| stored == Value::Object(view))
}

fn model_fields<T: Serialize>(model: &T) -> Result<serde_json::Map<String, Value>, String> {
    let Value::Object(mut fields) = serde_json::to_value(model).map_err(|error| error.to_string())? else {
        return Err("MCard model must serialize as an object".into());
    };
    fields.remove("card");
    Ok(fields)
}

pub(super) fn reference_envelope<T: Serialize>(model: &T, record: &MCardRecord) -> Result<Value, String> {
    record_algorithm(record)?;
    let mut fields = model_fields(model)?;
    fields.insert("hash".into(), record.hash.clone().into());
    Ok(Value::Object(fields))
}

/// Checks whether a payload and color_type satisfy a Place type expression.
pub fn check_type_expr(payload: &Value, color_type: &str, type_expr: &str) -> bool {
    let expr = type_expr.trim().to_lowercase();
    let ctype = color_type.trim().to_lowercase();
    let norm_ctype = ctype
        .strip_prefix(crate::layer0::vocabulary::HANDLE_CLM_TYPES)
        .or_else(|| ctype.strip_prefix(crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE))
        .unwrap_or(&ctype);
    let norm_expr = expr
        .strip_prefix(crate::layer0::vocabulary::HANDLE_CLM_TYPES)
        .or_else(|| expr.strip_prefix(crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE))
        .unwrap_or(&expr);
    if matches!(norm_expr, "any" | "*" | "top" | "true" | "") {
        return true;
    }
    if matches!(norm_expr, "bottom" | "none" | "false" | "empty") {
        return false;
    }
    if norm_ctype == norm_expr {
        return true;
    }
    if norm_expr.ends_with("/*") || norm_expr.ends_with('/') {
        let prefix = norm_expr.trim_end_matches('*');
        return norm_ctype.starts_with(prefix);
    }
    match norm_expr {
        "int" | "integer" | "number" => payload.is_i64() || payload.is_u64() || payload.is_f64(),
        "str" | "string" | "text" => payload.is_string(),
        "dict" | "map" | "object" | "structured" => payload.is_object(),
        "list" | "array" => payload.is_array(),
        "bool" | "boolean" => payload.is_boolean(),
        _ if (norm_expr.starts_with("view/") || norm_expr.starts_with(crate::layer0::vocabulary::HANDLE_CLM_VIEW)) && norm_ctype == "session/active" => payload.is_object(),
        _ => false,
    }
}

/// Petri Net Token realized as an `MCardRecord` and Cordis `PrimitivePCard` (`1 -> X`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct TokenMCard(TokenMCardData);

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenMCardData {
    /// Underlying immutable content-addressed MCard record.
    pub card: MCardRecord,
    /// Logical token identifier.
    pub token_id: String,
    /// Colour sort / type URI of the token.
    pub color_type: String,
    /// Structured JSON payload carried by the token.
    pub payload: Value,
}

impl std::ops::Deref for TokenMCard {
    type Target = TokenMCardData;
    fn deref(&self) -> &Self::Target { &self.0 }
}

impl<'de> Deserialize<'de> for TokenMCard {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let model = Self(TokenMCardData::deserialize(deserializer)?);
        if model.verify() { Ok(model) } else { Err(serde::de::Error::custom("MCard view differs from its verified record")) }
    }
}


impl TokenMCard {
    const KIND: &'static str = "token_mcard";

    /// Constructs a `TokenMCard` from a JSON payload and colour sort.
    pub fn from_payload(
        payload: Value,
        color_type: &str,
        token_id: &str,
        algorithm: Option<&str>,
        timestamp: Option<&str>,
    ) -> Result<Self, String> {
        let envelope = json!({
            "color_type": color_type,
            "kind": Self::KIND,
            "payload": payload,
            "token_id": token_id,
        });
        let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
        Ok(Self(TokenMCardData {
            card,
            token_id: token_id.to_string(),
            color_type: color_type.to_string(),
            payload,
        }))
    }

    /// Alias constructor for JSON token creation with default token ID.
    pub fn from_json(payload: &Value, color_type: &str, algorithm: Option<&str>) -> Result<Self, String> {
        Self::from_payload(payload.clone(), color_type, "tok_json", algorithm, None)
    }

    /// Returns the raw digest hex of the underlying `MCardRecord`.
    pub fn hash(&self) -> &str {
        &self.card.hash
    }

    /// Returns the algorithm-qualified `a:hex` reference.
    pub fn qualified_hash(&self) -> String {
        qualified_record_hash(&self.card).expect("immutable verified MCard")
    }

    /// Alias for `qualified_hash()` used across Layer 2/3 callers.
    pub fn qualified_ref(&self) -> String {
        self.qualified_hash()
    }

    pub fn to_hash_uri(&self) -> String {
        format!("{HANDLE_MCARD_HASH_2}{}", self.qualified_hash())
    }

    pub fn to_uri(&self) -> String {
        format!("{URI_SCHEME_MCARD}{}", self.qualified_hash())
    }

    /// Verifies cryptographic integrity of `card(hash, content, g_time)`.
    pub fn verify(&self) -> bool {
        verify_envelope(&self.card, self, Self::KIND)
    }

    /// Reflects `TokenMCard` into a Cordis `PrimitivePCard` (`1 -> X`).
    pub fn as_primitive_pcard(&self) -> PrimitivePCard {
        let author = AgentDid::new(crate::layer0::vocabulary_identities::DID_CLM_LAYER1).unwrap_or_else(|_| AgentDid::new_unchecked(crate::layer0::vocabulary_identities::DID_CLM_LAYER1));
        let uri = format!("{URI_SCHEME_MCARD}{}", self.qualified_hash());
        let mcard = MCard::new(uri, MCardPayload::Structured(self.payload.clone()), author, 0);
        PrimitivePCard::new(mcard)
    }

    /// Evaluates the `TokenMCard` as a constant `1 -> X` arrow returning its payload.
    pub fn evaluate(&self) -> &Value {
        &self.payload
    }
}

/// Petri Net Place realized as an `MCardRecord` and Type Lattice `BooleanPCard` (`X -> 2`).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct PlaceMCard(PlaceMCardData);

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct PlaceMCardData {
    /// Underlying immutable content-addressed MCard record.
    pub card: MCardRecord,
    /// Place identifier within the Petri Net.
    pub place_id: String,
    /// Type expression or URI guarding admission to this place.
    pub type_expr: String,
    /// Optional bounded capacity limit.
    pub capacity: Option<usize>,
    /// Structural lattice role (`InitialBottom`, `Intermediate`, `Exception`, `TerminalTop`).
    pub role: String,
    #[serde(skip, default)]
    cached_qualified_ref: MemoizedQualifiedRef,
}

impl std::ops::Deref for PlaceMCard {
    type Target = PlaceMCardData;
    fn deref(&self) -> &Self::Target { &self.0 }
}

impl<'de> Deserialize<'de> for PlaceMCard {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let model = Self(PlaceMCardData::deserialize(deserializer)?);
        if model.verify() { Ok(model) } else { Err(serde::de::Error::custom("MCard view differs from its verified record")) }
    }
}


impl PlaceMCard {
    const KIND: &'static str = "place_mcard";

    /// Creates a default `PlaceMCard` from a place ID.
    pub fn new(id: impl Into<String>) -> Self {
        Self::create(&id.into(), "any", None, "Intermediate", None, None).expect("default place envelope")
    }

    /// Returns the place identifier.
    pub fn id(&self) -> &str {
        &self.place_id
    }

    /// Creates a deterministic `PlaceMCard` with type guard and capacity bound.
    pub fn create(
        place_id: &str,
        type_expr: &str,
        capacity: Option<usize>,
        role: &str,
        algorithm: Option<&str>,
        timestamp: Option<&str>,
    ) -> Result<Self, String> {
        let cap_val = capacity.map(|c| json!(c)).unwrap_or(Value::Null);
        let envelope = json!({
            "capacity": cap_val,
            "kind": Self::KIND,
            "place_id": place_id,
            "role": role,
            "type_expr": type_expr,
        });
        let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
        Ok(Self(PlaceMCardData {
            card,
            place_id: place_id.to_string(),
            type_expr: type_expr.to_string(),
            capacity,
            role: role.to_string(),
            cached_qualified_ref: MemoizedQualifiedRef::default(),
        }))
    }

    /// Returns the raw digest hex of the underlying `MCardRecord`.
    pub fn hash(&self) -> &str {
        &self.card.hash
    }

    /// Returns the algorithm-qualified `a:hex` reference.
    pub fn qualified_hash(&self) -> String {
        self.cached_qualified_ref
            .get_or_init(|| qualified_record_hash(&self.card).expect("immutable verified MCard"))
            .to_string()
    }

    /// Alias for `qualified_hash()`.
    pub fn qualified_ref(&self) -> String {
        self.qualified_hash()
    }

    /// Verifies cryptographic integrity of `card(hash, content, g_time)`.
    pub fn verify(&self) -> bool {
        verify_envelope(&self.card, self, Self::KIND)
    }

    /// Reflects `PlaceMCard` into a Type Lattice `BooleanPCard` (`X -> 2`).
    pub fn as_boolean_pcard(&self) -> BooleanPCard {
        BooleanPCard {
            id: self.place_id.clone(),
            phase: InvariantPhase::Precondition,
            expression: self.type_expr.clone(),
            guarded_uri_pattern: format!("{URI_SCHEME_MCARD}{}", self.qualified_hash()),
            coeffects: CordisCoeffects::default(),
        }
    }

    /// Evaluates whether `token` is admitted by this Place's type guard and capacity bound.
    pub fn evaluate_guard(&self, token: &TokenMCard, current_occupancy: usize) -> BailVerdict {
        if let Some(cap) = self.capacity {
            if current_occupancy >= cap {
                return BailVerdict::Bail {
                    reason: format!("Place '{}' capacity {} exceeded", self.place_id, cap),
                    invariant_code: "INV-508-CAP".to_string(),
                    context_dump: json!({ "place_id": self.place_id, "capacity": cap }),
                };
            }
        }
        if check_type_expr(&token.payload, &token.color_type, &self.type_expr) {
            BailVerdict::Pass
        } else {
            BailVerdict::Bail {
                reason: format!(
                    "Token '{}' (color '{}') rejected by place '{}' guard '{}'",
                    token.token_id, token.color_type, self.place_id, self.type_expr
                ),
                invariant_code: "INV-508-TYPE".to_string(),
                context_dump: json!({
                    "place_id": self.place_id,
                    "expected": self.type_expr,
                    "actual": token.color_type,
                }),
            }
        }
    }

    /// Returns true if `evaluate_guard` passes for `token` at `current_occupancy`.
    pub fn admits(&self, token: &TokenMCard, current_occupancy: usize) -> bool {
        matches!(self.evaluate_guard(token, current_occupancy), BailVerdict::Pass)
    }
}