clm-kernel 0.0.8

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Sprint 493 (`DP-4` / `INV-493`): Versioned Core Dispatch Surface & VCardSandwich Hoare Middleware.
//!
//! Provides:
//! - `DispatchCatalogEntry`, `ExemptionMetadata`, `DispatchCatalogDoc`
//! - `CoreDispatchRegistry` with deterministic duplicate/alias/namespace checks
//! - `ScopedPluginGuard` RAII / disposable handle for scoped plugin registration
//! - `ExecutionReceipt` & `compute_receipt_hash` matching `execution_receipt.schema.json`
//! - `dispatch_with_hoare` integrating `TriDbSavepointGuard` (`DP-3`) and Hoare pre/post checks

use crate::cross_cutting::context::CLMContext;
use crate::fiber::savepoint_guard::TriDbSavepointGuard;
use crate::layer0::runtime_contract::ClmExitCode;
use rusqlite::{params, Connection};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};

pub const CATALOG_VERSION: &str = "dispatch-catalog-v1";
pub const CATALOG_SCHEMA_REF: &str = "types/lattice/dispatch_catalog.schema.json";
pub const RECEIPT_SCHEMA_VERSION: &str = "execution-receipt-v1";

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExemptionMetadata {
    pub owner: String,
    pub rationale: String,
}

/// Canonical dispatch catalog entry with fields ordered alphabetically for deterministic JSON output.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DispatchCatalogEntry {
    pub aliases: Vec<String>,
    pub catalog_version: String,
    pub exemption: Option<ExemptionMetadata>,
    pub handler_key: String,
    pub layer: u8,
    pub op_id: String,
    pub post_gate: Option<String>,
    pub pre_gate: Option<String>,
    pub status: String,
    pub uri_scheme: String,
    pub verification_policy: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DispatchCatalogDoc {
    pub catalog_version: String,
    pub entries: Vec<DispatchCatalogEntry>,
    pub schema: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReceiptError {
    pub code: i32,
    pub message: String,
    pub phase: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecutionReceiptWithoutHash {
    pub agent_did: String,
    pub error: Option<ReceiptError>,
    pub exit_code: i32,
    pub g_time: String,
    pub handler_key: String,
    pub idempotency_key: String,
    pub input_hash: String,
    pub op_id: String,
    pub output_hash: Option<String>,
    pub receipt_id: String,
    pub schema_version: String,
    pub status: String,
    pub witness_policy: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecutionReceipt {
    pub agent_did: String,
    pub error: Option<ReceiptError>,
    pub exit_code: i32,
    pub g_time: String,
    pub handler_key: String,
    pub idempotency_key: String,
    pub input_hash: String,
    pub op_id: String,
    pub output_hash: Option<String>,
    pub receipt_hash: String,
    pub receipt_id: String,
    pub schema_version: String,
    pub status: String,
    pub witness_policy: String,
}

impl ExecutionReceipt {
    pub fn build(base: ExecutionReceiptWithoutHash) -> Self {
        let receipt_hash = compute_receipt_hash(&base);
        Self {
            agent_did: base.agent_did,
            error: base.error,
            exit_code: base.exit_code,
            g_time: base.g_time,
            handler_key: base.handler_key,
            idempotency_key: base.idempotency_key,
            input_hash: base.input_hash,
            op_id: base.op_id,
            output_hash: base.output_hash,
            receipt_hash,
            receipt_id: base.receipt_id,
            schema_version: base.schema_version,
            status: base.status,
            witness_policy: base.witness_policy,
        }
    }
}

pub fn compute_receipt_hash(base: &ExecutionReceiptWithoutHash) -> String {
    let canonical = serde_json::to_string(base).expect("serialize ExecutionReceiptWithoutHash");
    let digest = blake3::hash(canonical.as_bytes()).to_hex();
    format!("blake3:{}", digest)
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DispatchRegistrationError {
    DuplicateOpId(String),
    AliasCollision(String),
    CoreNamespaceOverride(String),
}

impl std::fmt::Display for DispatchRegistrationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DuplicateOpId(id) => write!(f, "DuplicateDispatchOperationError: {}", id),
            Self::AliasCollision(a) => write!(f, "DuplicateDispatchOperationError (alias): {}", a),
            Self::CoreNamespaceOverride(id) => write!(f, "CoreNamespaceOverrideError: {}", id),
        }
    }
}

impl std::error::Error for DispatchRegistrationError {}

pub type CoreHandlerFn = Arc<dyn Fn(&CLMContext, &str) -> String + Send + Sync + 'static>;

#[derive(Default)]
struct RegistryState {
    core_entries: BTreeMap<String, DispatchCatalogEntry>,
    plugin_entries: BTreeMap<String, DispatchCatalogEntry>,
    aliases: BTreeMap<String, String>,
    handlers: BTreeMap<String, CoreHandlerFn>,
}

pub struct ScopedPluginGuard {
    state: Arc<Mutex<RegistryState>>,
    op_id: String,
    aliases: Vec<String>,
    disposed: bool,
}

impl ScopedPluginGuard {
    pub fn dispose(&mut self) {
        if self.disposed {
            return;
        }
        self.disposed = true;
        if let Ok(mut st) = self.state.lock() {
            st.plugin_entries.remove(&self.op_id);
            st.handlers.remove(&self.op_id);
            for alias in &self.aliases {
                if st.aliases.get(alias) == Some(&self.op_id) {
                    st.aliases.remove(alias);
                }
            }
        }
    }
}

impl Drop for ScopedPluginGuard {
    fn drop(&mut self) {
        self.dispose();
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HoareDispatchResult {
    pub exit_code: i32,
    pub output: String,
    pub handler_called: bool,
    pub receipt: ExecutionReceipt,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LegacyDispatchResult {
    pub exit_code: i32,
    pub output: String,
    pub error: Option<String>,
}

pub struct CoreDispatchRegistry {
    state: Arc<Mutex<RegistryState>>,
}

impl Default for CoreDispatchRegistry {
    fn default() -> Self {
        Self::from_canonical_catalog()
    }
}

impl CoreDispatchRegistry {
    pub fn from_canonical_catalog() -> Self {
        let raw_json = include_str!("../../../types/lattice/dispatch_catalog.json");
        let doc: DispatchCatalogDoc =
            serde_json::from_str(raw_json).expect("parse canonical dispatch_catalog.json");
        let reg = Self {
            state: Arc::new(Mutex::new(RegistryState::default())),
        };
        for entry in doc.entries {
            reg.register_core_entry(entry, None)
                .expect("register canonical core entry");
        }
        reg.install_default_handlers();
        reg
    }

    fn install_default_handlers(&self) {
        let mut st = self.state.lock().unwrap();
        st.handlers.insert(
            "clm.core.memorize_file".to_string(),
            Arc::new(|_ctx, payload| format!("memorized:{}", payload)),
        );
        st.handlers.insert(
            "clm.core.yaml_classify".to_string(),
            Arc::new(|_ctx, _payload| "classified:clm_triad".to_string()),
        );
        st.handlers.insert(
            "clm.core.baldwin_apply".to_string(),
            Arc::new(|_ctx, payload| format!("baldwin:{}", payload)),
        );
        st.handlers.insert(
            "clm.core.cpn_simulate".to_string(),
            Arc::new(|_ctx, payload| format!("cpn_simulated:{}", payload)),
        );
        st.handlers.insert(
            "clm.core.meta_eval".to_string(),
            Arc::new(|_ctx, payload| format!("meta_evaluated:{}", payload)),
        );
        st.handlers.insert(
            "clm.core.tridb_init".to_string(),
            Arc::new(|_ctx, _payload| "tridb:initialized".to_string()),
        );
        st.handlers.insert(
            "clm.fallback.legacy_shell_adapter".to_string(),
            Arc::new(|_ctx, payload| format!("legacy_shell:{}", payload)),
        );
        st.handlers.insert(
            "clm.health.version_probe".to_string(),
            Arc::new(|_ctx, _payload| "clm-core:v4.0.0".to_string()),
        );
    }

    pub fn register_core_entry(
        &self,
        entry: DispatchCatalogEntry,
        handler: Option<CoreHandlerFn>,
    ) -> Result<(), DispatchRegistrationError> {
        let mut st = self.state.lock().unwrap();
        if st.core_entries.contains_key(&entry.op_id)
            || st.plugin_entries.contains_key(&entry.op_id)
        {
            return Err(DispatchRegistrationError::DuplicateOpId(
                entry.op_id.clone(),
            ));
        }
        for alias in &entry.aliases {
            if st.aliases.contains_key(alias)
                || st.core_entries.contains_key(alias)
                || st.plugin_entries.contains_key(alias)
            {
                return Err(DispatchRegistrationError::AliasCollision(alias.clone()));
            }
        }
        for alias in &entry.aliases {
            st.aliases.insert(alias.clone(), entry.op_id.clone());
        }
        if let Some(h) = handler {
            st.handlers.insert(entry.op_id.clone(), h);
        }
        st.core_entries.insert(entry.op_id.clone(), entry);
        Ok(())
    }

    pub fn register_scoped_plugin(
        &self,
        entry: DispatchCatalogEntry,
        handler: Option<CoreHandlerFn>,
    ) -> Result<ScopedPluginGuard, DispatchRegistrationError> {
        let mut st = self.state.lock().unwrap();
        if entry.op_id.starts_with("clm.core.")
            || entry.op_id.starts_with("clm.fallback.")
            || entry.op_id.starts_with("clm.health.")
            || st.core_entries.contains_key(&entry.op_id)
            || !entry.op_id.starts_with("clm.plugin.")
        {
            return Err(DispatchRegistrationError::CoreNamespaceOverride(
                entry.op_id.clone(),
            ));
        }
        if st.plugin_entries.contains_key(&entry.op_id) {
            return Err(DispatchRegistrationError::DuplicateOpId(
                entry.op_id.clone(),
            ));
        }
        for alias in &entry.aliases {
            if st.aliases.contains_key(alias)
                || st.core_entries.contains_key(alias)
                || st.plugin_entries.contains_key(alias)
            {
                return Err(DispatchRegistrationError::AliasCollision(alias.clone()));
            }
        }

        let op_id = entry.op_id.clone();
        let aliases = entry.aliases.clone();
        for alias in &aliases {
            st.aliases.insert(alias.clone(), op_id.clone());
        }
        let default_op = op_id.clone();
        let h = handler.unwrap_or_else(|| {
            Arc::new(move |_ctx, payload| format!("plugin:{}:{}", default_op, payload))
        });
        st.handlers.insert(op_id.clone(), h);
        st.plugin_entries.insert(op_id.clone(), entry);
        drop(st);

        Ok(ScopedPluginGuard {
            state: self.state.clone(),
            op_id,
            aliases,
            disposed: false,
        })
    }

    pub fn resolve_entry(&self, route_or_op_id: &str) -> Option<DispatchCatalogEntry> {
        let st = self.state.lock().unwrap();
        let op_id = st
            .aliases
            .get(route_or_op_id)
            .map(|s| s.as_str())
            .unwrap_or(route_or_op_id);
        st.core_entries
            .get(op_id)
            .or_else(|| st.plugin_entries.get(op_id))
            .cloned()
    }

}

#[path = "catalog_hoare.rs"]
mod catalog_hoare;
#[allow(unused_imports)]
pub use catalog_hoare::*;