clm-kernel 0.0.12

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