clm-kernel 0.0.11

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
486
487
488
//! Layer 1 MCardCollection Unified Token Namespace & Cordis Fiber Firing Engine (Sprint 509).
//!
//! Implements:
//! - `MCardMarking`: Lossless canonical multiset marking `PlaceId -> Vec<QualifiedMCardRef>` (`a:hex`).
//! - `FiringReceiptMCard`: Self-verifying `MCardRecord` sealing a 5-state Cordis `Fiber` transition firing.
//! - `MCardTokenNamespace`: Unified `mcard://ns/<net_id>/...` namespace over `MCardRecord` storage,
//!   executing transitions inside a 5-state Cordis `Fiber` (`PENDING -> LOADING -> ACTIVE -> UNLOADING -> DISPOSED`)
//!   with LIFO rollback and algorithm-agile (`blake3` / `sha256`) verification.

use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::cpn::mcard_token::{
    qualified_record_hash, record_from_canonical_json, PlaceMCard, TokenMCard, TransitionMCard,
    DEFAULT_TIMESTAMP,
};
use crate::cpn::place_type_lattice::{PlaceRole, PlaceTypeBinding};
use crate::domain::BailVerdict;
use crate::layer0::mcard_record::MCardRecord;

/// Canonical 5-state Cordis `Fiber` lifecycle state sequence.
pub const FIBER_LIFECYCLE_STATES: [&str; 5] = [
    "PENDING",
    "LOADING",
    "ACTIVE",
    "UNLOADING",
    "DISPOSED",
];

/// Verifies `token`'s `MCardRecord` integrity and optional expected `a:hex` reference.
pub fn verify_qualified_ref(token: &TokenMCard, expected_qualified_ref: Option<&str>) -> bool {
    if !token.verify() {
        return false;
    }
    if let Some(expected) = expected_qualified_ref {
        let Some((prefix, raw_hex)) = expected.split_once(':') else {
            return false;
        };
        let actual_q = token.qualified_hash();
        let Some((actual_prefix, actual_hex)) = actual_q.split_once(':') else {
            return false;
        };
        if prefix.trim().to_lowercase() != actual_prefix || raw_hex.trim().to_lowercase() != actual_hex {
            return false;
        }
    }
    true
}

/// Self-verifying `MCardRecord` receipt sealing a 5-state Cordis `Fiber` transition firing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FiringReceiptMCard {
    /// Underlying immutable content-addressed MCard record.
    pub card: MCardRecord,
    /// Petri Net identifier.
    pub net_id: String,
    /// Fired transition identifier.
    pub transition_id: String,
    /// Monotonic step sequence number.
    pub step_seq: usize,
    /// Recorded Cordis `Fiber` lifecycle state trace.
    pub fiber_state_trace: Vec<String>,
    /// Consumed token references indexed by input place ID.
    pub consumed_refs: BTreeMap<String, Vec<String>>,
    /// Produced token references indexed by output place ID.
    pub produced_refs: BTreeMap<String, Vec<String>>,
    /// Pre-firing marking state hash (`a:hex`).
    pub pre_marking_hash: String,
    /// Post-firing marking state hash (`a:hex`).
    pub post_marking_hash: String,
    /// Execution verdict (`COMMITTED`, `ROLLED_BACK`, or `ROUTED_TO_EXCEPTION`).
    pub verdict: String,
}

impl FiringReceiptMCard {
    /// Creates a deterministic `FiringReceiptMCard` sealing a transition firing step.
    pub fn create(
        net_id: &str,
        transition_id: &str,
        step_seq: usize,
        fiber_state_trace: Vec<String>,
        consumed_refs: BTreeMap<String, Vec<String>>,
        produced_refs: BTreeMap<String, Vec<String>>,
        pre_marking_hash: &str,
        post_marking_hash: &str,
        verdict: &str,
        algorithm: Option<&str>,
        timestamp: Option<&str>,
    ) -> Result<Self, String> {
        let envelope = json!({
            "consumed_refs": consumed_refs,
            "fiber_state_trace": fiber_state_trace,
            "kind": "firing_receipt_mcard",
            "net_id": net_id,
            "post_marking_hash": post_marking_hash,
            "pre_marking_hash": pre_marking_hash,
            "produced_refs": produced_refs,
            "step_seq": step_seq,
            "transition_id": transition_id,
            "verdict": verdict,
        });
        let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
        Ok(Self {
            card,
            net_id: net_id.to_string(),
            transition_id: transition_id.to_string(),
            step_seq,
            fiber_state_trace,
            consumed_refs,
            produced_refs,
            pre_marking_hash: pre_marking_hash.to_string(),
            post_marking_hash: post_marking_hash.to_string(),
            verdict: verdict.to_string(),
        })
    }

    /// Returns the algorithm-qualified `a:hex` reference for this receipt.
    pub fn qualified_hash(&self) -> String {
        qualified_record_hash(&self.card)
    }
}

/// Lossless canonical multiset marking `PlaceId -> Vec<QualifiedMCardRef>` (`a:hex`).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MCardMarking {
    /// Token reference lists indexed by place ID.
    pub by_place: BTreeMap<String, Vec<String>>,
}

impl MCardMarking {
    /// Creates an empty `MCardMarking`.
    pub fn new() -> Self {
        Self { by_place: BTreeMap::new() }
    }

    /// Returns the ordered list of qualified token references at `place_id`.
    pub fn place_refs(&self, place_id: &str) -> Vec<String> {
        self.by_place.get(place_id).cloned().unwrap_or_default()
    }

    /// Alias for `place_refs(place_id)` returning token references at `place_id`.
    pub fn tokens_at(&self, place_id: &str) -> Vec<String> {
        self.place_refs(place_id)
    }

    /// Returns the current token count at `place_id`.
    pub fn count(&self, place_id: &str) -> usize {
        self.by_place.get(place_id).map(|v| v.len()).unwrap_or(0)
    }

    /// Projects the multiset marking into an integer occupancy map `PlaceId -> usize`.
    pub fn token_counts(&self) -> BTreeMap<String, usize> {
        self.by_place.iter().map(|(k, v)| (k.clone(), v.len())).collect()
    }

    /// Appends `qualified_ref` to `place_id`.
    pub fn append(&mut self, place_id: &str, qualified_ref: String) {
        self.by_place.entry(place_id.to_string()).or_default().push(qualified_ref);
    }

    /// Pops and returns the first token reference from `place_id`, if non-empty.
    pub fn pop_first(&mut self, place_id: &str) -> Option<String> {
        let vec = self.by_place.get_mut(place_id)?;
        if vec.is_empty() { None } else { Some(vec.remove(0)) }
    }

    /// Computes a deterministic `a:hex` state hash over the canonical marking JSON.
    pub fn state_hash(&self, algorithm: Option<&str>) -> Result<String, String> {
        let val = serde_json::to_value(&self.by_place)
            .map_err(|e| format!("Failed to serialize MCardMarking: {e}"))?;
        let rec = record_from_canonical_json(&val, algorithm, Some(DEFAULT_TIMESTAMP))?;
        Ok(qualified_record_hash(&rec))
    }
}

/// Unified `mcard://ns/<net_id>/...` namespace over `MCardRecord` storage and Cordis `Fiber` firing.
#[derive(Debug, Clone)]
pub struct MCardTokenNamespace {
    /// Logical Petri Net identifier.
    pub net_id: String,
    /// Registered `PlaceMCard`s indexed by place ID.
    pub places: BTreeMap<String, PlaceMCard>,
    /// Registered `PlaceTypeBinding`s indexed by place ID.
    pub bindings: BTreeMap<String, PlaceTypeBinding>,
    /// Registered `TransitionMCard`s indexed by transition ID.
    pub transitions: BTreeMap<String, TransitionMCard>,
    /// Content-addressed `TokenMCard`s indexed by qualified ref (`a:hex`).
    pub tokens_by_ref: BTreeMap<String, TokenMCard>,
    /// Content-addressed `MCardRecord`s indexed by qualified ref (`a:hex`).
    pub records_by_ref: BTreeMap<String, MCardRecord>,
    /// Mutable handle table mapping `mcard://ns/...` URIs to qualified refs.
    pub handles: BTreeMap<String, String>,
    /// Current multiset marking.
    pub marking: MCardMarking,
    /// Sealed `FiringReceiptMCard` audit log.
    pub receipts: Vec<FiringReceiptMCard>,
    deposit_seq: BTreeMap<String, usize>,
}

impl MCardTokenNamespace {
    /// Creates a new `MCardTokenNamespace` for `net_id`.
    pub fn new(net_id: &str) -> Self {
        Self {
            net_id: net_id.to_string(),
            places: BTreeMap::new(),
            bindings: BTreeMap::new(),
            transitions: BTreeMap::new(),
            tokens_by_ref: BTreeMap::new(),
            records_by_ref: BTreeMap::new(),
            handles: BTreeMap::new(),
            marking: MCardMarking::new(),
            receipts: Vec::new(),
            deposit_seq: BTreeMap::new(),
        }
    }

    /// Formats the canonical namespace URI for `place_id`.
    pub fn place_uri(&self, place_id: &str) -> String {
        format!("mcard://ns/{}/places/{place_id}", self.net_id)
    }

    /// Formats the canonical namespace URI for `transition_id`.
    pub fn transition_uri(&self, transition_id: &str) -> String {
        format!("mcard://ns/{}/transitions/{transition_id}", self.net_id)
    }

    /// Formats the canonical namespace URI for a marking slot at `(place_id, seq)`.
    pub fn marking_uri(&self, place_id: &str, seq: usize) -> String {
        format!("mcard://ns/{}/markings/{place_id}/{seq}", self.net_id)
    }

    /// Formats the canonical namespace URI for `receipt` at `step_seq`.
    pub fn receipt_uri(&self, step_seq: usize) -> String {
        format!("mcard://ns/{}/receipts/{step_seq}", self.net_id)
    }

    /// Registers a `PlaceMCard` and optional `PlaceTypeBinding` in the namespace.
    pub fn register_place(&mut self, place: PlaceMCard, binding: Option<PlaceTypeBinding>) -> String {
        let pid = place.place_id.clone();
        let qref = place.qualified_hash();
        let resolved_binding = binding.unwrap_or_else(|| {
            PlaceTypeBinding::new(place.clone(), PlaceRole::Intermediate, None, None)
        });
        self.places.insert(pid.clone(), place.clone());
        self.bindings.insert(pid.clone(), resolved_binding);
        self.marking.by_place.entry(pid.clone()).or_default();
        self.records_by_ref.insert(qref.clone(), place.card);
        let uri = self.place_uri(&pid);
        self.handles.insert(uri.clone(), qref);
        uri
    }

    /// Registers a `TransitionMCard` in the namespace.
    pub fn register_transition(&mut self, transition: TransitionMCard) -> String {
        let tid = transition.transition_id.clone();
        let qref = transition.qualified_hash();
        self.transitions.insert(tid.clone(), transition.clone());
        self.records_by_ref.insert(qref.clone(), transition.card);
        let uri = self.transition_uri(&tid);
        self.handles.insert(uri.clone(), qref);
        uri
    }

    /// Deposits `token` into `place_id` after verifying `g_time` and `PlaceTypeBinding` guards.
    pub fn deposit_token(
        &mut self,
        place_id: &str,
        token: TokenMCard,
        expected_qualified_ref: Option<&str>,
        author_did: Option<&str>,
    ) -> BailVerdict {
        if !verify_qualified_ref(&token, expected_qualified_ref) {
            return BailVerdict::Bail {
                reason: format!("Token '{}' failed qualified reference or g_time verification", token.token_id),
                invariant_code: "INV-509-VERIFY".to_string(),
                context_dump: json!({ "token_id": token.token_id }),
            };
        }
        let occ = self.marking.count(place_id);
        if let Some(binding) = self.bindings.get(place_id) {
            let verdict = binding.validate_token(&token, author_did, occ);
            if matches!(verdict, BailVerdict::Bail { .. }) {
                return verdict;
            }
        }
        let qref = token.qualified_hash();
        self.tokens_by_ref.insert(qref.clone(), token.clone());
        self.records_by_ref.insert(qref.clone(), token.card);
        self.marking.append(place_id, qref.clone());
        let seq = *self.deposit_seq.get(place_id).unwrap_or(&0);
        self.deposit_seq.insert(place_id.to_string(), seq + 1);
        let uri = self.marking_uri(place_id, seq);
        self.handles.insert(uri, qref);
        BailVerdict::Pass
    }

    /// Materializes the ordered `TokenMCard` list currently residing in `place_id`.
    pub fn get_place_tokens(&self, place_id: &str) -> Vec<TokenMCard> {
        self.marking
            .place_refs(place_id)
            .into_iter()
            .filter_map(|qref| self.tokens_by_ref.get(&qref).cloned())
            .collect()
    }

    /// Executes `transition_id` inside a 5-state Cordis `Fiber` with LIFO rollback and exception trap routing.
    pub fn fire_in_cordis_fiber<F>(
        &mut self,
        transition_id: &str,
        available_services: Option<&BTreeSet<String>>,
        exception_place_id: Option<&str>,
        author_did: Option<&str>,
        transform: F,
        output_algorithm: Option<&str>,
    ) -> Result<(FiringReceiptMCard, BailVerdict), String>
    where
        F: Fn(&[Value]) -> Result<Value, String>,
    {
        let transition = self
            .transitions
            .get(transition_id)
            .cloned()
            .ok_or_else(|| format!("Transition '{transition_id}' not registered"))?;
        let out_algo = output_algorithm.unwrap_or("blake3");

        let pre_snapshot = self.marking.clone();
        let pre_handles = self.handles.clone();
        let pre_seq = self.deposit_seq.clone();
        let pre_hash = pre_snapshot.state_hash(Some(out_algo))?;

        let abort = |ns: &mut Self,
                         reason: String,
                         consumed_tokens: Vec<TokenMCard>,
                         mut trace: Vec<String>|
         -> Result<(FiringReceiptMCard, BailVerdict), String> {
            ns.marking = pre_snapshot.clone();
            ns.handles = pre_handles.clone();
            ns.deposit_seq = pre_seq.clone();
            let is_suspended = reason.contains("SUSPENDED") || reason.contains("suspended");
            let mut verdict_label = if is_suspended { "SUSPENDED" } else { "ROLLED_BACK" };
            if is_suspended {
                if trace.last().map(|s| s.as_str()) != Some("SUSPENDED") {
                    trace.push("SUSPENDED".to_string());
                }
            } else {
                trace.push("UNLOADING".to_string());
                trace.push("DISPOSED".to_string());
            }
            let mut produced_map = BTreeMap::new();
            if let Some(exc_pid) = exception_place_id {
                if !consumed_tokens.is_empty() {
                    for in_pid in &transition.input_places {
                        ns.marking.pop_first(in_pid);
                    }
                    let exc_tok = TokenMCard::from_payload(
                        json!({
                            "input_refs": consumed_tokens.iter().map(|t| t.qualified_hash()).collect::<Vec<_>>(),
                            "reason": reason,
                            "transition_id": transition_id,
                        }),
                        "exception",
                        &format!("exc_{transition_id}_{}", ns.receipts.len()),
                        Some(out_algo),
                        Some(DEFAULT_TIMESTAMP),
                    )?;
                    let qref = exc_tok.qualified_hash();
                    ns.tokens_by_ref.insert(qref.clone(), exc_tok.clone());
                    ns.records_by_ref.insert(qref.clone(), exc_tok.card);
                    ns.marking.append(exc_pid, qref.clone());
                    produced_map.insert(exc_pid.to_string(), vec![qref]);
                    verdict_label = "ROUTED_TO_EXCEPTION";
                }
            }

            let post_hash = ns.marking.state_hash(Some(out_algo))?;
            let step_seq = ns.receipts.len();
            let receipt = FiringReceiptMCard::create(
                &ns.net_id,
                transition_id,
                step_seq,
                trace,
                BTreeMap::new(),
                produced_map,
                &pre_hash,
                &post_hash,
                verdict_label,
                Some(out_algo),
                Some(DEFAULT_TIMESTAMP),
            )?;
            let rq = receipt.qualified_hash();
            ns.records_by_ref.insert(rq.clone(), receipt.card.clone());
            let r_uri = ns.receipt_uri(step_seq);
            ns.handles.insert(r_uri, rq);
            ns.receipts.push(receipt.clone());
            Ok((
                receipt,
                BailVerdict::Bail {
                    reason,
                    invariant_code: "INV-509-FIBER".to_string(),
                    context_dump: json!({ "transition_id": transition_id }),
                },
            ))
        };

        let mut trace = vec!["PENDING".to_string()];
        let mut consumed_tokens = Vec::new();
        let mut consumed_refs: BTreeMap<String, Vec<String>> = BTreeMap::new();
        for in_pid in &transition.input_places {
            let refs = self.marking.place_refs(in_pid);
            if refs.is_empty() {
                return abort(self, format!("Input place '{in_pid}' is empty"), Vec::new(), trace);
            }
            let qref = &refs[0];
            let Some(tok) = self.tokens_by_ref.get(qref).cloned() else {
                return abort(self, format!("Token '{qref}' not found"), Vec::new(), trace);
            };
            if !verify_qualified_ref(&tok, Some(qref)) {
                return abort(self, format!("Token '{qref}' failed g_time verification"), Vec::new(), trace);
            }
            consumed_tokens.push(tok);
            consumed_refs.entry(in_pid.clone()).or_default().push(qref.clone());
        }

        trace.push("LOADING".to_string());
        let required_svcs: BTreeSet<String> = transition
            .coeffects
            .iter()
            .filter(|(_, mode)| mode.as_str() != "none")
            .map(|(k, _)| k.clone())
            .collect();
        if !required_svcs.is_empty() {
            let empty_set = BTreeSet::new();
            let provided = available_services.unwrap_or(&empty_set);
            let missing: Vec<String> = required_svcs.difference(provided).cloned().collect();
            if !missing.is_empty() {
                let msg = format!("Missing required CordisCoeffects services: {missing:?}");
                return abort(self, msg, consumed_tokens, trace);
            }
        }
        for (in_pid, tok) in transition.input_places.iter().zip(consumed_tokens.iter()) {
            if let Some(binding) = self.bindings.get(in_pid) {
                if let BailVerdict::Bail { reason, .. } = binding.validate_token(tok, author_did, 0) {
                    return abort(self, reason, consumed_tokens, trace);
                }
            }
        }
        trace.push("ACTIVE".to_string());
        for in_pid in &transition.input_places {
            self.marking.pop_first(in_pid);
        }
        let raw_inputs: Vec<Value> = consumed_tokens.iter().map(|t| t.payload.clone()).collect();
        let out_val = match transform(&raw_inputs) {
            Ok(v) => v,
            Err(err) => return abort(self, err, consumed_tokens, trace),
        };
        let out_count = transition.output_places.len().max(1);
        let mut produced_tokens = Vec::with_capacity(out_count);
        for idx in 0..out_count {
            produced_tokens.push(TokenMCard::from_payload(
                out_val.clone(), &transition.codomain_type, &format!("{transition_id}_out_{idx}"),
                Some(out_algo), Some(DEFAULT_TIMESTAMP),
            )?);
        }
        trace.push("UNLOADING".to_string());
        let mut produced_refs: BTreeMap<String, Vec<String>> = BTreeMap::new();
        for (idx, out_pid) in transition.output_places.iter().enumerate() {
            let out_tok = produced_tokens.get(idx).unwrap_or_else(|| produced_tokens.last().unwrap()).clone();
            let qref = out_tok.qualified_hash();
            if let BailVerdict::Bail { reason, .. } = self.deposit_token(out_pid, out_tok, Some(&qref), author_did) {
                return abort(self, reason, consumed_tokens, trace[..3].to_vec());
            }
            produced_refs.entry(out_pid.clone()).or_default().push(qref);
        }
        trace.push("DISPOSED".to_string());
        let post_hash = self.marking.state_hash(Some(out_algo))?;
        let step_seq = self.receipts.len();
        let receipt = FiringReceiptMCard::create(
            &self.net_id, transition_id, step_seq, trace, consumed_refs, produced_refs,
            &pre_hash, &post_hash, "COMMITTED", Some(out_algo), Some(DEFAULT_TIMESTAMP),
        )?;
        let rq = receipt.qualified_hash();
        self.records_by_ref.insert(rq.clone(), receipt.card.clone());
        self.handles.insert(self.receipt_uri(step_seq), rq);
        self.receipts.push(receipt.clone());
        Ok((receipt, BailVerdict::Pass))
    }
}