clm-kernel 0.0.23

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
// evaluator/dispatch/mod.rs
// ─────────────────────────────────────────────────────────────
// Central dispatch module for CLM internal evaluation.
//
// Architecture:
//   mod.rs            — InternalFn type, shared utilities, composable registry
//   registry_core.rs  — L0 Kenotic Core dispatchers (meta-eval, baldwin, tridb, yaml/classifier)
//   registry_runtime.rs — L0-L2 runtime dispatchers (file/memorize, CPN-VM, state adapters, polyglot)
//   registry_infra.rs — L3 + testing dispatchers (network/discovery, integration tests)
//   orchestrator.rs   — try_internal_dispatch (central CLM YAML → execution router)
//   runtime.rs        — Non-Rust runtime execution (python, node, shell, compose, system, etc.)
// ─────────────────────────────────────────────────────────────

pub mod catalog;
pub mod catalog_ids;
mod registry_core;
mod registry_runtime;
mod registry_infra;
// Test-harness arms keep their module-path keys, isolated from production (INV-600).
#[path = "registry_infra_testing.rs"]
mod registry_testing;
mod orchestrator_intercepts;
mod orchestrator_invariants;
mod orchestrator_pipeline;
mod orchestrator;
pub(crate) mod runtime;

use std::fs;
use std::path::Path;

/// Function pointer type for all internal dispatch entries.
/// Takes (clm_root: &str, clm_file: &str) and returns (exit_code, stdout).
pub(crate) type InternalFn = fn(&str, &str) -> Result<(i32, String), String>;

// ── Shared Utilities ────────────────────────────────────────

/// Parse the `process.args` list from a CLM YAML file.
pub(super) fn get_clm_args(clm_file: &str) -> Result<Vec<String>, String> {
    let content = fs::read_to_string(clm_file)
        .map_err(|e| format!("Failed to read CLM file for args: {}", e))?;
    let data: serde_yaml::Value = serde_yaml::from_str(&content)
        .map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
    let clm_data = data.get("clm").unwrap_or(&data);
    let concrete_impl = clm_data.get("concrete_impl")
        .ok_or_else(|| "No concrete_impl in CLM".to_string())?;
    let process = concrete_impl.get("process")
        .ok_or_else(|| "No process in concrete_impl".to_string())?;

    if let Some(args_val) = process.get("args") {
        if let Some(arr) = args_val.as_sequence() {
            let mut result = Vec::new();
            for item in arr {
                if let Some(s) = item.as_str() {
                    result.push(s.to_string());
                } else if let Some(i) = item.as_i64() {
                    result.push(i.to_string());
                } else if let Some(b) = item.as_bool() {
                    result.push(b.to_string());
                } else {
                    result.push("".to_string());
                }
            }
            Ok(result)
        } else {
            Err("process.args is not a list/sequence".to_string())
        }
    } else {
        Ok(Vec::new())
    }
}

/// Resolve a JSON-or-file argument to a JSON AST string.
pub(super) fn resolve_json_ast_internal(json_or_file: &str, clm_root: &str) -> String {
    let trimmed = json_or_file.trim();
    if trimmed.starts_with('{') || trimmed.starts_with('[') {
        trimmed.to_string()
    } else {
        let raw_path = Path::new(json_or_file);
        let path = if raw_path.is_absolute() {
            raw_path.to_path_buf()
        } else {
            Path::new(clm_root).join(json_or_file)
        };
        if path.exists() {
            crate::yaml::parse_to_mcards(&path.to_string_lossy()).unwrap_or_else(|_| "null".to_string())
        } else {
            trimmed.to_string()
        }
    }
}

// ── Inventory-Based Static Registry ─────────────────────────

/// A statically registered evaluation entry point collected via the `inventory` crate.
pub struct DispatchEntry {
    pub module_path: &'static str,
    pub func: InternalFn,
}

inventory::collect!(DispatchEntry);

/// Decentralized macro for registering CLM evaluators directly at definition site.
#[macro_export]
macro_rules! register_clm_dispatch {
    ($path:expr, $func:expr) => {
        inventory::submit! {
            $crate::evaluator::dispatch::DispatchEntry {
                module_path: $path,
                func: $func,
            }
        }
    };
}

// ── Composable Registry ─────────────────────────────────────

/// Module-path namespaces of the test harness; production ids never fall back into them.
const TESTING_ROUTES: &[&str] = &["clm_rust_core::integration::", "clm_rust_core::test::", "clm_rust_core::prove::"];

/// Look up a route (a catalog id or alias) in the internal dispatch registry (INV-600).
///
/// Production registries (`registry_core`, `registry_runtime`, `registry_infra`) match canonical
/// catalog ids from `catalog_ids`. A route in a test-harness namespace falls back to the testing
/// registry (`registry_testing` and the `inventory`-collected shell tests), which keeps module paths.
pub(crate) fn get_internal_registry(module_path: &str) -> Option<InternalFn> {
    registry_core::dispatch(module_path)
        .or_else(|| registry_runtime::dispatch(module_path))
        .or_else(|| registry_infra::dispatch(module_path))
        .or_else(|| testing_registry(module_path))
}

fn testing_registry(module_path: &str) -> Option<InternalFn> {
    if !TESTING_ROUTES.iter().any(|prefix| module_path.starts_with(prefix)) {
        return None;
    }
    static REGISTRY: std::sync::OnceLock<std::collections::HashMap<&'static str, InternalFn>> = std::sync::OnceLock::new();
    let map = REGISTRY.get_or_init(|| {
        let mut m = std::collections::HashMap::with_capacity(256);
        for entry in inventory::iter::<DispatchEntry> {
            m.insert(entry.module_path, entry.func);
        }
        m
    });

    map.get(module_path).copied().or_else(|| registry_testing::dispatch_testing_verification(module_path))
}

// ── Public Re-export ────────────────────────────────────────

pub(crate) use orchestrator::try_internal_dispatch;
#[allow(unused_imports)]
pub(crate) use orchestrator::try_internal_dispatch_with_context;