clm-kernel 0.0.22

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! 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 crate::layer0::vocabulary::{HANDLE_MCARD_NS};
use std::collections::{BTreeMap, BTreeSet};
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
}

#[path = "firing_receipt.rs"]
mod firing_receipt;
pub use firing_receipt::*;

#[path = "marking_state.rs"]
mod marking_state;
pub use marking_state::MCardMarking;


/// 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!("{HANDLE_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!("{HANDLE_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!("{HANDLE_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!("{HANDLE_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.clone());
        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.clone());
        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.clone());
        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(crate::layer0::vocabulary::HASH_ALGORITHM_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.clone());
                    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))
    }
}