clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 0: Stateless Kenotic MCard Data Entity
//! Canonical Path: kernel/clm_rust_core/src/layer0/mcard.rs

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use super::hash::compute_blake3;
use super::codec::canonical_json;

/// Content payload carried by an MCard resting state.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value")]
pub enum MCardPayload {
    /// Pure scalar or numeric primitive (Number in FND).
    Scalar(serde_json::Value),
    /// UTF-8 formatted text or markdown.
    Text(String),
    /// Raw binary content addressed in CAS.
    Binary {
        mime_type: String,
        data: Vec<u8>,
    },
    /// Structured JSON payload.
    Structured(serde_json::Value),
    /// Content-addressed URI reference.
    Uri(String),
}

/// The universal immutable data entity and file system primitive (Layer 0).
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(transparent)]
pub struct MCard(MCardData);

/// Read-only fields of a validated MCard; the owning card cannot be mutated.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MCardData {
    /// Canonical URI (e.g. "mcard:workspace/config/settings").
    pub uri: String,
    /// Digest of the exact content bytes under the algorithm declared in g_time.
    pub hash: String,
    /// Underlying data payload.
    pub payload: MCardPayload,
    /// Immutable metadata attributes.
    pub metadata: HashMap<String, serde_json::Value>,
    /// Cryptographic author DID or public identifier.
    pub author: String,
    /// Monotonic logical sequence or version counter.
    pub sequence: u64,
    pub g_time: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mcard_preimage_v1: Option<super::mcard_projection::MCardPreimage>,
}

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

impl<'de> Deserialize<'de> for MCard {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let card = Self(MCardData::deserialize(deserializer)?);
        card.to_record().map_err(serde::de::Error::custom)?;
        Ok(card)
    }
}

impl MCard {
    /// Constructs a new MCard, computing its BLAKE3 hash automatically from its canonical payload bytes.
    pub fn new(uri: impl Into<String>, payload: MCardPayload, author: impl Into<String>, sequence: u64) -> Self {
        let uri = uri.into();
        let author = author.into();
        let payload_bytes = payload_to_bytes(&payload);
        let hash = compute_blake3(&payload_bytes);
        Self(MCardData {
            uri,
            hash,
            payload,
            metadata: HashMap::new(),
            author,
            sequence,
            g_time: super::gtime::stamp_g_time(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3, None, None, None),
            mcard_preimage_v1: None,
        })
    }

    /// Constructs an MCard with explicit metadata.
    pub fn with_metadata(
        uri: impl Into<String>,
        payload: MCardPayload,
        metadata: HashMap<String, serde_json::Value>,
        author: impl Into<String>,
        sequence: u64,
    ) -> Self {
        let mut card = Self::new(uri, payload, author, sequence);
        card.0.metadata = metadata;
        card
    }

    /// Serializes payload to canonical bytes for deterministic hashing.
    pub fn payload_bytes(&self) -> Vec<u8> {
        payload_to_bytes(&self.payload)
    }

    /// Returns the verified content digest, including a stored envelope when present.
    pub fn compute_payload_hash(&self) -> String {
        self.to_record().expect("immutable verified MCard").hash
    }

    /// Returns the content digest qualified by the algorithm declared in g_time.
    pub fn compute_prefixed_hash(&self) -> String {
        let record = self.to_record().expect("immutable verified MCard");
        let super::mcard_record::RecordVerification::DeclaredOk { algorithm } =
            super::mcard_record::verify_record(&record) else { unreachable!("immutable verified MCard") };
        format!("{}:{}", algorithm, record.hash.rsplit(':').next().unwrap())
    }

    /// Verifies that self.hash correctly matches the underlying payload.
    pub fn verify_integrity(&self) -> bool {
        self.to_record().is_ok()
    }

    pub fn to_record(&self) -> Result<super::mcard_record::MCardRecord, String> {
        super::mcard_projection::verified_record(self, &self.hash, &self.g_time,
            self.payload_bytes(), self.mcard_preimage_v1.as_ref())
    }

    /// Serializes the entire MCard into canonical JSON UTF-8 bytes.
    pub fn to_canonical_bytes(&self) -> Result<Vec<u8>, String> {
        self.to_record()?;
        let json_str = canonical_json(self)?;
        Ok(json_str.into_bytes())
    }
}

/// Helper to serialize payload to deterministic bytes.
pub fn payload_to_bytes(payload: &MCardPayload) -> Vec<u8> {
    match payload {
        MCardPayload::Text(s) => s.as_bytes().to_vec(),
        MCardPayload::Binary { data, .. } => data.clone(),
        MCardPayload::Scalar(v) | MCardPayload::Structured(v) => {
            canonical_json(v).unwrap_or_else(|_| v.to_string()).into_bytes()
        }
        MCardPayload::Uri(u) => u.as_bytes().to_vec(),
    }
}