clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Versioned Schema Migrations for SQLite Tri-Database Pillars.
//!
//! Provides deterministic schema initialization conforming to INV-TAPE-01:
//! Three tables (card, handle_registry, handle_history), three columns each.
//! All auxiliary tables have been eliminated (INV-TAPE-01 / ORC-23 / ORC-26).

use crate::error::{ClmError, StorageErrorCode, Result};
use rusqlite::Connection;

/// Represents a versioned schema migration step.
pub struct Migration {
    pub version: i64,
    pub description: &'static str,
    pub sql_up: &'static str,
}

/// Baseline migration 1: The Monadic Core (card, handle_registry, handle_history).
///
/// INV-TAPE-01: three tables, three columns each. The kind is not a column (INV-TAPE-01a): the
/// handle names it and `kindOf` decides it. Lifecycle is external (INV-TAPE-04): tombstones and
/// their reasons live in a sidecar tape, not in a `change_type` column or a `card_tombstone` table.
/// The DDL is generated from `schema/mcard_schema.sql` into the runtime contract (INV-594).
pub const MIGRATION_1_BASELINE: Migration = Migration {
    version: 1,
    description: "Baseline Monadic Core Schema (card, handle_registry, handle_history)",
    sql_up: crate::layer0::runtime_contract::SQLITE_DDL_V3_1,
};

/// Applies the canonical baseline schema (INV-TAPE-01) to the given database connection.
pub fn apply_migrations(conn: &mut Connection, _pillar: &str) -> Result<()> {
    // If handle_registry already exists with legacy created_at column (pre-v4.0.0 Triad),
    // drop it to conform to INV-TAPE-01 (3 tables, 3 columns each).
    let table_name = "handle_registry";
    let col_name = "created_at";
    let check_sql = format!(
        "SELECT count(*) > 0 FROM pragma_table_info('{}') WHERE name = '{}'",
        table_name, col_name
    );
    let has_created_at: bool = conn
        .query_row(&check_sql, [], |r| r.get(0))
        .unwrap_or(false);
    if has_created_at {
        let _ = conn.execute_batch("ALTER TABLE handle_registry DROP COLUMN created_at;");
    }

    conn.execute_batch(MIGRATION_1_BASELINE.sql_up).map_err(|e| {
        ClmError::storage(
            StorageErrorCode::InvalidSchemaVersion,
            format!("Failed to initialize baseline Monadic Core schema: {}", e),
        )
    })?;
    Ok(())
}

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

    #[test]
    fn test_migrations_apply_baseline() {
        let mut conn = Connection::open_in_memory().unwrap();
        apply_migrations(&mut conn, "content_memory").unwrap();

        // Verify card table exists
        let count: i64 = conn
            .query_row("SELECT count(*) FROM card", [], |r| r.get(0))
            .unwrap();
        assert_eq!(count, 0);

        // Verify no auxiliary tables were created (INV-TAPE-01)
        let aux_exists: bool = conn
            .query_row(
                "SELECT count(*) > 0 FROM sqlite_master WHERE type='table' AND name='_clm_schema_migrations'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert!(!aux_exists);
    }
}