clm-kernel 0.0.1

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, prefixed_hash, verify_hash};
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, Deserialize)]
pub struct MCard {
    /// Canonical URI (e.g. "mcard:workspace/config/settings").
    pub uri: String,
    /// Cryptographic BLAKE3 hash of canonical serialized payload.
    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,
}

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 {
            uri,
            hash,
            payload,
            metadata: HashMap::new(),
            author,
            sequence,
        }
    }

    /// 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.metadata = metadata;
        card
    }

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

    /// Recomputes payload hash using BLAKE3.
    pub fn compute_payload_hash(&self) -> String {
        compute_blake3(&self.payload_bytes())
    }

    /// Recomputes prefixed hash ("blake3:<hex>").
    pub fn compute_prefixed_hash(&self) -> String {
        prefixed_hash(&self.payload_bytes())
    }

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

    /// Serializes the entire MCard into canonical JSON UTF-8 bytes.
    pub fn to_canonical_bytes(&self) -> Result<Vec<u8>, String> {
        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(),
    }
}