clm-kernel 0.0.4

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! In-memory WASM storage for the three CLM database pillars.
//!
//! This is a Stage 1.2 stop-gap: it provides enough SQL semantics to run
//! `init-tridb`, `yaml-load-once`, and `memorize-mcard` inside the WASM heap
//! without pulling in `rusqlite` or a C SQLite build. It is intentionally
//! minimal — complex queries still need a real SQLite-WASM integration later.

use std::cell::RefCell;
use std::collections::HashMap;

pub type Row = HashMap<String, String>;
pub type Table = Vec<Row>;

/// In-memory database holding the three CLM pillars.
#[derive(Debug, Default, Clone)]
pub struct WasmStorage {
    pillars: HashMap<String, HashMap<String, Table>>,
}

impl WasmStorage {
    pub fn new() -> Self {
        Self::default()
    }

    /// Ensure a pillar exists.
    pub fn ensure_pillar(&mut self, pillar: &str) {
        self.pillars
            .entry(pillar.to_string())
            .or_insert_with(HashMap::new);
    }

    /// Create a table inside a pillar if it does not already exist.
    pub fn create_table(&mut self, pillar: &str, table: &str) {
        let tables = self
            .pillars
            .entry(pillar.to_string())
            .or_insert_with(HashMap::new);
        tables.entry(table.to_string()).or_insert_with(Vec::new);
    }

    /// Insert a row into a table. Columns are inferred from the row keys.
    pub fn insert(&mut self, pillar: &str, table: &str, row: Row) {
        self.create_table(pillar, table);
        self.pillars
            .get_mut(pillar)
            .unwrap()
            .get_mut(table)
            .unwrap()
            .push(row);
    }

    /// Run a tiny subset of SQL:
    /// - `SELECT * FROM table`
    /// - `SELECT count(*) FROM table`
    /// - `SELECT col1, col2 FROM table`
    pub fn query(&self, pillar: &str, sql: &str) -> Result<QueryResult, String> {
        let sql = sql.trim();
        let lower = sql.to_lowercase();
        if lower.starts_with("select count(*) from ") {
            let table = lower
                .strip_prefix("select count(*) from ")
                .unwrap()
                .trim()
                .trim_end_matches(';');
            let count = self
                .pillars
                .get(pillar)
                .and_then(|t| t.get(table))
                .map(|t| t.len())
                .unwrap_or(0);
            let mut row = HashMap::new();
            row.insert("count(*)".to_string(), count.to_string());
            return Ok(QueryResult::Rows(vec![row]));
        }
        if lower.starts_with("select * from ") {
            let table = lower
                .strip_prefix("select * from ")
                .unwrap()
                .trim()
                .trim_end_matches(';');
            let rows = self
                .pillars
                .get(pillar)
                .and_then(|t| t.get(table))
                .cloned()
                .unwrap_or_default();
            return Ok(QueryResult::Rows(rows));
        }
        if lower.starts_with("select ") && lower.contains(" from ") {
            // select col1, col2 from table
            let rest = lower.strip_prefix("select ").unwrap();
            let parts: Vec<&str> = rest.split(" from ").collect();
            if parts.len() != 2 {
                return Err(format!("unsupported SELECT: {}", sql));
            }
            let cols: Vec<String> = parts[0].split(',').map(|s| s.trim().to_string()).collect();
            let table = parts[1].trim().trim_end_matches(';');
            let all_rows = self
                .pillars
                .get(pillar)
                .and_then(|t| t.get(table))
                .cloned()
                .unwrap_or_default();
            let projected: Vec<Row> = all_rows
                .into_iter()
                .map(|r| {
                    cols.iter()
                        .filter_map(|c| r.get(c).map(|v| (c.clone(), v.clone())))
                        .collect()
                })
                .collect();
            return Ok(QueryResult::Rows(projected));
        }
        Err(format!("unsupported query: {}", sql))
    }

    /// Execute a tiny subset of DDL/DML:
    /// - `CREATE TABLE ...`
    /// - `INSERT INTO ... VALUES (...)`
    pub fn execute(&mut self, pillar: &str, sql: &str) -> Result<usize, String> {
        let sql = sql.trim();
        let lower = sql.to_lowercase();
        if lower.starts_with("create table ") {
            let name = lower
                .strip_prefix("create table ")
                .unwrap()
                .split_whitespace()
                .next()
                .unwrap()
                .trim()
                .trim_end_matches('(')
                .trim()
                .trim_end_matches(';');
            self.create_table(pillar, name);
            return Ok(0);
        }
        if lower.starts_with("insert into ") {
            // Naive parse: INSERT INTO table (c1,c2) VALUES (v1,v2);
            let rest = lower.strip_prefix("insert into ").unwrap();
            let parts: Vec<&str> = rest.splitn(2, " values ").collect();
            if parts.len() != 2 {
                return Err(format!("unsupported INSERT: {}", sql));
            }
            let table_part = parts[0].trim();
            let (table, cols) = if let Some(idx) = table_part.find('(') {
                (
                    table_part[..idx].trim(),
                    table_part[idx + 1..]
                        .trim_end_matches(')')
                        .split(',')
                        .map(|s| s.trim().to_string())
                        .collect::<Vec<_>>(),
                )
            } else {
                (table_part, vec![])
            };
            let values_part = parts[1]
                .trim()
                .trim_start_matches('(')
                .trim_end_matches(')')
                .trim_end_matches(';');
            let values: Vec<String> = values_part
                .split(',')
                .map(|s| {
                    let s = s.trim();
                    s.trim_matches('\'')
                        .trim_matches('"')
                        .to_string()
                })
                .collect();
            if cols.len() != values.len() {
                return Err(format!(
                    "column/value count mismatch in INSERT: {}",
                    sql
                ));
            }
            let row: Row = cols.into_iter().zip(values.into_iter()).collect();
            self.insert(pillar, table, row);
            return Ok(1);
        }
        Err(format!("unsupported execute: {}", sql))
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum QueryResult {
    Rows(Vec<Row>),
}

thread_local! {
    static WASM_STORAGE: RefCell<WasmStorage> = RefCell::new(WasmStorage::new());
}

/// Initialize the three CLM pillars in WASM linear memory.
pub fn init_tridb() -> Result<(), String> {
    WASM_STORAGE.with(|s| {
        let mut storage = s.borrow_mut();
        for pillar in ["agent_identities", "content_memory", "execution_log"] {
            storage.ensure_pillar(pillar);
            for table in ["card", "handle_registry", "handle_history", "schema_version"] {
                storage.create_table(pillar, table);
            }
        }
    });
    Ok(())
}

/// Run a query against the named pillar.
pub fn query(pillar: &str, sql: &str) -> Result<QueryResult, String> {
    WASM_STORAGE.with(|s| s.borrow().query(pillar, sql))
}

/// Execute DDL/DML against the named pillar.
pub fn execute(pillar: &str, sql: &str) -> Result<usize, String> {
    WASM_STORAGE.with(|s| s.borrow_mut().execute(pillar, sql))
}

/// Reset storage (useful for tests).
pub fn reset() {
    WASM_STORAGE.with(|s| {
        *s.borrow_mut() = WasmStorage::new();
    });
}

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

    #[wasm_bindgen_test]
    fn test_init_tridb_creates_pillars_and_tables() {
        reset();
        init_tridb().unwrap();
        let result = query("content_memory", "SELECT count(*) FROM card").unwrap();
        match result {
            QueryResult::Rows(rows) => {
                assert_eq!(rows.len(), 1);
                assert_eq!(rows[0].get("count(*)").unwrap(), "0");
            }
        }
    }

    #[wasm_bindgen_test]
    fn test_insert_and_select() {
        reset();
        execute(
            "content_memory",
            "INSERT INTO card (hash, content) VALUES ('abc123', 'hello')",
        )
        .unwrap();
        let result = query("content_memory", "SELECT * FROM card").unwrap();
        match result {
            QueryResult::Rows(rows) => {
                assert_eq!(rows.len(), 1);
                assert_eq!(rows[0].get("hash").unwrap(), "abc123");
                assert_eq!(rows[0].get("content").unwrap(), "hello");
            }
        }
    }

    #[wasm_bindgen_test]
    fn test_projected_select() {
        reset();
        execute(
            "content_memory",
            "INSERT INTO card (hash, content) VALUES ('abc123', 'hello')",
        )
        .unwrap();
        let result = query("content_memory", "SELECT hash FROM card").unwrap();
        match result {
            QueryResult::Rows(rows) => {
                assert_eq!(rows.len(), 1);
                assert!(rows[0].contains_key("hash"));
                assert!(!rows[0].contains_key("content"));
            }
        }
    }

    #[wasm_bindgen_test]
    fn test_benchmark_100_mcard_insertions() {
        reset();
        init_tridb().unwrap();
        let n = 100;
        let start = std::time::Instant::now();
        for i in 0..n {
            let hash = format!("hash_{:04}", i);
            let content = format!("MCard content #{}", i);
            execute(
                "content_memory",
                &format!(
                    "INSERT INTO card (hash, content, kind) VALUES ('{}', '{}', 'mcard')",
                    hash, content
                ),
            )
            .unwrap();
        }
        let elapsed = start.elapsed();
        // DoD 5: 100 MCard insertions complete in < 50ms.
        assert!(
            elapsed.as_millis() < 50,
            "100 insertions took {}ms (DoD: < 50ms)",
            elapsed.as_millis()
        );
        // Verify all 100 were inserted.
        let result = query("content_memory", "SELECT count(*) FROM card").unwrap();
        match result {
            QueryResult::Rows(rows) => {
                assert_eq!(rows[0].get("count(*)").unwrap(), "100");
            }
        }
    }
}