clm-kernel 0.0.8

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
//! 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 std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::domain::{
    to_canonical_json_bytes, BailVerdict, BooleanPCard, CordisCoeffects, DynamicPCard,
    InvariantPhase, MCard, MCardPayload, PrimitivePCard,
};
use crate::layer0::mcard_record::{verify_record, MCardRecord, RecordVerification};
use crate::types::{AgentDid, ContentHash};

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

/// 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("blake3").trim().trim_end_matches(':').to_lowercase();
    let ts = timestamp.unwrap_or(DEFAULT_TIMESTAMP);
    let bytes = to_canonical_json_bytes(envelope);
    let hash = crate::hash::raw_hash_bytes_for(&algo, &bytes)?;
    let g_time = crate::fs_utils::compute_g_time_at(&algo, ts, DEFAULT_LOCALE)?;
    Ok(MCardRecord { hash, content: bytes, g_time })
}

/// Returns the algorithm declared in `record.g_time`.
pub fn record_algorithm(record: &MCardRecord) -> String {
    record.g_time.split('|').next().unwrap_or("blake3").trim().to_lowercase()
}

/// Returns the qualified `a:hex` reference for `record`.
pub fn qualified_record_hash(record: &MCardRecord) -> String {
    let algo = record_algorithm(record);
    let raw = record.hash.split_once(':').map(|(_, h)| h).unwrap_or(record.hash.as_str());
    format!("{algo}:{raw}")
}

/// 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();
    if matches!(expr.as_str(), "any" | "*" | "top" | "true" | "") || expr.starts_with("clm://") {
        return true;
    }
    if matches!(expr.as_str(), "bottom" | "none" | "false" | "empty") {
        return false;
    }
    if color_type.trim().to_lowercase() == expr {
        return true;
    }
    match expr.as_str() {
        "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(),
        _ => false,
    }
}

/// Petri Net Token realized as an `MCardRecord` and Cordis `PrimitivePCard` (`1 -> X`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenMCard {
    /// 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 TokenMCard {
    /// 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": "token_mcard",
            "payload": payload,
            "token_id": token_id,
        });
        let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
        Ok(Self {
            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)
    }

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

    /// Verifies cryptographic integrity of `card(hash, content, g_time)`.
    pub fn verify(&self) -> bool {
        matches!(verify_record(&self.card), RecordVerification::DeclaredOk { .. })
    }

    /// Reflects `TokenMCard` into a Cordis `PrimitivePCard` (`1 -> X`).
    pub fn as_primitive_pcard(&self) -> PrimitivePCard {
        let author = AgentDid::new("did:clm:layer1").unwrap_or_else(|_| AgentDid::new_unchecked("did:clm:layer1"));
        let uri = format!("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, Serialize, Deserialize)]
pub struct PlaceMCard {
    /// 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,
}

impl PlaceMCard {
    /// 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": "place_mcard",
            "place_id": place_id,
            "role": role,
            "type_expr": type_expr,
        });
        let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
        Ok(Self {
            card,
            place_id: place_id.to_string(),
            type_expr: type_expr.to_string(),
            capacity,
            role: role.to_string(),
        })
    }

    /// 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)
    }

    /// Verifies cryptographic integrity of `card(hash, content, g_time)`.
    pub fn verify(&self) -> bool {
        matches!(verify_record(&self.card), RecordVerification::DeclaredOk { .. })
    }

    /// 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!("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)
    }
}

/// Petri Net Transition realized as an `MCardRecord` and Cordis `DynamicPCard` (`A -> B`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransitionMCard {
    /// Underlying immutable content-addressed MCard record.
    pub card: MCardRecord,
    /// Transition identifier within the Petri Net.
    pub transition_id: String,
    /// Ordered list of input place identifiers.
    pub input_places: Vec<String>,
    /// Ordered list of output place identifiers.
    pub output_places: Vec<String>,
    /// Domain colour sort expression.
    pub domain_type: String,
    /// Codomain colour sort expression.
    pub codomain_type: String,
    /// Declared 5-axis Cordis coeffect vector.
    pub coeffects: BTreeMap<String, String>,
    /// Symbolic operation expression.
    pub operation_expr: String,
}

impl TransitionMCard {
    /// Returns the pure default 5-axis Cordis coeffect vector (`none` on all axes).
    pub fn default_coeffect_map() -> BTreeMap<String, String> {
        let mut m = BTreeMap::new();
        for axis in ["filesystem", "network", "random", "sqlite", "time"] {
            m.insert(axis.to_string(), "none".to_string());
        }
        m
    }

    /// Creates a deterministic `TransitionMCard` from input/output places and coeffects.
    pub fn create(
        transition_id: &str,
        input_places: Vec<String>,
        output_places: Vec<String>,
        domain_type: &str,
        codomain_type: &str,
        coeffects: Option<BTreeMap<String, String>>,
        operation_expr: &str,
        algorithm: Option<&str>,
        timestamp: Option<&str>,
    ) -> Result<Self, String> {
        let coeff = coeffects.unwrap_or_else(Self::default_coeffect_map);
        let envelope = json!({
            "codomain_type": codomain_type,
            "coeffects": coeff,
            "domain_type": domain_type,
            "input_places": input_places,
            "kind": "transition_mcard",
            "operation_expr": operation_expr,
            "output_places": output_places,
            "transition_id": transition_id,
        });
        let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
        Ok(Self {
            card,
            transition_id: transition_id.to_string(),
            input_places,
            output_places,
            domain_type: domain_type.to_string(),
            codomain_type: codomain_type.to_string(),
            coeffects: coeff,
            operation_expr: operation_expr.to_string(),
        })
    }

    /// 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)
    }

    /// Verifies cryptographic integrity of `card(hash, content, g_time)`.
    pub fn verify(&self) -> bool {
        matches!(verify_record(&self.card), RecordVerification::DeclaredOk { .. })
    }

    /// Reflects `TransitionMCard` into a Cordis `DynamicPCard` (`A -> B`).
    pub fn as_dynamic_pcard(&self) -> DynamicPCard {
        let services: Vec<String> = self
            .coeffects
            .iter()
            .filter(|(_, mode)| mode.as_str() != "none")
            .map(|(k, v)| format!("{k}:{v}"))
            .collect();
        DynamicPCard {
            id: self.transition_id.clone(),
            code_hash: ContentHash::parse(&self.card.hash)
                .unwrap_or_else(|_| ContentHash::compute(&self.card.content)),
            source_uri: format!("mcard://{}", self.qualified_hash()),
            coeffects: CordisCoeffects {
                required_services: services,
                input_schema_uri: Some(self.domain_type.clone()),
                output_schema_uri: Some(self.codomain_type.clone()),
                required_capabilities: Vec::new(),
            },
            signature: format!("{} -> {}", self.domain_type, self.codomain_type),
        }
    }

    /// Fires the transition over `input_tokens` and mints output `TokenMCard`s.
    pub fn fire<F>(
        &self,
        input_tokens: &[TokenMCard],
        transform: F,
        algorithm: Option<&str>,
        timestamp: Option<&str>,
    ) -> Result<Vec<TokenMCard>, String>
    where
        F: Fn(&[Value]) -> Value,
    {
        let algo = algorithm.unwrap_or_else(|| {
            if self.card.g_time.starts_with("sha256|") { "sha256" } else { "blake3" }
        });
        let raw_inputs: Vec<Value> = input_tokens.iter().map(|t| t.payload.clone()).collect();
        let out_payload = transform(&raw_inputs);
        let out_count = self.output_places.len().max(1);
        let mut produced = Vec::with_capacity(out_count);
        for idx in 0..out_count {
            produced.push(TokenMCard::from_payload(
                out_payload.clone(),
                &self.codomain_type,
                &format!("{}_out_{idx}", self.transition_id),
                Some(algo),
                timestamp,
            )?);
        }
        Ok(produced)
    }
}

/// Valk's Object Petri Net (Nets-Within-Nets) realized as an `MCardRecord`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetMCard {
    /// Underlying immutable content-addressed MCard record.
    pub card: MCardRecord,
    /// Identifier of the serialized Petri Net.
    pub net_id: String,
    /// Places belonging to the Petri Net.
    pub places: Vec<PlaceMCard>,
    /// Transitions belonging to the Petri Net.
    pub transitions: Vec<TransitionMCard>,
    /// Current token marking indexed by place ID.
    pub marking: BTreeMap<String, Vec<TokenMCard>>,
}

impl NetMCard {
    /// Creates a deterministic `NetMCard` encapsulating an entire Petri Net and marking.
    pub fn create(
        net_id: &str,
        places: Vec<PlaceMCard>,
        transitions: Vec<TransitionMCard>,
        marking: BTreeMap<String, Vec<TokenMCard>>,
        algorithm: Option<&str>,
        timestamp: Option<&str>,
    ) -> Result<Self, String> {
        let mut marking_json = serde_json::Map::new();
        for (pid, toks) in &marking {
            let arr: Vec<Value> = toks
                .iter()
                .map(|t| json!({"color_type": t.color_type, "hash": t.card.hash, "payload": t.payload, "token_id": t.token_id}))
                .collect();
            marking_json.insert(pid.clone(), Value::Array(arr));
        }
        let places_json: Vec<Value> = places
            .iter()
            .map(|p| json!({"capacity": p.capacity, "hash": p.card.hash, "place_id": p.place_id, "role": p.role, "type_expr": p.type_expr}))
            .collect();
        let trans_json: Vec<Value> = transitions
            .iter()
            .map(|tr| json!({"codomain_type": tr.codomain_type, "coeffects": tr.coeffects, "domain_type": tr.domain_type, "hash": tr.card.hash, "input_places": tr.input_places, "operation_expr": tr.operation_expr, "output_places": tr.output_places, "transition_id": tr.transition_id}))
            .collect();
        let envelope = json!({
            "kind": "net_mcard",
            "marking": Value::Object(marking_json),
            "net_id": net_id,
            "places": places_json,
            "transitions": trans_json,
        });
        let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
        Ok(Self { card, net_id: net_id.to_string(), places, transitions, marking })
    }

    /// Reifies this `NetMCard` as a higher-order `TokenMCard` (Nets-Within-Nets).
    pub fn to_token_mcard(&self, algorithm: Option<&str>, timestamp: Option<&str>) -> Result<TokenMCard, String> {
        let payload: Value = serde_json::from_slice(&self.card.content)
            .map_err(|e| format!("Failed to decode NetMCard content: {e}"))?;
        let algo_owned = record_algorithm(&self.card);
        let algo = algorithm.unwrap_or(&algo_owned);
        TokenMCard::from_payload(payload, "net_mcard", &format!("net_tok_{}", self.net_id), Some(algo), timestamp)
    }
}