clm-kernel 0.0.13

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 1 All-MCard Token Ontology & Cordis Function-Number Duality (Sprint 507).
//!
//! Implements the All-MCard Petri Net Triad where every Petri Net element is an
//! immutable content-addressed `MCardRecord` (`card(hash, content, g_time)`):
//! - `TokenMCard`: Value MCard <-> Cordis `PrimitivePCard` (`1 -> X`)
//! - `PlaceMCard`: Guard MCard <-> Type Lattice `BooleanPCard` (`X -> 2`)
//! - `TransitionMCard`: Operator MCard <-> Cordis `DynamicPCard` (`A -> B`) with `CordisCoeffects`
//! - `NetMCard`: Valk's Object Petri Nets (Nets-Within-Nets) serialized as a `TokenMCard`

#[allow(unused_imports)]
use std::collections::BTreeMap;
use std::sync::OnceLock;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::domain::{
    to_canonical_json_bytes, BailVerdict, BooleanPCard, CordisCoeffects,
    InvariantPhase, MCard, MCardPayload, PrimitivePCard,
};
use crate::layer0::mcard_record::{verify_record, MCardRecord, RecordVerification};
#[allow(unused_imports)]
use crate::types::{AgentDid, ContentHash};

/// Default canonical ISO-8601 timestamp for deterministic Layer 1 MCard minting.
pub const DEFAULT_TIMESTAMP: &str = "2026-04-16T00:00:00Z";
/// Default canonical locale tag for `g_time`.
pub const DEFAULT_LOCALE: &str = "UTC";

/// Transparent lazy cache for qualified `algorithm:hex` references.
#[derive(Default)]
pub struct MemoizedQualifiedRef(OnceLock<String>);

impl MemoizedQualifiedRef {
    #[inline]
    pub fn get_or_init<F: FnOnce() -> String>(&self, f: F) -> &str {
        self.0.get_or_init(f).as_str()
    }
}

impl std::fmt::Debug for MemoizedQualifiedRef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("MemoizedQualifiedRef").field(&self.0.get()).finish()
    }
}

impl Clone for MemoizedQualifiedRef {
    fn clone(&self) -> Self {
        let lock = OnceLock::new();
        if let Some(val) = self.0.get() {
            let _ = lock.set(val.clone());
        }
        Self(lock)
    }
}

impl PartialEq for MemoizedQualifiedRef {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for MemoizedQualifiedRef {}

impl PartialOrd for MemoizedQualifiedRef {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for MemoizedQualifiedRef {
    fn cmp(&self, _other: &Self) -> std::cmp::Ordering {
        std::cmp::Ordering::Equal
    }
}

impl std::hash::Hash for MemoizedQualifiedRef {
    fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
}

/// Creates a deterministic `MCardRecord` from a `serde_json::Value` serialized as canonical JSON.
pub fn record_from_canonical_json(
    envelope: &Value,
    algorithm: Option<&str>,
    timestamp: Option<&str>,
) -> Result<MCardRecord, String> {
    let algo = algorithm.unwrap_or("blake3").trim().trim_end_matches(':').to_lowercase();
    let ts = timestamp.unwrap_or(DEFAULT_TIMESTAMP);
    let bytes = to_canonical_json_bytes(envelope);
    MCardRecord::create_at(&bytes, Some(&algo), Some(ts), DEFAULT_LOCALE)
}

#[inline]
fn record_algorithm_trimmed(record: &MCardRecord) -> &str {
    let seg = record.g_time.split('|').next().unwrap_or("blake3").trim();
    if seg.is_empty() { "blake3" } else { seg }
}

/// Returns the algorithm declared in `record.g_time`.
pub fn record_algorithm(record: &MCardRecord) -> String {
    let seg = record_algorithm_trimmed(record);
    if seg.is_ascii() && seg.bytes().all(|b| !b.is_ascii_uppercase()) {
        seg.to_string()
    } else {
        seg.to_lowercase()
    }
}

/// Returns the qualified `a:hex` reference for `record`.
pub fn qualified_record_hash(record: &MCardRecord) -> String {
    let algo = record_algorithm_trimmed(record);
    let raw = record.hash.split_once(':').map(|(_, h)| h).unwrap_or(record.hash.as_str());
    if algo.is_ascii() && algo.bytes().all(|b| !b.is_ascii_uppercase()) {
        let mut out = String::with_capacity(algo.len() + 1 + raw.len());
        out.push_str(algo);
        out.push(':');
        out.push_str(raw);
        out
    } else {
        format!("{}:{raw}", algo.to_lowercase())
    }
}

/// Checks whether a payload and color_type satisfy a Place type expression.
pub fn check_type_expr(payload: &Value, color_type: &str, type_expr: &str) -> bool {
    let expr = type_expr.trim().to_lowercase();
    let ctype = color_type.trim().to_lowercase();
    let norm_ctype = ctype
        .strip_prefix("clm://types/")
        .or_else(|| ctype.strip_prefix("clm://type/"))
        .unwrap_or(&ctype);
    let norm_expr = expr
        .strip_prefix("clm://types/")
        .or_else(|| expr.strip_prefix("clm://type/"))
        .unwrap_or(&expr);
    if matches!(norm_expr, "any" | "*" | "top" | "true" | "") {
        return true;
    }
    if matches!(norm_expr, "bottom" | "none" | "false" | "empty") {
        return false;
    }
    if norm_ctype == norm_expr {
        return true;
    }
    if norm_expr.ends_with("/*") || norm_expr.ends_with('/') {
        let prefix = norm_expr.trim_end_matches('*');
        return norm_ctype.starts_with(prefix);
    }
    match norm_expr {
        "int" | "integer" | "number" => payload.is_i64() || payload.is_u64() || payload.is_f64(),
        "str" | "string" | "text" => payload.is_string(),
        "dict" | "map" | "object" | "structured" => payload.is_object(),
        "list" | "array" => payload.is_array(),
        "bool" | "boolean" => payload.is_boolean(),
        _ if (norm_expr.starts_with("view/") || norm_expr.starts_with("clm://view/")) && norm_ctype == "session/active" => payload.is_object(),
        _ => false,
    }
}

/// Petri Net Token realized as an `MCardRecord` and Cordis `PrimitivePCard` (`1 -> X`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenMCard {
    /// Underlying immutable content-addressed MCard record.
    pub card: MCardRecord,
    /// Logical token identifier.
    pub token_id: String,
    /// Colour sort / type URI of the token.
    pub color_type: String,
    /// Structured JSON payload carried by the token.
    pub payload: Value,
}

impl TokenMCard {
    /// Constructs a `TokenMCard` from a JSON payload and colour sort.
    pub fn from_payload(
        payload: Value,
        color_type: &str,
        token_id: &str,
        algorithm: Option<&str>,
        timestamp: Option<&str>,
    ) -> Result<Self, String> {
        let envelope = json!({
            "color_type": color_type,
            "kind": "token_mcard",
            "payload": payload,
            "token_id": token_id,
        });
        let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
        Ok(Self {
            card,
            token_id: token_id.to_string(),
            color_type: color_type.to_string(),
            payload,
        })
    }

    /// Alias constructor for JSON token creation with default token ID.
    pub fn from_json(payload: &Value, color_type: &str, algorithm: Option<&str>) -> Result<Self, String> {
        Self::from_payload(payload.clone(), color_type, "tok_json", algorithm, None)
    }

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

    /// Alias for `qualified_hash()` used across Layer 2/3 callers.
    pub fn qualified_ref(&self) -> String {
        self.qualified_hash()
    }

    pub fn to_hash_uri(&self) -> String {
        format!("mcard://hash/{}", self.qualified_hash())
    }

    pub fn to_uri(&self) -> String {
        format!("mcard://{}", self.qualified_hash())
    }

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

    /// Reflects `TokenMCard` into a Cordis `PrimitivePCard` (`1 -> X`).
    pub fn as_primitive_pcard(&self) -> PrimitivePCard {
        let author = AgentDid::new("did:clm:layer1").unwrap_or_else(|_| AgentDid::new_unchecked("did:clm:layer1"));
        let uri = format!("mcard://{}", self.qualified_hash());
        let mcard = MCard::new(uri, MCardPayload::Structured(self.payload.clone()), author, 0);
        PrimitivePCard::new(mcard)
    }

    /// Evaluates the `TokenMCard` as a constant `1 -> X` arrow returning its payload.
    pub fn evaluate(&self) -> &Value {
        &self.payload
    }
}

/// Petri Net Place realized as an `MCardRecord` and Type Lattice `BooleanPCard` (`X -> 2`).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct PlaceMCard {
    /// Underlying immutable content-addressed MCard record.
    pub card: MCardRecord,
    /// Place identifier within the Petri Net.
    pub place_id: String,
    /// Type expression or URI guarding admission to this place.
    pub type_expr: String,
    /// Optional bounded capacity limit.
    pub capacity: Option<usize>,
    /// Structural lattice role (`InitialBottom`, `Intermediate`, `Exception`, `TerminalTop`).
    pub role: String,
    #[serde(skip, default)]
    pub cached_qualified_ref: MemoizedQualifiedRef,
}

impl PlaceMCard {
    /// Creates a default `PlaceMCard` from a place ID.
    pub fn new(id: impl Into<String>) -> Self {
        let place_id = id.into();
        Self::create(&place_id, "any", None, "Intermediate", None, None).unwrap_or_else(|_| {
            let envelope = json!({
                "capacity": Value::Null,
                "kind": "place_mcard",
                "place_id": place_id,
                "role": "Intermediate",
                "type_expr": "any",
            });
            let card = record_from_canonical_json(&envelope, None, None).unwrap();
            Self {
                card,
                place_id,
                type_expr: "any".to_string(),
                capacity: None,
                role: "Intermediate".to_string(),
                cached_qualified_ref: MemoizedQualifiedRef::default(),
            }
        })
    }

    /// Returns the place identifier.
    pub fn id(&self) -> &str {
        &self.place_id
    }

    /// Creates a deterministic `PlaceMCard` with type guard and capacity bound.
    pub fn create(
        place_id: &str,
        type_expr: &str,
        capacity: Option<usize>,
        role: &str,
        algorithm: Option<&str>,
        timestamp: Option<&str>,
    ) -> Result<Self, String> {
        let cap_val = capacity.map(|c| json!(c)).unwrap_or(Value::Null);
        let envelope = json!({
            "capacity": cap_val,
            "kind": "place_mcard",
            "place_id": place_id,
            "role": role,
            "type_expr": type_expr,
        });
        let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
        Ok(Self {
            card,
            place_id: place_id.to_string(),
            type_expr: type_expr.to_string(),
            capacity,
            role: role.to_string(),
            cached_qualified_ref: MemoizedQualifiedRef::default(),
        })
    }

    /// 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 {
        self.cached_qualified_ref
            .get_or_init(|| qualified_record_hash(&self.card))
            .to_string()
    }

    /// Alias for `qualified_hash()`.
    pub fn qualified_ref(&self) -> String {
        self.qualified_hash()
    }

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

    /// Reflects `PlaceMCard` into a Type Lattice `BooleanPCard` (`X -> 2`).
    pub fn as_boolean_pcard(&self) -> BooleanPCard {
        BooleanPCard {
            id: self.place_id.clone(),
            phase: InvariantPhase::Precondition,
            expression: self.type_expr.clone(),
            guarded_uri_pattern: format!("mcard://{}", self.qualified_hash()),
            coeffects: CordisCoeffects::default(),
        }
    }

    /// Evaluates whether `token` is admitted by this Place's type guard and capacity bound.
    pub fn evaluate_guard(&self, token: &TokenMCard, current_occupancy: usize) -> BailVerdict {
        if let Some(cap) = self.capacity {
            if current_occupancy >= cap {
                return BailVerdict::Bail {
                    reason: format!("Place '{}' capacity {} exceeded", self.place_id, cap),
                    invariant_code: "INV-508-CAP".to_string(),
                    context_dump: json!({ "place_id": self.place_id, "capacity": cap }),
                };
            }
        }
        if check_type_expr(&token.payload, &token.color_type, &self.type_expr) {
            BailVerdict::Pass
        } else {
            BailVerdict::Bail {
                reason: format!(
                    "Token '{}' (color '{}') rejected by place '{}' guard '{}'",
                    token.token_id, token.color_type, self.place_id, self.type_expr
                ),
                invariant_code: "INV-508-TYPE".to_string(),
                context_dump: json!({
                    "place_id": self.place_id,
                    "expected": self.type_expr,
                    "actual": token.color_type,
                }),
            }
        }
    }

    /// Returns true if `evaluate_guard` passes for `token` at `current_occupancy`.
    pub fn admits(&self, token: &TokenMCard, current_occupancy: usize) -> bool {
        matches!(self.evaluate_guard(token, current_occupancy), BailVerdict::Pass)
    }
}