clm-kernel 0.0.1

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! MCard Universal Virtual Filesystem Engine (Sprint 191).
//!
//! Enforces:
//! 1. Zero-FS Hermeticity (INV-09): Operates in-memory or on SQLite CAS without host disk I/O.
//! 2. Handle Registry Singularity (INV-04) & Tri-Database Separation (INV-05):
//!    Directly wraps canonical `card`, `handle_registry`, and `handle_history` tables.
//! 3. Content-Addressable Identity (INV-02): BLAKE3 hashes for all MCard payloads.
//! 4. Spatiotemporal Compositionality: Mountable in Cordis Context for scoped fiber execution.

use crate::domain::{MCard, MCardPayload};
use crate::error::{ClmError, Result, StorageErrorCode};
use crate::types::{AgentDid, ContentHash};
use rusqlite::{params, Connection};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};

/// File metadata stat for an MCard in the virtual filesystem.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MCardStat {
    pub uri: String,
    pub hash: ContentHash,
    pub size_bytes: usize,
    pub created_at: String,
    pub updated_at: String,
}

/// The universal immutable filesystem engine mapping URIs to content-addressed MCards.
#[derive(Clone)]
pub struct MCardFileSystem {
    conn: Arc<Mutex<Connection>>,
    context_prefix: String,
}

impl MCardFileSystem {
    /// Initializes an isolated, zero-disk in-memory MCard filesystem (INV-09).
    pub fn new_in_memory() -> Result<Self> {
        let conn = Connection::open_in_memory()?;
        Self::init_schema(&conn)?;
        Ok(Self {
            conn: Arc::new(Mutex::new(conn)),
            context_prefix: String::new(),
        })
    }

    /// Initializes an in-memory MCard filesystem scoped to a specific context prefix.
    pub fn new_in_memory_scoped(prefix: &str) -> Result<Self> {
        let mut fs = Self::new_in_memory()?;
        fs.context_prefix = prefix.trim_matches('/').to_string();
        Ok(fs)
    }

    /// Wraps an existing SQLite connection manager or shared connection with an optional context prefix.
    pub fn new(conn: Arc<Mutex<Connection>>, context_prefix: &str) -> Self {
        Self {
            conn,
            context_prefix: context_prefix.trim_matches('/').to_string(),
        }
    }

    /// Wraps an existing SQLite connection manager or shared connection (root prefix).
    pub fn with_connection(conn: Arc<Mutex<Connection>>) -> Result<Self> {
        {
            let locked = conn
                .lock()
                .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
            Self::init_schema(&locked)?;
        }
        Ok(Self {
            conn,
            context_prefix: String::new(),
        })
    }

    /// Returns a new `MCardFileSystem` handle sharing the same storage but isolated to `prefix`.
    pub fn with_prefix(&self, prefix: &str) -> Self {
        Self {
            conn: self.conn.clone(),
            context_prefix: prefix.trim_matches('/').to_string(),
        }
    }

    /// Returns the active context prefix for this filesystem handle.
    pub fn context_prefix(&self) -> &str {
        &self.context_prefix
    }

    /// Resolves canonical URI with context prefix scoping (DOD-191-04).
    pub fn canonicalize_uri(&self, path: &str) -> String {
        let clean = path.trim_start_matches('/');
        if let Some(rest) = clean.strip_prefix("mcard:") {
            let rest_clean = rest.trim_start_matches('/');
            if self.context_prefix.is_empty() {
                format!("mcard:{}", rest_clean)
            } else if rest_clean.starts_with(&self.context_prefix) {
                format!("mcard:{}", rest_clean)
            } else {
                format!("mcard:{}/{}", self.context_prefix, rest_clean)
            }
        } else if self.context_prefix.is_empty() {
            format!("mcard:{}", clean)
        } else {
            format!("mcard:{}/{}", self.context_prefix, clean)
        }
    }

    /// Ephemerally mounts a scoped MCardFileSystem on a Fiber, registering a LIFO unmount
    /// callback on the fiber's DisposableList that cleans up all transient handles on disposal (DOD-191-07).
    pub fn ephemeral_mount(&self, fiber: &crate::fiber::context::Fiber, prefix: &str) -> Result<Self> {
        let scoped_fs = self.with_prefix(prefix);
        let prefix_clean = prefix.trim_matches('/').to_string();
        let handle_pattern = if prefix_clean.is_empty() {
            "mcard:%".to_string()
        } else {
            format!("mcard:{}/%", prefix_clean)
        };
        let conn_clone = self.conn.clone();

        fiber.register_disposable(move || {
            let conn = conn_clone.lock().map_err(|e| e.to_string())?;
            conn.execute(
                "DELETE FROM handle_registry WHERE handle LIKE ?1",
                rusqlite::params![&handle_pattern],
            )
            .map_err(|e| e.to_string())?;
            Ok(())
        });

        Ok(scoped_fs)
    }

    /// Ensures the canonical Tri-Database schema exists (INV-04, INV-05).
    fn init_schema(conn: &Connection) -> Result<()> {
        conn.execute_batch(
            r#"
            CREATE TABLE IF NOT EXISTS card (
                hash TEXT PRIMARY KEY,
                content TEXT NOT NULL,
                g_time TEXT
            );

            CREATE TABLE IF NOT EXISTS handle_registry (
                handle TEXT PRIMARY KEY,
                current_hash TEXT NOT NULL,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL
            );

            CREATE TABLE IF NOT EXISTS handle_history (
                handle TEXT NOT NULL,
                previous_hash TEXT NOT NULL,
                changed_at TEXT NOT NULL
            );

            CREATE INDEX IF NOT EXISTS idx_handle_reg_prefix ON handle_registry(handle);
            "#,
        )?;
        Ok(())
    }

    /// Writes an MCard into the filesystem, content-addressing the payload and updating the handle registry.
    pub fn write_file(&self, uri: &str, payload: MCardPayload, author: AgentDid) -> Result<MCard> {
        let canonical_uri = self.canonicalize_uri(uri);
        let now = crate::utils::now_iso8601();
        let mut conn = self
            .conn
            .lock()
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;

        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;

        // 1. Check existing handle state to maintain sequence and created_at
        let existing: Option<(String, String)> = {
            let mut stmt = tx.prepare_cached(
                "SELECT current_hash, created_at FROM handle_registry WHERE handle = ?1",
            )?;
            stmt.query_row(params![&canonical_uri], |row| Ok((row.get(0)?, row.get(1)?)))
                .ok()
        };

        let (seq, created_at) = match &existing {
            Some((_, ca)) => {
                // Determine next sequence from history count
                let mut count_stmt = tx.prepare_cached(
                    "SELECT count(*) FROM handle_history WHERE handle = ?1",
                )?;
                let count: i64 = count_stmt.query_row(params![&canonical_uri], |row| row.get(0))?;
                ((count as u64) + 2, ca.clone())
            }
            None => (1, now.clone()),
        };

        // 2. Construct canonical MCard & serialize
        let mcard = MCard::new(&canonical_uri, payload, author, seq);
        let serialized_card = serde_json::to_string(&mcard)?;
        let hash_str = mcard.hash.as_str();

        // 3. Insert CAS card blob (INV-02, INV-05)
        {
            let mut stmt_card = tx.prepare_cached(
                "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
            )?;
            stmt_card.execute(params![hash_str, serialized_card, now])?;
        }

        // 4. Update handle history if previous hash exists and differs (G-Set tracking)
        if let Some((prev_hash, _)) = existing.as_ref().filter(|(prev, _)| prev != hash_str) {
            let mut stmt_hist = tx.prepare_cached(
                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
            )?;
            stmt_hist.execute(params![&canonical_uri, prev_hash, now])?;
        }

        // 5. Update or insert handle registry entry (INV-04)
        {
            let mut stmt_reg = tx.prepare_cached(
                "INSERT OR REPLACE INTO handle_registry (handle, current_hash, created_at, updated_at) \
                 VALUES (?1, ?2, ?3, ?4)",
            )?;
            stmt_reg.execute(params![&canonical_uri, hash_str, created_at, now])?;
        }

        tx.commit()?;
        Ok(mcard)
    }

    /// Reads and cryptographically verifies an MCard by its URI handle (INV-02, INV-04).
    pub fn read_file(&self, uri: &str) -> Result<MCard> {
        let canonical_uri = self.canonicalize_uri(uri);
        let conn = self
            .conn
            .lock()
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;

        // 1. Resolve handle to current hash
        let current_hash: String = {
            let mut stmt = conn.prepare_cached(
                "SELECT current_hash FROM handle_registry WHERE handle = ?1",
            )?;
            stmt.query_row(params![&canonical_uri], |row| row.get(0)).map_err(|_| {
                ClmError::storage(
                    StorageErrorCode::CardNotFound,
                    format!("Handle '{}' not found in MCardFs", canonical_uri),
                )
            })?
        };

        // 2. Fetch CAS card content
        let content: String = {
            let mut stmt = conn.prepare_cached("SELECT content FROM card WHERE hash = ?1")?;
            stmt.query_row(params![current_hash], |row| row.get(0))
                .map_err(|_| {
                    ClmError::storage(
                        StorageErrorCode::CorruptedContent,
                        format!("Card content for hash '{}' not found", current_hash),
                    )
                })?
        };

        // 3. Deserialize and verify zero-trust cryptographic identity
        let mcard: MCard = serde_json::from_str(&content)?;
        let expected_payload_bytes = serde_json::to_vec(&mcard.payload)?;
        let expected_hash = ContentHash::compute(&expected_payload_bytes);

        if expected_hash.as_str() != current_hash {
            return Err(ClmError::storage(
                StorageErrorCode::CorruptedContent,
                format!(
                    "Cryptographic mismatch for handle '{}': registry={} computed={}",
                    canonical_uri, current_hash, expected_hash
                ),
            ));
        }

        Ok(mcard)
    }

    /// Checks if an MCard exists by its handle URI.
    pub fn exists(&self, uri: &str) -> Result<bool> {
        let canonical_uri = self.canonicalize_uri(uri);
        let conn = self
            .conn
            .lock()
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
        let mut stmt = conn.prepare_cached(
            "SELECT count(*) FROM handle_registry WHERE handle = ?1",
        )?;
        let count: i64 = stmt.query_row(params![&canonical_uri], |row| row.get(0))?;
        Ok(count > 0)
    }

    /// Returns stat metadata for a virtual file.
    pub fn stat_file(&self, uri: &str) -> Result<MCardStat> {
        let canonical_uri = self.canonicalize_uri(uri);
        let conn = self
            .conn
            .lock()
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;

        let (hash_str, created_at, updated_at): (String, String, String) = {
            let mut stmt = conn.prepare_cached(
                "SELECT current_hash, created_at, updated_at FROM handle_registry WHERE handle = ?1",
            )?;
            stmt.query_row(params![&canonical_uri], |row| {
                Ok((row.get(0)?, row.get(1)?, row.get(2)?))
            })
            .map_err(|_| {
                ClmError::storage(
                    StorageErrorCode::CardNotFound,
                    format!("Handle '{}' not found", canonical_uri),
                )
            })?
        };

        let size_bytes: usize = {
            let mut stmt = conn.prepare_cached("SELECT length(content) FROM card WHERE hash = ?1")?;
            stmt.query_row(params![hash_str], |row| row.get::<_, i64>(0))
                .unwrap_or(0) as usize
        };

        let hash = ContentHash::parse(&hash_str)?;
        Ok(MCardStat {
            uri: canonical_uri,
            hash,
            size_bytes,
            created_at,
            updated_at,
        })
    }

    /// Lists all MCard handles sharing the specified URI prefix.
    pub fn list_dir(&self, prefix: &str) -> Result<Vec<String>> {
        let conn = self
            .conn
            .lock()
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;

        let canonical_prefix = self.canonicalize_uri(prefix);
        let pattern = if canonical_prefix.ends_with('/') {
            format!("{}%", canonical_prefix)
        } else if canonical_prefix == "mcard:" {
            "mcard:%".to_string()
        } else {
            format!("{}/%", canonical_prefix)
        };

        let mut stmt = conn.prepare_cached(
            "SELECT handle FROM handle_registry WHERE handle LIKE ?1 ORDER BY handle ASC",
        )?;
        let rows = stmt.query_map(params![pattern], |row| row.get(0))?;

        let mut handles = Vec::new();
        for handle in rows {
            handles.push(handle?);
        }
        Ok(handles)
    }

    /// Deregisters an MCard handle, preserving the underlying immutable CAS blob (INV-04).
    pub fn delete_file(&self, uri: &str) -> Result<()> {
        let canonical_uri = self.canonicalize_uri(uri);
        let now = crate::utils::now_iso8601();
        let mut conn = self
            .conn
            .lock()
            .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;

        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
        {
            // Record deletion in history
            let mut stmt_hist = tx.prepare_cached(
                "INSERT INTO handle_history (handle, previous_hash, changed_at) \
                 SELECT handle, current_hash, ?1 FROM handle_registry WHERE handle = ?2",
            )?;
            stmt_hist.execute(params![now, &canonical_uri])?;

            // Remove from active registry
            let mut stmt_del = tx.prepare_cached("DELETE FROM handle_registry WHERE handle = ?1")?;
            let affected = stmt_del.execute(params![&canonical_uri])?;

            if affected == 0 {
                return Err(ClmError::storage(
                    StorageErrorCode::CardNotFound,
                    format!("Handle '{}' not found for deletion", canonical_uri),
                ));
            }
        }
        tx.commit()?;
        Ok(())
    }
}