clm-kernel 0.0.24

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> {
    let algorithm = match crate::layer0::gtime::parse_g_time(g_time) {
        crate::layer0::gtime::ParsedGTime::Declared(value) => value.algorithm,
        _ => return Err("tape writes require an explicit supported algorithm in g_time".to_string()),
    };
    let record = crate::layer0::mcard_record::MCardRecord {
        hash: crate::hash::raw_hash_bytes_for(&algorithm, content)?,
        content: content.to_vec(), g_time: g_time.to_string(),
    };
    crate::layer2::record_store::insert_record(conn, &record).map_err(|error| error.to_string())?;
    Ok(record.hash)
}

/// Read a card by its content hash.
pub fn get(conn: &Connection, hash: &str) -> Result<Option<(Vec<u8>, String)>, String> {
    crate::layer2::record_store::read_record(conn, hash)
        .map(|record| record.map(|record| (record.content, record.g_time)))
        .map_err(|error| error.to_string())
}

/// Is this card on the tape? Delegates to the existing cached implementation.
pub fn has(conn: &Connection, hash: &str) -> Result<bool, String> {
    get(conn, hash).map(|record| record.is_some())
}

/// 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> {
    get(conn, hash)?.ok_or_else(|| "cannot bind a missing card".to_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 {
        // INV-594: the fixture opens the canonical tape the runtime contract generates, not a copy.
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(crate::layer0::runtime_contract::SQLITE_DDL_V3_1)
            .unwrap();
        conn
    }

    #[test]
    fn the_six_operations_are_bound_by_name() {
        let c = tape();
        let at = "blake3|2026-01-01T00:00:00Z|UTC";
        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 = "blake3|2026-01-01T00:00:00Z|UTC";
        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 = "blake3|2026-01-01T00:00:00Z|UTC";
        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 = "blake3|2026-01-01T00:00:00Z|UTC";
        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"]);
    }
}