Skip to main content

clm_rust_core/evaluator/dispatch/
mod.rs

1// evaluator/dispatch/mod.rs
2// ─────────────────────────────────────────────────────────────
3// Central dispatch module for CLM internal evaluation.
4//
5// Architecture:
6//   mod.rs            — InternalFn type, shared utilities, composable registry
7//   registry_core.rs  — L0 Kenotic Core dispatchers (meta-eval, baldwin, tridb, yaml/classifier)
8//   registry_runtime.rs — L0-L2 runtime dispatchers (file/memorize, CPN-VM, state adapters, polyglot)
9//   registry_infra.rs — L3 + testing dispatchers (network/discovery, integration tests)
10//   orchestrator.rs   — try_internal_dispatch (central CLM YAML → execution router)
11//   runtime.rs        — Non-Rust runtime execution (python, node, shell, compose, system, etc.)
12// ─────────────────────────────────────────────────────────────
13
14pub mod catalog;
15mod registry_core;
16mod registry_runtime;
17mod registry_infra;
18mod orchestrator_intercepts;
19mod orchestrator_invariants;
20mod orchestrator_pipeline;
21mod orchestrator;
22pub(crate) mod runtime;
23
24use std::fs;
25use std::path::Path;
26
27/// Function pointer type for all internal dispatch entries.
28/// Takes (clm_root: &str, clm_file: &str) and returns (exit_code, stdout).
29pub(crate) type InternalFn = fn(&str, &str) -> Result<(i32, String), String>;
30
31// ── Shared Utilities ────────────────────────────────────────
32
33/// Parse the `process.args` list from a CLM YAML file.
34pub(super) fn get_clm_args(clm_file: &str) -> Result<Vec<String>, String> {
35    let content = fs::read_to_string(clm_file)
36        .map_err(|e| format!("Failed to read CLM file for args: {}", e))?;
37    let data: serde_yaml::Value = serde_yaml::from_str(&content)
38        .map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
39    let clm_data = data.get("clm").unwrap_or(&data);
40    let concrete_impl = clm_data.get("concrete_impl")
41        .ok_or_else(|| "No concrete_impl in CLM".to_string())?;
42    let process = concrete_impl.get("process")
43        .ok_or_else(|| "No process in concrete_impl".to_string())?;
44
45    if let Some(args_val) = process.get("args") {
46        if let Some(arr) = args_val.as_sequence() {
47            let mut result = Vec::new();
48            for item in arr {
49                if let Some(s) = item.as_str() {
50                    result.push(s.to_string());
51                } else if let Some(i) = item.as_i64() {
52                    result.push(i.to_string());
53                } else if let Some(b) = item.as_bool() {
54                    result.push(b.to_string());
55                } else {
56                    result.push("".to_string());
57                }
58            }
59            Ok(result)
60        } else {
61            Err("process.args is not a list/sequence".to_string())
62        }
63    } else {
64        Ok(Vec::new())
65    }
66}
67
68/// Resolve a JSON-or-file argument to a JSON AST string.
69pub(super) fn resolve_json_ast_internal(json_or_file: &str, clm_root: &str) -> String {
70    let trimmed = json_or_file.trim();
71    if trimmed.starts_with('{') || trimmed.starts_with('[') {
72        trimmed.to_string()
73    } else {
74        let raw_path = Path::new(json_or_file);
75        let path = if raw_path.is_absolute() {
76            raw_path.to_path_buf()
77        } else {
78            Path::new(clm_root).join(json_or_file)
79        };
80        if path.exists() {
81            crate::yaml::parse_to_mcards(&path.to_string_lossy()).unwrap_or_else(|_| "null".to_string())
82        } else {
83            trimmed.to_string()
84        }
85    }
86}
87
88// ── Inventory-Based Static Registry ─────────────────────────
89
90/// A statically registered evaluation entry point collected via the `inventory` crate.
91pub struct DispatchEntry {
92    pub module_path: &'static str,
93    pub func: InternalFn,
94}
95
96inventory::collect!(DispatchEntry);
97
98/// Decentralized macro for registering CLM evaluators directly at definition site.
99#[macro_export]
100macro_rules! register_clm_dispatch {
101    ($path:expr, $func:expr) => {
102        inventory::submit! {
103            $crate::evaluator::dispatch::DispatchEntry {
104                module_path: $path,
105                func: $func,
106            }
107        }
108    };
109}
110
111// ── Composable Registry ─────────────────────────────────────
112
113/// Look up a module path in the internal dispatch registry.
114///
115/// First checks the statically compiled `inventory` registry in O(1) time.
116/// Falls back to legacy match tables in `registry_core`, `registry_runtime`, `registry_infra`.
117pub(crate) fn get_internal_registry(module_path: &str) -> Option<InternalFn> {
118    static REGISTRY: std::sync::OnceLock<std::collections::HashMap<&'static str, InternalFn>> = std::sync::OnceLock::new();
119    let map = REGISTRY.get_or_init(|| {
120        let mut m = std::collections::HashMap::with_capacity(256);
121        for entry in inventory::iter::<DispatchEntry> {
122            m.insert(entry.module_path, entry.func);
123        }
124        m
125    });
126
127    if let Some(&func) = map.get(module_path) {
128        return Some(func);
129    }
130
131    registry_core::dispatch(module_path)
132        .or_else(|| registry_runtime::dispatch(module_path))
133        .or_else(|| registry_infra::dispatch(module_path))
134}
135
136// ── Public Re-export ────────────────────────────────────────
137
138pub(crate) use orchestrator::try_internal_dispatch;
139#[allow(unused_imports)]
140pub(crate) use orchestrator::try_internal_dispatch_with_context;