clm-kernel 0.0.12

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! The Universal Tape Interface — the Rust binding (ORC-IV).
//!
//! The interface is declared once in `registry/tape-driver-interface.yaml`. This is Rust's
//! binding of it: the six declared operations, **by the declared names**.
//!
//! WHY THIS MODULE EXISTS. `db.rs` already does all of this — but under a PARALLEL
//! VOCABULARY: `get_card_content`, `card_exists_cached`, `resolve_handle_hash_cached`. The
//! `ORC-IV` item says the runtimes must reach the tape "through the single universal tape
//! interface", and a parallel vocabulary is a SECOND interface: a reader cannot tell that
//! `card_exists_cached` and `has` are the same operation. `check_tape_driver.py` measured
//! Rust at **0/6 by name**.
//!
//! So this is a BINDING, not a rewrite — the same shape as `kindOf` bound in three runtimes.
//! The existing functions keep their names and their callers; the declared names are added
//! on top, delegating where an implementation already exists.
//!
//! Six operations over three tables — the same 3 x 3 shape as the schema.

use rusqlite::{params, Connection};

/// The three tables. Named here so a fourth cannot appear by accident (TD-01).
pub const CORE_TABLES: [&str; 3] = ["card", "handle_registry", "handle_history"];

/// Store an immutable card. Content-addressed: identical bytes write nothing (TD-02).
pub fn put(conn: &Connection, content: &[u8], g_time: &str) -> Result<String, String> {
    use crate::layer0::mcard_record::{verify_record, MCardRecord, RecordVerification};

    let record = if g_time.contains('|') {
        let algorithm = g_time.split('|').next().unwrap_or_default();
        let hash = crate::hash::raw_hash_bytes_for(algorithm, content)?;
        MCardRecord {
            hash,
            content: content.to_vec(),
            g_time: g_time.to_string(),
        }
    } else if g_time.starts_with("a:") {
        let mut fields = std::collections::HashMap::new();
        for segment in g_time.split(';') {
            let Some((key, value)) = segment.split_once(':') else {
                return Err("invalid legacy TypeScript g_time".to_string());
            };
            if fields.insert(key, value).is_some() {
                return Err("duplicate legacy TypeScript g_time key".to_string());
            }
        }
        let algorithm = fields.get("a").copied().unwrap_or_default();
        let timestamp = fields.get("t").copied().unwrap_or_default();
        let locale = fields.get("c").copied().unwrap_or("UTC");
        MCardRecord::create_at(content, Some(algorithm), Some(timestamp), locale)?
    } else {
        MCardRecord::create_at(content, None, Some(g_time), "UTC")?
    };

    if !matches!(verify_record(&record), RecordVerification::DeclaredOk { .. }) {
        return Err("refusing tape write with mismatched hash and g_time".to_string());
    }
    conn.execute(
        "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
        params![record.hash, record.content, record.g_time],
    )
    .map_err(|e| format!("put failed: {e}"))?;
    Ok(record.hash)
}

/// Read a card by its content hash.
pub fn get(conn: &Connection, hash: &str) -> Result<Option<(Vec<u8>, String)>, String> {
    conn.query_row(
        "SELECT content, g_time FROM card WHERE hash = ?1",
        params![hash],
        |row| Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, String>(1)?)),
    )
    .map(Some)
    .or_else(|e| match e {
        rusqlite::Error::QueryReturnedNoRows => Ok(None),
        other => Err(format!("get failed: {}", other)),
    })
}

/// Is this card on the tape? Delegates to the existing cached implementation.
pub fn has(conn: &Connection, hash: &str) -> Result<bool, String> {
    crate::db::card_exists_cached(conn, hash).map_err(|e| format!("has failed: {}", e))
}

/// How many cards the tape holds.
pub fn count(conn: &Connection) -> Result<i64, String> {
    conn.query_row("SELECT COUNT(*) FROM card", [], |r| r.get(0))
        .map_err(|e| format!("count failed: {}", e))
}

/// Bind a handle to a card, appending a history row ONLY when the binding MOVES (TD-03/04).
///
/// Returns `true` when a transition was recorded. A no-op binding records nothing: a history
/// row means the pointer moved, and a no-op move is a recorded lie.
pub fn register_handle(conn: &Connection, handle: &str, hash: &str, at: &str) -> Result<bool, String> {
    let current: Option<String> = conn
        .query_row(
            "SELECT current_hash FROM handle_registry WHERE handle = ?1",
            params![handle],
            |r| r.get(0),
        )
        .ok();
    match current {
        None => {
            conn.execute(
                "INSERT INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
                params![handle, hash, at],
            )
            .map_err(|e| format!("register_handle failed: {}", e))?;
            conn.execute(
                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
                params![handle, hash, at],
            )
            .map_err(|e| format!("register_handle history failed: {}", e))?;
            Ok(true)
        }
        Some(prev) if prev != hash => {
            conn.execute(
                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
                params![handle, prev, at],
            )
            .map_err(|e| format!("register_handle history failed: {}", e))?;
            conn.execute(
                "UPDATE handle_registry SET current_hash = ?1, updated_at = ?2 WHERE handle = ?3",
                params![hash, at, handle],
            )
            .map_err(|e| format!("register_handle update failed: {}", e))?;
            Ok(true)
        }
        Some(_) => Ok(false),
    }
}

/// Resolve a handle to its current card. Delegates to the existing cached implementation.
pub fn resolve_handle(conn: &Connection, handle: &str) -> Result<Option<String>, String> {
    crate::db::resolve_handle_hash_cached(conn, handle)
        .map_err(|e| format!("resolve_handle failed: {}", e))
}

/// The transitions a handle has made, oldest first.
///
/// Ordered by `rowid` — which is why `id` is not a column. This IS the revision record:
/// `created_at` is its first entry, which is why `created_at` is not a column either.
pub fn handle_history(conn: &Connection, handle: &str) -> Result<Vec<String>, String> {
    let mut stmt = conn
        .prepare("SELECT previous_hash FROM handle_history WHERE handle = ?1 ORDER BY rowid ASC")
        .map_err(|e| format!("handle_history prepare failed: {}", e))?;
    let rows = stmt
        .query_map(params![handle], |r| r.get::<_, String>(0))
        .map_err(|e| format!("handle_history failed: {}", e))?;
    rows.collect::<rusqlite::Result<Vec<String>>>()
        .map_err(|e| format!("handle_history read failed: {}", e))
}

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

    fn tape() -> Connection {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            "CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
             CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, updated_at TEXT NOT NULL);
             CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
        )
        .unwrap();
        conn
    }

    #[test]
    fn the_six_operations_are_bound_by_name() {
        let c = tape();
        let at = "2026-01-01T00:00:00Z";
        let h = put(&c, b"alpha", at).unwrap();
        assert_eq!(count(&c).unwrap(), 1);
        assert!(has(&c, &h).unwrap());
        assert_eq!(get(&c, &h).unwrap().unwrap().0, b"alpha");
        assert!(register_handle(&c, "urn:mcard:mcard:content:x", &h, at).unwrap());
        assert_eq!(resolve_handle(&c, "urn:mcard:mcard:content:x").unwrap().unwrap(), h);
        assert_eq!(handle_history(&c, "urn:mcard:mcard:content:x").unwrap().len(), 1);
    }

    #[test]
    fn td02_identical_content_writes_nothing() {
        let c = tape();
        let at = "2026-01-01T00:00:00Z";
        put(&c, b"alpha", at).unwrap();
        put(&c, b"alpha", at).unwrap();
        assert_eq!(count(&c).unwrap(), 1, "content addressing IS the identity");
    }

    #[test]
    fn td03_a_noop_binding_records_nothing() {
        let c = tape();
        let at = "2026-01-01T00:00:00Z";
        let h = put(&c, b"alpha", at).unwrap();
        register_handle(&c, "urn:mcard:mcard:content:x", &h, at).unwrap();
        assert!(!register_handle(&c, "urn:mcard:mcard:content:x", &h, at).unwrap());
        assert_eq!(handle_history(&c, "urn:mcard:mcard:content:x").unwrap().len(), 1);
    }

    #[test]
    fn td04_a_move_appends_exactly_one_row() {
        let c = tape();
        let at = "2026-01-01T00:00:00Z";
        let a = put(&c, b"alpha", at).unwrap();
        let b = put(&c, b"bravo", at).unwrap();
        register_handle(&c, "urn:mcard:mcard:content:x", &a, at).unwrap();
        register_handle(&c, "urn:mcard:mcard:content:x", &b, at).unwrap();
        assert_eq!(handle_history(&c, "urn:mcard:mcard:content:x").unwrap().len(), 2);
    }

    #[test]
    fn td01_exactly_three_tables() {
        let c = tape();
        let mut stmt = c
            .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
            .unwrap();
        let tables: Vec<String> = stmt.query_map([], |r| r.get(0)).unwrap().map(|r| r.unwrap()).collect();
        assert_eq!(tables, vec!["card", "handle_history", "handle_registry"]);
    }
}