clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Unified Spatiotemporal FND Domain Models (Sprint 190).
//!
//! Enforces:
//! 1. MCard as the Single Root Type & Spatial Carrier (s ∈ S)
//! 2. Function-Number Duality (FND): PrimitivePCard (1 -> X) vs DynamicPCard (A -> B)
//! 3. BooleanPCard as Cordis Bail Predicate (X -> 2)
//! 4. Reactive Coeffects (@Inject) and Content-Addressed BLAKE3 Hashes

use crate::satori::element::SatoriMessage;
pub use crate::types::{AgentDid, ContentHash, Handle};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// 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),
    /// Normalized Satori message speech act from Koishi conversational substrate.
    Satori(SatoriMessage),
    /// Raw binary content addressed in SQLite CAS.
    Binary {
        mime_type: String,
        data: Vec<u8>,
    },
    /// Structured JSON payload.
    Structured(serde_json::Value),
    /// Serialized executable PCard definition (Function in FND).
    Executable(Box<PCardDefinition>),
}

/// The universal immutable data entity and file system primitive.
#[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" or "mcard:chat/message/msg_101").
    pub uri: String,
    /// Digest of the exact content bytes under the algorithm declared in g_time.
    pub hash: ContentHash,
    /// Underlying data payload.
    pub payload: MCardPayload,
    /// Immutable metadata attributes.
    pub metadata: HashMap<String, serde_json::Value>,
    /// Cryptographic author DID.
    pub author: AgentDid,
    /// 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<crate::layer0::mcard_projection::MCardPreimage>,
}

pub use crate::layer0::codec::sort_json_value as canonicalize_json_value;

/// Serialize a serde_json::Value to deterministic canonical JSON bytes.
pub fn to_canonical_json_bytes(val: &serde_json::Value) -> Vec<u8> {
    crate::layer0::codec::canonical_json(val)
        .map(|s| s.into_bytes())
        .unwrap_or_default()
}

/// Serialize payload to deterministic canonical JSON bytes.
pub fn serialize_canonical_payload(payload: &MCardPayload) -> Vec<u8> {
    if let Ok(val) = serde_json::to_value(payload) {
        to_canonical_json_bytes(&val)
    } else {
        serde_json::to_vec(payload).unwrap_or_default()
    }
}

/// Compute deterministic BLAKE3 content hash over canonical JSON preimage.
pub fn compute_canonical_hash(payload: &MCardPayload) -> ContentHash {
    let bytes = serialize_canonical_payload(payload);
    ContentHash::parse(crate::layer0::hash::compute_blake3(&bytes)).expect("BLAKE3 emits a valid digest")
}

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 serialized payload.
    pub fn new(uri: impl Into<String>, payload: MCardPayload, author: AgentDid, sequence: u64) -> Self {
        let hash = compute_canonical_hash(&payload);
        Self(MCardData {
            uri: uri.into(),
            hash,
            payload,
            metadata: HashMap::new(),
            author,
            sequence,
            g_time: crate::layer0::gtime::stamp_g_time(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3, None, None, None),
            mcard_preimage_v1: None,
        })
    }

    pub fn to_record(&self) -> Result<crate::layer0::mcard_record::MCardRecord, String> {
        crate::layer0::mcard_projection::verified_record(self, self.hash.as_str(), &self.g_time,
            serialize_canonical_payload(&self.payload), self.mcard_preimage_v1.as_ref())
    }

    /// Constructs an MCard with explicit metadata.
    pub fn with_metadata(
        uri: impl Into<String>,
        payload: MCardPayload,
        metadata: HashMap<String, serde_json::Value>,
        author: AgentDid,
        sequence: u64,
    ) -> Self {
        let hash = compute_canonical_hash(&payload);
        Self(MCardData {
            uri: uri.into(),
            hash,
            payload,
            metadata,
            author,
            sequence,
            g_time: crate::layer0::gtime::stamp_g_time(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3, None, None, None),
            mcard_preimage_v1: None,
        })
    }
}

/// Cordis Coeffects: Declared dependencies required by a PCard before execution.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct CordisCoeffects {
    /// Required services in context tree (e.g., ["database", "crypto", "http"]).
    pub required_services: Vec<String>,
    /// Expected input schema URI (MCard resting state).
    pub input_schema_uri: Option<String>,
    /// Output schema URI guaranteed by successful execution.
    pub output_schema_uri: Option<String>,
    /// Authorizing agent DIDs required to activate this step.
    pub required_capabilities: Vec<String>,
}

/// Zero-coeffect constant function: 1 -> X
/// Evaluates instantaneously as an identity morphism without context resolution overhead.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrimitivePCard {
    pub mcard: MCard,
}

impl PrimitivePCard {
    pub fn new(mcard: MCard) -> Self {
        Self { mcard }
    }
    /// Evaluates to its underlying resting state.
    pub fn evaluate(&self) -> &MCard {
        &self.mcard
    }
}

/// Dynamic, effectful computation: A -> B
/// Declares reactive coeffects (@Inject) and mounts inside a Cordis Fiber.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DynamicPCard {
    pub id: String,
    /// Behavioral executable payload (WASM, Python bytecode, or AST expression).
    pub code_hash: ContentHash,
    /// Source URI for human-readable audit trail.
    pub source_uri: String,
    /// Declared Cordis coeffects.
    pub coeffects: CordisCoeffects,
    /// Pure state transition function signature.
    pub signature: String,
}

/// Verdict returned by a Boolean PCard.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BailVerdict {
    /// Predicate satisfied: proceed with pipeline.
    Pass,
    /// Predicate violated: abort pipeline and trigger LIFO rollback.
    Bail {
        reason: String,
        invariant_code: String,
        context_dump: serde_json::Value,
    },
}

/// Invariant evaluation target.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum InvariantPhase {
    /// Evaluated in Fiber LOADING state before state mutation (P in {P} S {Q}).
    Precondition,
    /// Evaluated in Fiber ACTIVE state after state mutation (Q in {P} S {Q}).
    Postcondition,
    /// Evaluated continuously during loop iterations.
    LoopInvariant,
}

/// Boolean PCard: Specialization of PCard returning Bool (X -> 2).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BooleanPCard {
    pub id: String,
    pub phase: InvariantPhase,
    /// Formal invariant predicate logic (CEL or pure AST).
    pub expression: String,
    /// Target MCard URI pattern being guarded.
    pub guarded_uri_pattern: String,
    /// Coeffects needed to evaluate the predicate.
    pub coeffects: CordisCoeffects,
}

impl BooleanPCard {
    pub fn is_precondition(&self) -> bool {
        self.phase == InvariantPhase::Precondition
    }
    pub fn is_postcondition(&self) -> bool {
        self.phase == InvariantPhase::Postcondition
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "pcard_type")]
pub enum PCardDefinition {
    Primitive(Box<PrimitivePCard>),
    Dynamic(DynamicPCard),
    Boolean(BooleanPCard),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_mcard_blake3_hash_generation() {
        let author = AgentDid::new("did:clm:agent:tester").unwrap();
        let payload = MCardPayload::Text("Hello Cordis Koishi FND".to_string());
        let mcard = MCard::new("mcard:test/msg1", payload.clone(), author.clone(), 1);

        assert_eq!(mcard.uri, "mcard:test/msg1");
        assert_eq!(mcard.author, author);
        assert_eq!(mcard.sequence, 1);
        assert_eq!(mcard.hash.as_str().len(), 64);

        // Deterministic content addressing
        let mcard2 = MCard::new("mcard:test/msg2", payload, author, 2);
        assert_eq!(mcard.hash, mcard2.hash);
    }

    #[test]
    fn test_primitive_pcard_evaluation() {
        let author = AgentDid::new("did:clm:agent:tester").unwrap();
        let payload = MCardPayload::Scalar(serde_json::json!(42));
        let mcard = MCard::new("mcard:scalar/answer", payload, author, 1);
        let primitive = PrimitivePCard::new(mcard.clone());

        assert_eq!(primitive.evaluate(), &mcard);
    }

    #[test]
    fn test_canonical_json_preimage_univalence() {
        let v1 = serde_json::json!({"z": 1, "a": 2, "m": {"y": 3, "b": 4}});
        let v2 = serde_json::json!({"a": 2, "m": {"b": 4, "y": 3}, "z": 1});
        let bytes1 = to_canonical_json_bytes(&v1);
        let bytes2 = to_canonical_json_bytes(&v2);
        assert_eq!(bytes1, bytes2);
        assert_eq!(std::str::from_utf8(&bytes1).unwrap(), "{\"a\":2,\"m\":{\"b\":4,\"y\":3},\"z\":1}");

        let v_unicode = serde_json::json!({"greeting": "Hello, δΈ–η•Œ! 🌍"});
        let bytes_u = to_canonical_json_bytes(&v_unicode);
        let str_u = std::str::from_utf8(&bytes_u).unwrap();
        assert!(!str_u.contains("\\u"));
        assert!(str_u.contains("Hello, δΈ–η•Œ! 🌍"));

        let hash = ContentHash::compute(&bytes1);
        assert_eq!(hash.as_str().len(), 64);
    }
}