clm-kernel 0.0.13

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

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

use crate::domain::{CordisCoeffects, DynamicPCard};
use crate::layer0::mcard_record::{verify_record, MCardRecord, RecordVerification};
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, Deserialize)]
pub struct TransitionMCard {
    /// 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 TransitionMCard {
    /// 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": "transition_mcard",
            "operation_expr": operation_expr,
            "output_places": output_places,
            "transition_id": transition_id,
        });
        let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
        Ok(Self {
            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)
    }

    /// Verifies cryptographic integrity of `card(hash, content, g_time)`.
    pub fn verify(&self) -> bool {
        matches!(verify_record(&self.card), RecordVerification::DeclaredOk { .. })
    }

    /// Reflects `TransitionMCard` into a Cordis `DynamicPCard` (`A -> B`).
    pub fn as_dynamic_pcard(&self) -> DynamicPCard {
        let services: Vec<String> = self
            .coeffects
            .iter()
            .filter(|(_, mode)| mode.as_str() != "none")
            .map(|(k, v)| format!("{k}:{v}"))
            .collect();
        DynamicPCard {
            id: self.transition_id.clone(),
            code_hash: ContentHash::parse(&self.card.hash)
                .unwrap_or_else(|_| ContentHash::compute(&self.card.content)),
            source_uri: format!("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 algo = algorithm.unwrap_or_else(|| {
            if self.card.g_time.starts_with("sha256|") { "sha256" } else { "blake3" }
        });
        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)
    }
}