clm-kernel 0.0.13

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Satori Conversational Substrate and Normalization Layer.
//!
//! Exposes:
//! - Satori AST elements (`Text`, `At`, `Quote`, `Image`, `Button`, `Action`)
//! - Satori XML parser & serializer
//! - Delimited Continuations for Fiber suspension & resumption
//! - Maxwell's Demon auditing ($H^1 = 0$, $L = S_T - H_T$)
//! - MCard event ingestion pipeline

#[cfg(feature = "fiber")]
pub mod continuation;
pub mod element;
pub mod mcard_codec;
#[cfg(feature = "native")]
pub mod parser;

#[cfg(feature = "fiber")]
pub use continuation::{
    audit_maxwell_demon, park_fiber_continuation, resume_continuation, timeout_continuation,
    DelimitedContinuation, MaxwellReceipt,
};

pub use element::{SatoriElement, SatoriMessage};
pub use mcard_codec::{
    classify_speech_act, mcard_to_satori, satori_to_mcard, SatoriSpeechActType,
};
#[cfg(feature = "native")]
pub use parser::{parse_satori_message, parse_satori_xml, serialize_satori_xml};


use std::path::Path;

/// Ingests a normalized Satori message into content_memory.db as a content-addressed MCard.
#[cfg_attr(not(feature = "native"), allow(unused_variables))]
pub fn ingest_satori_message(db_path: &Path, msg: &SatoriMessage) -> Result<String, String> {
    let hash = msg.content_hash();
    let mcard_json = serde_json::to_string(&msg.to_mcard())
        .map_err(|e| format!("Serialization error: {}", e))?;
    let handle = format!("mcard:chat/message/{}", msg.id);

    // If SQLite rusqlite is available
    #[cfg(feature = "native")]
    {
        let conn = rusqlite::Connection::open(db_path)
            .map_err(|e| format!("Failed to open database '{}': {}", db_path.display(), e))?;

        conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS card (
                hash TEXT PRIMARY KEY,
                content TEXT NOT NULL,
                g_time TEXT
            );
            CREATE TABLE IF NOT EXISTS handle_registry (
                handle TEXT PRIMARY KEY,
                current_hash TEXT NOT NULL,
                updated_at TEXT NOT NULL
            );",
        )
        .map_err(|e| format!("Table creation error: {}", e))?;

        // Canonical coordinate naming the algorithm that produced `hash` (charter L2).
        let now = crate::fs_utils::compute_g_time();

        conn.execute(
            "INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
            rusqlite::params![hash, mcard_json, now],
        )
        .map_err(|e| format!("Insert card error: {}", e))?;

        conn.execute(
            "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
            rusqlite::params![handle, hash, now],
        )
        .map_err(|e| format!("Insert handle error: {}", e))?;
    }

    Ok(hash)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fiber::{EventBus, Fiber, FiberState};
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;

    #[test]
    fn test_satori_xml_parse_and_serialize() {
        let xml = "<at id=\"did:key:z6Mku123\"/><quote id=\"msg_456\"/><text>Please confirm your choice:</text><button id=\"btn_yes\" label=\"Approve\"/><action id=\"submit\"/>";
        let elements = parse_satori_xml(xml).expect("XML parse should succeed");

        assert_eq!(elements.len(), 5);
        assert_eq!(
            elements[0],
            SatoriElement::at("did:key:z6Mku123")
        );
        assert_eq!(elements[1], SatoriElement::quote("msg_456"));
        assert_eq!(
            elements[2],
            SatoriElement::text("Please confirm your choice:")
        );
        assert_eq!(
            elements[3],
            SatoriElement::button("btn_yes", "Approve")
        );
        assert_eq!(elements[4], SatoriElement::action("submit"));

        let serialized = serialize_satori_xml(&elements);
        assert!(serialized.contains("<at id=\"did:key:z6Mku123\"/>"));
        assert!(serialized.contains("<button id=\"btn_yes\" label=\"Approve\"/>"));
    }

    #[test]
    fn test_satori_mcard_conversion() {
        let elements = vec![
            SatoriElement::at("did:key:alice"),
            SatoriElement::text("Hello Cordis!"),
        ];
        let msg = SatoriMessage::new("msg_001", "chan_main", "did:key:alice", elements, 1720000000);
        let mcard = msg.to_mcard();

        assert_eq!(mcard["mcard_uri"], "mcard:chat/message/msg_001");
        assert_eq!(mcard["type"], "clm:types:chat:satori_message");

        let hash = msg.content_hash();
        assert!(!hash.is_empty());
        assert_eq!(mcard["content_hash"], hash);

        let roundtrip = SatoriMessage::from_mcard(&mcard).expect("MCard deserialization should succeed");
        assert_eq!(roundtrip.id, "msg_001");
        assert_eq!(roundtrip.elements.len(), 2);
    }

    #[test]
    fn test_delimited_continuation_park_and_resume() {
        let fiber = Arc::new(Fiber::new("fiber_dialogue_1", vec![]));
        assert_eq!(fiber.get_state(), FiberState::Active);

        let event_bus = EventBus::new();
        let continuation = DelimitedContinuation::new("fiber_dialogue_1", "chan_test", "What is your name?", 5000);

        // Park fiber awaiting user response
        let _unreg = park_fiber_continuation(&fiber, &event_bus, &continuation)
            .expect("Fiber should park cleanly");
        assert_eq!(fiber.get_state(), FiberState::Suspended);

        // Simulate incoming verified user Satori message
        let user_reply = SatoriMessage::new(
            "reply_1",
            "chan_test",
            "did:key:z6MkuBob",
            vec![SatoriElement::text("My name is Bob.")],
            1720000001,
        );

        let receipt = resume_continuation(&fiber, &continuation, user_reply)
            .expect("Resume continuation should succeed");

        assert!(receipt.verified);
        assert_eq!(receipt.cohomology_h1, 0);
        assert_eq!(receipt.lagrangian_delta, 1);
        assert_eq!(fiber.get_state(), FiberState::Active);

        let stored = continuation.resumed_message.lock().unwrap();
        assert!(stored.is_some());
        assert_eq!(stored.as_ref().unwrap().id, "reply_1");
    }

    #[test]
    fn test_maxwells_demon_rejects_hallucination() {
        // Message with forbidden hallucinated synthetic content
        let bad_msg = SatoriMessage::new(
            "msg_hallucinated",
            "chan_test",
            "did:key:alice",
            vec![SatoriElement::text("Here is false data: [HALLUCINATED] fictitious token")],
            1720000000,
        );

        let receipt = audit_maxwell_demon(&bad_msg).expect("Audit should complete");
        assert!(!receipt.verified);
        assert_eq!(receipt.cohomology_h1, 1); // Obstruction class H^1 != 0
        assert_eq!(receipt.lagrangian_delta, -1);
        assert!(receipt.rejection_reason.unwrap().contains("H^1 != 0"));
    }

    #[test]
    fn test_continuation_timeout_unwind_disposables() {
        let fiber = Arc::new(Fiber::new("fiber_timeout_test", vec![]));
        let flag = Arc::new(AtomicBool::new(false));
        let flag_clone = flag.clone();

        fiber.register_disposable(move || {
            flag_clone.store(true, Ordering::SeqCst);
            Ok(())
        });

        // Suspend fiber
        fiber.suspend().unwrap();
        assert_eq!(fiber.get_state(), FiberState::Suspended);

        // Trigger timeout
        timeout_continuation(&fiber).expect("Timeout should execute cleanly");

        assert_eq!(
            fiber.get_state(),
            FiberState::Failed("Continuation timeout: disposables unwound".to_string())
        );
        // Disposable executed
        assert!(flag.load(Ordering::SeqCst), "Fiber disposables must be cleanly unwound on timeout");
    }
}