clm-kernel 0.0.24

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

use crate::layer0::vocabulary::{HANDLE_MCARD_CHAT_MESSAGE};
#[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 mcard_json = serde_json::to_string(&msg.to_mcard())
        .map_err(|e| format!("Serialization error: {}", e))?;
    let record = crate::layer0::mcard_record::MCardRecord::create(mcard_json.as_bytes(), None)?;
    let hash = record.hash.clone();
    let handle = format!("{HANDLE_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(crate::layer0::runtime_contract::SQLITE_DDL_V3_1)
        .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();

        crate::layer2::record_store::insert_record(&conn, &record).map_err(|error| error.to_string())?;

        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::{DispatchMode, 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");
    }

    fn verified_reply(id: &str) -> serde_json::Value {
        let reply = SatoriMessage::new(id, "chan_test", "did:key:z6MkuBob", vec![SatoriElement::text("My name is Bob.")], 1720000001);
        serde_json::to_value(reply).unwrap()
    }

    fn parked(fiber_id: &str) -> (Arc<Fiber>, EventBus, DelimitedContinuation) {
        let fiber = Arc::new(Fiber::new(fiber_id, vec![]));
        let event_bus = EventBus::new();
        let continuation = DelimitedContinuation::new(fiber_id, "chan_test", "What is your name?", 5000);
        (fiber, event_bus, continuation)
    }

    #[test]
    fn a_verified_event_resumes_the_parked_fiber() {
        let (fiber, event_bus, continuation) = parked("fiber_event");
        let _unregister = park_fiber_continuation(&fiber, &event_bus, &continuation).unwrap();

        let outputs = event_bus.dispatch(&continuation.topic, verified_reply("reply_1"), DispatchMode::Waterfall).unwrap();
        assert_eq!(outputs.len(), 1);
        assert_eq!(fiber.get_state(), FiberState::Active);
        assert_eq!(continuation.resumed_message.lock().unwrap().as_ref().unwrap().id, "reply_1");
    }

    #[test]
    fn a_late_event_after_a_timeout_does_not_resume_the_fiber() {
        let (fiber, event_bus, continuation) = parked("fiber_late");
        let _unregister = park_fiber_continuation(&fiber, &event_bus, &continuation).unwrap();
        timeout_continuation(&fiber).unwrap();
        let timed_out = FiberState::Failed("Continuation timeout: disposables unwound".to_string());
        assert_eq!(fiber.get_state(), timed_out);

        let outputs = event_bus.dispatch(&continuation.topic, verified_reply("late"), DispatchMode::Waterfall).unwrap();
        assert!(outputs.is_empty(), "the timeout unregistered the listener, so no handler runs");
        assert_eq!(fiber.get_state(), timed_out);
        assert!(continuation.resumed_message.lock().unwrap().is_none());
    }

    #[test]
    fn a_late_event_after_dispose_does_not_resume_the_fiber() {
        let (fiber, event_bus, continuation) = parked("fiber_disposed");
        let unregister = park_fiber_continuation(&fiber, &event_bus, &continuation).unwrap();
        fiber.dispose().unwrap();

        let outputs = event_bus.dispatch(&continuation.topic, verified_reply("late"), DispatchMode::Waterfall).unwrap();
        assert!(outputs.is_empty());
        assert_eq!(fiber.get_state(), FiberState::Disposed);
        assert_eq!(unregister(), Ok(()), "the caller's handle is a no-op once the fiber unregistered the listener");
    }

    #[test]
    fn the_listener_surfaces_a_refused_resume() {
        let (fiber, event_bus, continuation) = parked("fiber_refused");
        let _unregister = park_fiber_continuation(&fiber, &event_bus, &continuation).unwrap();
        // Unloading without unwinding keeps the listener registered; unloading has no edge back to active.
        fiber.transition_to(FiberState::Unloading).unwrap();

        let refused = event_bus.dispatch(&continuation.topic, verified_reply("late"), DispatchMode::Waterfall).unwrap_err();
        assert!(refused.starts_with("illegal fiber transition unloading -> active"), "{refused}");
        assert_eq!(fiber.get_state(), FiberState::Unloading);
        assert!(continuation.resumed_message.lock().unwrap().is_none());
    }
}