clm-kernel 0.0.13

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 1: In-Process PCard-to-Fiber Transition Loader & Dispatcher (CRD-02).
//! Canonical Path: kernel/clm_rust_core/src/layer1/transition_loader.rs
//!
//! Implements:
//! - PCard resolution from SQLite CAS storage (layer0_function_memory.mcard.db)
//! - In-process native execution of Layer 0 functions (e.g. create_record)
//! - Execution governed by Cordis 5-state Fiber lifecycle (Pending -> Loading -> Active -> Unloading -> Disposed)
//! - Strict Bipartite net invariant enforcement
//! - Token decrement from inputs and increment to outputs (x^T ยท D = 0)
//! - Sub-millisecond execution latency
//! - Zero token leakage on failure

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::time::Instant;

use crate::fiber::{Fiber, FiberState};
use crate::layer0::mcard_record::{create_record, MCardRecord};
use crate::layer1::types::{Marking, PetriNet};

/// Tripartite PCard data loaded from CAS storage.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PcardData {
    pub function_id: String,
    pub pcard_hash: String,
    pub abstract_face: serde_json::Value,
    pub concrete_face: serde_json::Value,
    pub balanced_face: serde_json::Value,
}

/// Execution outcome for an in-process CPN transition firing.
#[derive(Debug, Clone)]
pub struct TransitionExecutionOutcome {
    pub transition_id: String,
    pub function_id: String,
    pub success: bool,
    pub record_hash: Option<String>,
    pub latency_ms: f64,
    pub state_history: Vec<FiberState>,
    pub error: Option<String>,
}

/// In-process PCard-to-Fiber Transition Loader.
pub struct TransitionLoader {
    pub pool_db_path: PathBuf,
}

impl TransitionLoader {
    pub fn new(pool_db_path: impl Into<PathBuf>) -> Self {
        Self {
            pool_db_path: pool_db_path.into(),
        }
    }

    pub fn default_pool() -> Self {
        let candidates = [
            PathBuf::from("clm/db/layer0_function_memory.mcard.db"),
            PathBuf::from("../../db/layer0_function_memory.mcard.db"),
            PathBuf::from("../db/layer0_function_memory.mcard.db"),
        ];
        let found = candidates.into_iter().find(|p| p.exists()).unwrap_or_else(|| {
            PathBuf::from("clm/db/layer0_function_memory.mcard.db")
        });
        Self::new(found)
    }

    /// Resolves tripartite PCard by handle from SQLite CAS database.
    pub fn resolve_pcard(&self, function_id: &str) -> Result<PcardData, String> {
        if !self.pool_db_path.exists() {
            return Err(format!("Function memory DB not found: {:?}", self.pool_db_path));
        }

        let conn = rusqlite::Connection::open_with_flags(
            &self.pool_db_path,
            rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
        )
        .map_err(|e| format!("Failed to open DB: {}", e))?;

        let mut stmt = conn
            .prepare("SELECT current_hash FROM handle_registry WHERE handle = ?")
            .map_err(|e| format!("Prepare error: {}", e))?;

        let mut hash_res: Result<String, _> = stmt.query_row([function_id], |row| row.get(0));

        // Alias fallback if handle is one of the dual names
        if hash_res.is_err() {
            if function_id == "urn:mcard:cas/mcard/create-record" {
                hash_res = stmt.query_row(["urn:mcard:cas/mcard-record/create-record"], |row| row.get(0));
            } else if function_id == "urn:mcard:cas/mcard-record/create-record" {
                hash_res = stmt.query_row(["urn:mcard:cas/mcard/create-record"], |row| row.get(0));
            }
        }

        let pcard_hash = hash_res.map_err(|_| format!("Function handle '{}' not found in handle_registry", function_id))?;

        let mut card_stmt = conn
            .prepare("SELECT content FROM card WHERE hash = ?")
            .map_err(|e| format!("Card prepare error: {}", e))?;

        let card_raw: Vec<u8> = card_stmt
            .query_row([&pcard_hash], |row| row.get(0))
            .map_err(|e| format!("Root card '{}' missing: {}", pcard_hash, e))?;

        let root_val: serde_json::Value = serde_json::from_slice(&card_raw)
            .map_err(|e| format!("Failed to parse root card JSON: {}", e))?;

        let faces = root_val
            .get("payload")
            .and_then(|p| p.get("faces"))
            .and_then(|f| f.as_object())
            .ok_or_else(|| "PCard missing required faces object".to_string())?;

        let mut resolved_faces: HashMap<String, serde_json::Value> = HashMap::new();

        for (aspect, q_hash_val) in faces {
            let q_hash = q_hash_val.as_str().unwrap_or("");
            let bare_hash = if let Some((_, h)) = q_hash.split_once(':') {
                h
            } else {
                q_hash
            };

            if let Ok(f_raw) = card_stmt.query_row([bare_hash], |row| row.get::<_, Vec<u8>>(0)) {
                if let Ok(f_val) = serde_json::from_slice(&f_raw) {
                    resolved_faces.insert(aspect.clone(), f_val);
                }
            }
        }

        Ok(PcardData {
            function_id: function_id.to_string(),
            pcard_hash,
            abstract_face: resolved_faces.remove("abstract").unwrap_or(serde_json::Value::Null),
            concrete_face: resolved_faces.remove("concrete").unwrap_or(serde_json::Value::Null),
            balanced_face: resolved_faces.remove("balanced").unwrap_or(serde_json::Value::Null),
        })
    }

    /// Invokes create_record directly in-process.
    pub fn invoke_create_record(
        &self,
        content: &[u8],
        algorithm: Option<&str>,
    ) -> Result<MCardRecord, String> {
        create_record(content, algorithm)
    }

    /// Validates that the PetriNet strictly satisfies bipartite invariants.
    pub fn validate_bipartite(net: &PetriNet) -> Result<(), String> {
        let place_ids: HashSet<&str> = net.places.iter().map(|p| p.id.as_str()).collect();
        let trans_ids: HashSet<&str> = net.transitions.iter().map(|t| t.id.as_str()).collect();

        let overlap: Vec<&&str> = place_ids.intersection(&trans_ids).collect();
        if !overlap.is_empty() {
            return Err(format!("Partition overlap: {:?} declared as both Place and Transition", overlap));
        }

        for trans in &net.transitions {
            for inp in &trans.inputs {
                if trans_ids.contains(inp.as_str()) {
                    return Err(format!(
                        "Bipartite violation: Transition '{}' connects directly to Transition '{}'",
                        trans.id, inp
                    ));
                }
                if !place_ids.contains(inp.as_str()) {
                    return Err(format!(
                        "Transition '{}' references unknown input Place '{}'",
                        trans.id, inp
                    ));
                }
            }
            for outp in &trans.outputs {
                if trans_ids.contains(outp.as_str()) {
                    return Err(format!(
                        "Bipartite violation: Transition '{}' connects directly to Transition '{}'",
                        trans.id, outp
                    ));
                }
                if !place_ids.contains(outp.as_str()) {
                    return Err(format!(
                        "Transition '{}' references unknown output Place '{}'",
                        trans.id, outp
                    ));
                }
            }
        }

        Ok(())
    }

    /// Fires a transition in-process within a Cordis Fiber lifecycle.
    pub fn fire_transition(
        &self,
        net: &PetriNet,
        marking: &mut Marking,
        transition_id: &str,
        input_payload: &[u8],
        planted_error: bool,
    ) -> Result<TransitionExecutionOutcome, String> {
        Self::validate_bipartite(net)?;

        let trans = net
            .transitions
            .iter()
            .find(|t| t.id == transition_id)
            .ok_or_else(|| format!("Transition '{}' not found in net", transition_id))?;

        // 1. Check token enablement in input places
        for in_place in &trans.inputs {
            let count = marking.get(in_place).copied().unwrap_or(0);
            if count < 1 {
                return Err(format!(
                    "Transition '{}' not enabled: input place '{}' has 0 tokens",
                    transition_id, in_place
                ));
            }
        }

        // 2. Instantiate Cordis Fiber (Pending)
        let fiber = Fiber::new(
            format!("fiber_{}_{}", transition_id, uuid::Uuid::new_v4()),
            vec!["@Inject::Context".to_string()],
        );
        let mut state_history = vec![fiber.get_state()];

        let start_time = Instant::now();

        // Pending -> Loading
        fiber.transition_to(FiberState::Loading)?;
        state_history.push(fiber.get_state());

        // Loading -> Active
        fiber.transition_to(FiberState::Active)?;
        state_history.push(fiber.get_state());

        if planted_error {
            // ZERO TOKEN LEAKAGE:
            // Input tokens remain untouched.
            // Output tokens not deposited.
            // Unload and dispose fiber.
            let _ = fiber.transition_to(FiberState::Unloading);
            state_history.push(fiber.get_state());
            let _ = fiber.transition_to(FiberState::Disposed);
            state_history.push(fiber.get_state());

            let latency_ms = start_time.elapsed().as_secs_f64() * 1000.0;
            return Ok(TransitionExecutionOutcome {
                transition_id: transition_id.to_string(),
                function_id: "urn:mcard:cas/mcard-record/create-record".to_string(),
                success: false,
                record_hash: None,
                latency_ms,
                state_history,
                error: Some("Planted failure in transition execution".to_string()),
            });
        }

        // Execute function in-process while Active
        let record = create_record(input_payload, None)?;

        // Active -> Unloading
        fiber.transition_to(FiberState::Unloading)?;
        state_history.push(fiber.get_state());

        // Decrement input tokens
        for in_place in &trans.inputs {
            let count = marking.get_mut(in_place).unwrap();
            *count -= 1;
        }

        // Increment output tokens
        for outp in &trans.outputs {
            let count = marking.entry(outp.clone()).or_insert(0);
            *count += 1;
        }

        // Unloading -> Disposed
        fiber.transition_to(FiberState::Disposed)?;
        state_history.push(fiber.get_state());

        let latency_ms = start_time.elapsed().as_secs_f64() * 1000.0;

        Ok(TransitionExecutionOutcome {
            transition_id: transition_id.to_string(),
            function_id: "urn:mcard:cas/mcard-record/create-record".to_string(),
            success: true,
            record_hash: Some(record.hash),
            latency_ms,
            state_history,
            error: None,
        })
    }
}