clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 1 TransitionMCard Model.

use crate::layer0::vocabulary::{URI_SCHEME_MCARD};
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::domain::{CordisCoeffects, DynamicPCard};
use crate::layer0::mcard_record::MCardRecord;
use crate::types::ContentHash;
use super::token_models::{qualified_record_hash, record_from_canonical_json, TokenMCard};

/// Petri Net Transition realized as an `MCardRecord` and Cordis `DynamicPCard` (`A -> B`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct TransitionMCard(TransitionMCardData);

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransitionMCardData {
    /// 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 std::ops::Deref for TransitionMCard {
    type Target = TransitionMCardData;
    fn deref(&self) -> &Self::Target { &self.0 }
}

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


impl TransitionMCard {
    const KIND: &'static str = "transition_mcard";

    /// 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": Self::KIND,
            "operation_expr": operation_expr,
            "output_places": output_places,
            "transition_id": transition_id,
        });
        let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
        Ok(Self(TransitionMCardData {
            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).expect("immutable verified MCard")
    }

    /// Verifies cryptographic integrity of `card(hash, content, g_time)`.
    pub fn verify(&self) -> bool {
        super::token_models::verify_envelope(&self.card, self, Self::KIND)
    }

    /// Reflects `TransitionMCard` into a Cordis `DynamicPCard` (`A -> B`).
    pub fn as_dynamic_pcard(&self) -> Result<DynamicPCard, String> {
        let services: Vec<String> = self
            .coeffects
            .iter()
            .filter(|(_, mode)| mode.as_str() != "none")
            .map(|(k, v)| format!("{k}:{v}"))
            .collect();
        Ok(DynamicPCard {
            id: self.transition_id.clone(),
            code_hash: ContentHash::parse(&self.card.hash).map_err(|e| e.to_string())?,
            source_uri: format!("{URI_SCHEME_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 declared_algorithm = super::token_models::record_algorithm(&self.card)?;
        let algo = algorithm.unwrap_or(&declared_algorithm);
        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)
    }
}