clm-kernel 0.0.22

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! NetMCard extracted from `mcard_token.rs` (Sprint 534 compactness ratchet).

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

/// Valk's Object Petri Net (Nets-Within-Nets) realized as an `MCardRecord`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct NetMCard(NetMCardData);

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetMCardData {
    /// 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>>,
    #[serde(skip, default)]
    cached_qualified_ref: MemoizedQualifiedRef,
}

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

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


impl NetMCard {
    const KIND: &'static str = "net_mcard";

    /// 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(|token| token_models::reference_envelope(token, &token.card))
                .collect::<Result<_, _>>()?;
            marking_json.insert(pid.clone(), Value::Array(arr));
        }
        let places_json: Vec<Value> = places
            .iter()
            .map(|place| token_models::reference_envelope(place, &place.card))
            .collect::<Result<_, _>>()?;
        let trans_json: Vec<Value> = transitions
            .iter()
            .map(|transition| token_models::reference_envelope(transition, &transition.card))
            .collect::<Result<_, _>>()?;
        let envelope = json!({
            "kind": Self::KIND,
            "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(NetMCardData {
            card,
            net_id: net_id.to_string(),
            places,
            transitions,
            marking,
            cached_qualified_ref: MemoizedQualifiedRef::default(),
        }))
    }

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

    /// Returns the memoized 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()
    }

    pub fn verify(&self) -> bool {
        let Ok(algorithm) = record_algorithm(&self.card) else { return false; };
        Self::create(&self.net_id, self.places.clone(), self.transitions.clone(), self.marking.clone(), Some(&algorithm), None)
            .is_ok_and(|rebuilt| rebuilt.card.content == self.card.content)
    }

    /// 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, Self::KIND, &format!("net_tok_{}", self.net_id), Some(algo), timestamp)
    }
}