clm-kernel 0.0.4

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Reticulum Satori Binary AST Transducer for CLM Layer 3 Mesh.
//! Canonical Path: kernel/clm_rust_core/src/mesh/reticulum_satori.rs
//!
//! Implements:
//! - Low-overhead binary encoding/decoding for Satori AST elements (INV-L3-RET-357-01)
//! - Cryptographic delivery receipts (INV-L3-RET-357-02)
//! - Multi-media MCard reference extraction for pre-event CAS ingestion (INV-L3-RET-357-03)

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use thiserror::Error;

#[derive(Error, Debug)]
pub enum ReticulumSatoriError {
    #[error("Frame too short")]
    FrameTooShort,

    #[error("Malformed attribute or child framing")]
    MalformedFraming,

    #[error("JSON error: {0}")]
    JsonError(#[from] serde_json::Error),
}

pub const OP_TEXT: u8 = 0x01;
pub const OP_AT: u8 = 0x02;
pub const OP_QUOTE: u8 = 0x03;
pub const OP_IMAGE: u8 = 0x04;
pub const OP_AUDIO: u8 = 0x05;
pub const OP_VIDEO: u8 = 0x06;
pub const OP_BUTTON: u8 = 0x07;
pub const OP_ACTION: u8 = 0x08;
pub const OP_CARD: u8 = 0x09;
pub const OP_EXECUTE: u8 = 0x0A;
pub const OP_WITNESS: u8 = 0x0B;
pub const OP_CUSTOM: u8 = 0x0C;
pub const OP_MESSAGE: u8 = 0x10;

pub fn opcode_from_type(t: &str) -> u8 {
    match t {
        "text" => OP_TEXT,
        "at" => OP_AT,
        "quote" => OP_QUOTE,
        "image" => OP_IMAGE,
        "audio" => OP_AUDIO,
        "video" => OP_VIDEO,
        "button" => OP_BUTTON,
        "action" => OP_ACTION,
        "card" => OP_CARD,
        "execute" => OP_EXECUTE,
        "witness" => OP_WITNESS,
        "message" => OP_MESSAGE,
        _ => OP_CUSTOM,
    }
}

pub fn type_from_opcode(op: u8) -> &'static str {
    match op {
        OP_TEXT => "text",
        OP_AT => "at",
        OP_QUOTE => "quote",
        OP_IMAGE => "image",
        OP_AUDIO => "audio",
        OP_VIDEO => "video",
        OP_BUTTON => "button",
        OP_ACTION => "action",
        OP_CARD => "card",
        OP_EXECUTE => "execute",
        OP_WITNESS => "witness",
        OP_MESSAGE => "message",
        _ => "custom",
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SatoriBinaryElement {
    #[serde(rename = "type")]
    pub element_type: String,
    #[serde(default)]
    pub attrs: serde_json::Map<String, serde_json::Value>,
    #[serde(default)]
    pub children: Vec<SatoriBinaryElement>,
}

/// Encodes Satori AST node into compact binary frame.
/// Framing: [1B opcode][2B attrLen BE][attrBytes][2B childCount BE][children...]
pub fn encode_satori_binary(node: &SatoriBinaryElement) -> Vec<u8> {
    let opcode = opcode_from_type(&node.element_type);
    let attr_bytes = serde_json::to_vec(&node.attrs).unwrap_or_default();
    let encoded_children: Vec<Vec<u8>> = node
        .children
        .iter()
        .map(encode_satori_binary)
        .collect();

    let children_len: usize = encoded_children.iter().map(|c| c.len()).sum();
    let mut out = Vec::with_capacity(1 + 2 + attr_bytes.len() + 2 + children_len);

    out.push(opcode);
    let attr_len = attr_bytes.len() as u16;
    out.extend_from_slice(&attr_len.to_be_bytes());
    out.extend_from_slice(&attr_bytes);

    let child_count = node.children.len() as u16;
    out.extend_from_slice(&child_count.to_be_bytes());

    for child in encoded_children {
        out.extend_from_slice(&child);
    }

    out
}

/// Decodes binary frame into Satori AST node.
pub fn decode_satori_binary(buf: &[u8]) -> Result<SatoriBinaryElement, ReticulumSatoriError> {
    let (node, _) = decode_satori_binary_with_length(buf, 0)?;
    Ok(node)
}

pub fn decode_satori_binary_with_length(
    buf: &[u8],
    start_offset: usize,
) -> Result<(SatoriBinaryElement, usize), ReticulumSatoriError> {
    let mut offset = start_offset;
    if buf.len() - offset < 5 {
        return Err(ReticulumSatoriError::FrameTooShort);
    }

    let opcode = buf[offset];
    offset += 1;

    let attr_len = u16::from_be_bytes([buf[offset], buf[offset + 1]]) as usize;
    offset += 2;

    if buf.len() < offset + attr_len + 2 {
        return Err(ReticulumSatoriError::MalformedFraming);
    }

    let attr_bytes = &buf[offset..offset + attr_len];
    offset += attr_len;

    let attrs: serde_json::Map<String, serde_json::Value> = serde_json::from_slice(attr_bytes)?;

    let child_count = u16::from_be_bytes([buf[offset], buf[offset + 1]]) as usize;
    offset += 2;

    let mut children = Vec::with_capacity(child_count);
    for _ in 0..child_count {
        if offset >= buf.len() {
            return Err(ReticulumSatoriError::MalformedFraming);
        }
        let (child_node, child_bytes_read) = decode_satori_binary_with_length(buf, offset)?;
        children.push(child_node);
        offset += child_bytes_read;
    }

    let total_bytes_read = offset - start_offset;
    let element_type = type_from_opcode(opcode).to_string();
    Ok((
        SatoriBinaryElement {
            element_type,
            attrs,
            children,
        },
        total_bytes_read,
    ))
}

/// Computes unforgeable cryptographic delivery receipt token (INV-L3-RET-357-02).
pub fn compute_receipt_token(message_bytes: &[u8], link_id: &[u8; 16]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(message_bytes);
    let msg_hash = hasher.finalize();

    let mut receipt_hasher = Sha256::new();
    receipt_hasher.update(msg_hash);
    receipt_hasher.update(link_id);
    hex::encode(receipt_hasher.finalize())
}

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

    #[test]
    fn test_satori_ast_roundtrip() {
        let mut attrs = serde_json::Map::new();
        attrs.insert("text".to_string(), serde_json::Value::String("Rust native speech act".to_string()));

        let child = SatoriBinaryElement {
            element_type: "text".to_string(),
            attrs,
            children: Vec::new(),
        };

        let mut root_attrs = serde_json::Map::new();
        root_attrs.insert("id".to_string(), serde_json::Value::String("turn-rust-01".to_string()));

        let root = SatoriBinaryElement {
            element_type: "message".to_string(),
            attrs: root_attrs,
            children: vec![child],
        };

        let encoded = encode_satori_binary(&root);
        let decoded = decode_satori_binary(&encoded).unwrap();

        assert_eq!(decoded.element_type, "message");
        assert_eq!(decoded.children.len(), 1);
        assert_eq!(decoded.children[0].element_type, "text");
        assert_eq!(
            decoded.children[0].attrs.get("text").unwrap().as_str().unwrap(),
            "Rust native speech act"
        );
    }
}