clm-kernel 0.0.2

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
// evaluator/dispatch/registry_core.rs
// ─────────────────────────────────────────────────────────────
// L0 Kenotic Core dispatch entries:
//   - Meta-Circular Evaluation (run_evaluation)
//   - Baldwin Modularity Algebra (split, merge)
//   - Tri-Database operations (init_tridb, sql_query, handle_register/delete)
//   - YAML/Classifier operations (yaml_load_once, yaml_get_field, classify, etc.)
// ─────────────────────────────────────────────────────────────

use std::env;
use std::path::Path;
use super::{InternalFn, get_clm_args, resolve_json_ast_internal};
use crate::evaluator::{
    thread_local_depth_increment,
    thread_local_depth_decrement,
    run_evaluation,
};

/// Composite dispatcher for all L0 Kenotic Core modules.
pub(super) fn dispatch(module_path: &str) -> Option<InternalFn> {
    dispatch_meta_eval(module_path)
        .or_else(|| dispatch_baldwin_algebra(module_path))
        .or_else(|| dispatch_tri_database(module_path))
        .or_else(|| dispatch_yaml_classifier(module_path))
}

// ── Meta-Circular Evaluation ────────────────────────────────

fn dispatch_meta_eval(module_path: &str) -> Option<InternalFn> {
    match module_path {
        // Sprint 103: Meta-Circular Evaluation In-process Dispatch
        "clm_rust_core::evaluator::run_evaluation" => Some(|clm_root, clm_file| {
            let args = get_clm_args(clm_file)?;
            let target_file = args.first().map(|s| s.as_str());
            let payload = args.get(1).map(|s| s.as_str());

            let depth = thread_local_depth_increment();
            let quiet = env::var("CLM_QUIET").as_deref() == Ok("true");

            if depth > 3 {
                thread_local_depth_decrement();
                return Err(format!("Maximum evaluation nesting depth of 3 exceeded (current depth: {})", depth));
            }

            let current_id = crate::db::TEST_SANDBOX_DB_ID.with(|id| {
                id.borrow().clone().unwrap_or_else(|| "default".to_string())
            });
            let nested_id = format!("{}_{}", current_id, depth);
            let sandbox_guard = crate::db::DatabaseSandboxGuard::activate(&nested_id);

            let res = run_evaluation(
                Path::new(clm_root),
                target_file,
                payload,
                None,
                quiet,
                Some(&format!("nested_{}", depth)),
            );

            thread_local_depth_decrement();
            drop(sandbox_guard);

            match res {
                Ok(exit_code) => {
                    if exit_code == 0 {
                        let active_a_hash = env::var("CLM_ACTIVE_A_HASH").unwrap_or_default();
                        let active_c_hash = env::var("CLM_ACTIVE_C_HASH").unwrap_or_default();
                        let content_hash = crate::baldwin::sha256_hash_string(&format!("nested_run_{}", depth));
                        let extra_fields = format!(
                            "child_exit_code: 0\nchild_depth: {}\nconsensus_gate: \"sealed_by_parent\"",
                            depth
                        );
                        let _ = crate::db::emit_exec_mcard(
                            "meta_circular_consensus",
                            &content_hash,
                            &extra_fields,
                            &active_a_hash,
                            &active_c_hash,
                            clm_root,
                        );
                    }
                    Ok((exit_code, format!("exit_code: {}\n", exit_code)))
                }
                Err(e) => Err(e),
            }
        }),
        _ => None,
    }
}

// ── Baldwin Modularity Algebra ──────────────────────────────

fn dispatch_baldwin_algebra(module_path: &str) -> Option<InternalFn> {
    match module_path {
        // L0 Kenotic Core — Baldwin Modularity Algebra
        "clm_rust_core::baldwin::split" => Some(|clm_root, clm_file| {
            let args = get_clm_args(clm_file)?;
            let file = if args.is_empty() { clm_file } else { &args[0] };
            crate::baldwin::split(file, clm_root)
                .map(|out| (0, out))
        }),
        "clm_rust_core::baldwin::merge" => Some(|_clm_root, clm_file| {
            let args = get_clm_args(clm_file)?;
            if args.len() < 2 {
                return Err("merge requires at least 2 arguments (a_file, c_file)".to_string());
            }
            crate::baldwin::merge(&args[0], &args[1], args.get(2).map(|s| s.as_str()))
                .map(|out| (0, out))
        }),
        _ => None,
    }
}

// ── Tri-Database Operations ─────────────────────────────────

fn dispatch_tri_database(module_path: &str) -> Option<InternalFn> {
    match module_path {
        // L0 Kenotic Core — Tri-Database
        "clm_rust_core::db::init_tridb" => Some(|clm_root, _clm_file| {
            crate::db::init_tridb(clm_root)
                .map(|_| (0, "[INIT_TRIDB] ✅ All 3 pillar databases initialized from Canonical Schema\n".to_string()))
                .map_err(|e| e.to_string())
        }),
        "clm_rust_core::db::sql_query_parameterized" => Some(|clm_root, clm_file| {
            let args = get_clm_args(clm_file)?;
            if args.len() < 2 {
                return Err("sql_query_parameterized requires at least 2 arguments (pillar, query)".to_string());
            }
            let pillar = &args[0];
            let query = &args[1];
            let mut params = Vec::new();
            let mut is_json = false;
            for arg in args.iter().skip(2) {
                if arg == "--json" || arg == "true" {
                    is_json = true;
                } else {
                    params.push(arg.clone());
                }
            }
            crate::db::sql_query_parameterized(pillar, clm_root, query, params, is_json)
                .map(|res| (0, format!("{}\n", res)))
                .map_err(|e| e.to_string())
        }),
        "clm_rust_core::db::handle_register_batch" => Some(|clm_root, clm_file| {
            let args = get_clm_args(clm_file)?;
            if args.len() != 4 {
                return Err("handle_register_batch requires exactly 4 arguments (pillar, handle, hash, content)".to_string());
            }
            crate::db::handle_register_batch(&args[0], clm_root, &args[1], &args[2], &args[3])
                .map(|_| (0, "".to_string()))
                .map_err(|e| e.to_string())
        }),
        "clm_rust_core::db::handle_delete_batch" => Some(|clm_root, clm_file| {
            let args = get_clm_args(clm_file)?;
            if args.len() != 2 {
                return Err("handle_delete_batch requires exactly 2 arguments (pillar, handle)".to_string());
            }
            crate::db::handle_delete_batch(&args[0], clm_root, &args[1])
                .map(|_| (0, "".to_string()))
                .map_err(|e| e.to_string())
        }),
        _ => None,
    }
}

// ── YAML & Classifier Operations ────────────────────────────

fn dispatch_yaml_classifier(module_path: &str) -> Option<InternalFn> {
    match module_path {
        // L0 Kenotic Core — Normalization & Formatting
        "clm_rust_core::yaml::yaml_load_once" => Some(|clm_root, clm_file| {
            let args = get_clm_args(clm_file)?;
            if args.is_empty() {
                return Err("yaml_load_once requires at least 1 argument (file)".to_string());
            }
            crate::yaml::yaml_load_once(&args[0], clm_root)
                .map(|out| (0, format!("{}\n", out)))
                .map_err(|e| e.to_string())
        }),
        "clm_rust_core::yaml::yaml_get_field" => Some(|clm_root, clm_file| {
            let args = get_clm_args(clm_file)?;
            if args.len() != 2 {
                return Err("yaml_get_field requires exactly 2 arguments (json_or_file, jq_path)".to_string());
            }
            let json = resolve_json_ast_internal(&args[0], clm_root);
            let field = crate::yaml::yaml_get_field(&json, &args[1]);
            Ok((0, format!("{}\n", field)))
        }),
        "clm_rust_core::yaml::yaml_get_array_length" => Some(|clm_root, clm_file| {
            let args = get_clm_args(clm_file)?;
            if args.len() != 2 {
                return Err("yaml_get_array_length requires exactly 2 arguments (json_or_file, jq_path)".to_string());
            }
            let json = resolve_json_ast_internal(&args[0], clm_root);
            let len = crate::yaml::yaml_get_array_length(&json, &args[1]);
            Ok((0, format!("{}\n", len)))
        }),
        "clm_rust_core::yaml::yaml_get_array_item" => Some(|clm_root, clm_file| {
            let args = get_clm_args(clm_file)?;
            if args.len() != 3 {
                return Err("yaml_get_array_item requires exactly 3 arguments (json_or_file, jq_path, index)".to_string());
            }
            let json = resolve_json_ast_internal(&args[0], clm_root);
            let idx: usize = args[2].parse().map_err(|e| format!("Invalid index: {}", e))?;
            let item = crate::yaml::yaml_get_array_item(&json, &args[1], idx);
            Ok((0, format!("{}\n", item)))
        }),
        "clm_rust_core::classifier::classify" => Some(|clm_root, clm_file| {
            let args = get_clm_args(clm_file)?;
            if args.is_empty() {
                return Err("classify requires at least 1 argument (json_or_file)".to_string());
            }
            let json_str = resolve_json_ast_internal(&args[0], clm_root);
            if let Ok(json_val) = serde_json::from_str(&json_str) {
                let classification = crate::classifier::classify(&json_val);
                Ok((0, format!("{}\n", classification)))
            } else {
                Ok((0, "Number\n".to_string()))
            }
        }),
        "clm_rust_core::classifier::detect_dialect" => Some(|clm_root, clm_file| {
            let args = get_clm_args(clm_file)?;
            if args.len() != 2 {
                return Err("detect_dialect requires exactly 2 arguments (json_or_file, classification)".to_string());
            }
            let json_str = resolve_json_ast_internal(&args[0], clm_root);
            if let Ok(json_val) = serde_json::from_str(&json_str) {
                let dialect = crate::classifier::detect_dialect(&json_val, &args[1]);
                Ok((0, format!("{}\n", dialect)))
            } else {
                Ok((0, "UNKNOWN\n".to_string()))
            }
        }),
        _ => None,
    }
}