clm-kernel 0.0.5

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Satori Message AST and Element Representations for Layer 4 Generative Hypermedia Surface.
//!
//! Provides canonical representations of chat elements across Discord, Telegram, WebSockets,
//! and CLI streams, normalized into BLAKE3 content-addressed MCard events.

use serde::{Deserialize, Serialize};

/// Canonical Satori message element types.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SatoriElement {
    #[serde(rename = "text")]
    Text {
        #[serde(alias = "content")]
        text: String,
    },
    #[serde(rename = "at")]
    At { id: String },
    #[serde(rename = "quote")]
    Quote { id: String },
    #[serde(rename = "image")]
    Image { src: String },
    #[serde(rename = "audio")]
    Audio { src: String },
    #[serde(rename = "button")]
    Button { id: String, label: String },
    #[serde(rename = "action")]
    Action { id: String },
}

impl SatoriElement {
    pub fn text(t: impl Into<String>) -> Self {
        Self::Text { text: t.into() }
    }

    pub fn at(id: impl Into<String>) -> Self {
        Self::At { id: id.into() }
    }

    pub fn quote(id: impl Into<String>) -> Self {
        Self::Quote { id: id.into() }
    }

    pub fn image(src: impl Into<String>) -> Self {
        Self::Image { src: src.into() }
    }

    pub fn audio(src: impl Into<String>) -> Self {
        Self::Audio { src: src.into() }
    }

    pub fn button(id: impl Into<String>, label: impl Into<String>) -> Self {
        Self::Button {
            id: id.into(),
            label: label.into(),
        }
    }

    pub fn action(id: impl Into<String>) -> Self {
        Self::Action { id: id.into() }
    }

    /// Serializes an element into Satori XML tag.
    pub fn to_xml(&self) -> String {
        match self {
            Self::Text { text } => format!("<text>{}</text>", escape_xml(text)),
            Self::At { id } => format!("<at id=\"{}\"/>", escape_xml(id)),
            Self::Quote { id } => format!("<quote id=\"{}\"/>", escape_xml(id)),
            Self::Image { src } => format!("<image src=\"{}\"/>", escape_xml(src)),
            Self::Audio { src } => format!("<audio src=\"{}\"/>", escape_xml(src)),
            Self::Button { id, label } => {
                format!("<button id=\"{}\" label=\"{}\"/>", escape_xml(id), escape_xml(label))
            }
            Self::Action { id } => format!("<action id=\"{}\"/>", escape_xml(id)),
        }
    }
}

/// A normalized Satori message event container.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SatoriMessage {
    pub id: String,
    pub channel_id: String,
    pub user_did: String,
    pub elements: Vec<SatoriElement>,
    pub timestamp: u64,
}

impl SatoriMessage {
    pub fn new(
        id: impl Into<String>,
        channel_id: impl Into<String>,
        user_did: impl Into<String>,
        elements: Vec<SatoriElement>,
        timestamp: u64,
    ) -> Self {
        Self {
            id: id.into(),
            channel_id: channel_id.into(),
            user_did: user_did.into(),
            elements,
            timestamp,
        }
    }

    /// Computes BLAKE3 content-address digest of canonical JSON.
    pub fn content_hash(&self) -> String {
        let serialized = serde_json::to_string(self).unwrap_or_default();
        blake3::hash(serialized.as_bytes()).to_hex().to_string()
    }

    /// Converts message to canonical MCard JSON.
    pub fn to_mcard(&self) -> serde_json::Value {
        serde_json::json!({
            "mcard_uri": format!("mcard:chat/message/{}", self.id),
            "type": "clm:types:chat:satori_message",
            "header": {
                "id": self.id,
                "channel_id": self.channel_id,
                "user_did": self.user_did,
                "timestamp": self.timestamp,
            },
            "elements": self.elements,
            "content_hash": self.content_hash(),
        })
    }

    /// Constructs SatoriMessage from MCard JSON.
    pub fn from_mcard(value: &serde_json::Value) -> Result<Self, String> {
        let header = value.get("header").ok_or("Missing header in MCard")?;
        let id = header
            .get("id")
            .and_then(|v| v.as_str())
            .ok_or("Missing id")?
            .to_string();
        let channel_id = header
            .get("channel_id")
            .and_then(|v| v.as_str())
            .ok_or("Missing channel_id")?
            .to_string();
        let user_did = header
            .get("user_did")
            .and_then(|v| v.as_str())
            .ok_or("Missing user_did")?
            .to_string();
        let timestamp = header.get("timestamp").and_then(|v| v.as_u64()).unwrap_or(0);
        let elements: Vec<SatoriElement> = if let Some(elems) = value.get("elements") {
            serde_json::from_value(elems.clone())
                .map_err(|e| format!("Invalid elements: {}", e))?
        } else {
            Vec::new()
        };

        Ok(Self {
            id,
            channel_id,
            user_did,
            elements,
            timestamp,
        })
    }

    /// Serializes whole message elements to Satori XML fragment.
    pub fn to_xml(&self) -> String {
        self.elements
            .iter()
            .map(|e| e.to_xml())
            .collect::<Vec<_>>()
            .join("")
    }
}

fn escape_xml(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}