clm-kernel 0.0.1

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! RuntimeAdapter trait and RuntimeDispatcher for Stage 1.3.
//!
//! Provides a unified dispatch interface for PCard runtime execution:
//! - `RuntimeAdapter` trait: `fn execute(&self, script: &str, input: &Value) -> Result<Value, String>`.
//! - `WasmRuntimeAdapter`: executes built-in handlers in WASM linear memory.
//! - `ShellRuntimeAdapter` (native-only): spawns shell subprocess.
//! - `PythonRuntimeAdapter` (native-only): spawns Python subprocess.
//! - `NodeRuntimeAdapter` (native-only): spawns Node.js subprocess.
//! - `RuntimeDispatcher`: HashMap<String, Box<dyn RuntimeAdapter>> registry.
//!
//! Under WASM, only `WasmRuntimeAdapter` is available. Under native, all four
//! adapters are registered. The dispatcher replaces direct `std::process::Command`
//! calls in `execute_pcard_binding`.

use serde_json::Value;
use std::collections::HashMap;

/// Trait for executing a PCard binding script.
///
/// Each runtime type (shell, python, node, llm, echo, noop, math) implements
/// this trait. The dispatcher looks up the runtime by name and calls `execute`.
pub trait RuntimeAdapter: Send + Sync {
    /// Execute the script with the given input and return the output.
    fn execute(&self, script: &str, input: &Value) -> Result<Value, String>;

    /// Human-readable name of this adapter (e.g. "shell", "python", "wasm").
    fn name(&self) -> &str;
}

/// Dispatcher that maps runtime names to adapters.
pub struct RuntimeDispatcher {
    adapters: HashMap<String, Box<dyn RuntimeAdapter>>,
}

impl RuntimeDispatcher {
    /// Create a new empty dispatcher.
    pub fn new() -> Self {
        Self {
            adapters: HashMap::new(),
        }
    }

    /// Create a dispatcher pre-populated with all available adapters for the
    /// current target.
    ///
    /// Under WASM: only `WasmRuntimeAdapter` built-ins (echo, noop, math).
    /// Under native: shell, python, node, plus WASM built-ins.
    pub fn with_defaults() -> Self {
        let mut d = Self::new();

        // Built-in WASM-safe handlers (always available).
        d.register("echo", Box::new(WasmRuntimeAdapter::Echo));
        d.register("noop", Box::new(WasmRuntimeAdapter::Noop));
        d.register("math", Box::new(WasmRuntimeAdapter::Math));

        // Native-only adapters.
        #[cfg(feature = "native")]
        {
            d.register("shell", Box::new(ShellRuntimeAdapter));
            d.register("python", Box::new(PythonRuntimeAdapter));
            d.register("node", Box::new(NodeRuntimeAdapter));
            d.register("llm", Box::new(LlmRuntimeAdapter::new()));
        }

        d
    }

    /// Register an adapter under a runtime name.
    pub fn register(&mut self, runtime: &str, adapter: Box<dyn RuntimeAdapter>) {
        self.adapters.insert(runtime.to_string(), adapter);
    }

    /// Dispatch execution to the named runtime.
    ///
    /// Returns an error if the runtime is not registered.
    pub fn dispatch(&self, runtime: &str, script: &str, input: &Value) -> Result<Value, String> {
        let adapter = self
            .adapters
            .get(runtime)
            .ok_or_else(|| format!("unknown runtime: {} (registered: {:?})", runtime, self.list_runtimes()))?;
        adapter.execute(script, input)
    }

    /// List all registered runtime names.
    pub fn list_runtimes(&self) -> Vec<&str> {
        self.adapters.keys().map(|s| s.as_str()).collect()
    }

    /// Check if a runtime is registered.
    pub fn has(&self, runtime: &str) -> bool {
        self.adapters.contains_key(runtime)
    }
}

impl Default for RuntimeDispatcher {
    fn default() -> Self {
        Self::with_defaults()
    }
}

// ── WasmRuntimeAdapter ──────────────────────────────────────────────

/// Built-in handlers that run entirely in WASM linear memory.
/// These are always available (no subprocess, no filesystem).
#[derive(Debug, Clone, Copy)]
pub enum WasmRuntimeAdapter {
    Echo,
    Noop,
    Math,
}

impl RuntimeAdapter for WasmRuntimeAdapter {
    fn name(&self) -> &str {
        match self {
            Self::Echo => "echo",
            Self::Noop => "noop",
            Self::Math => "math",
        }
    }

    fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
        match self {
            Self::Echo => Ok(Value::String(script.to_string())),
            Self::Noop => Ok(Value::String(String::new())),
            Self::Math => {
                let expr = script.trim();
                for op in ['+', '-'] {
                    if let Some(idx) = expr.find(op) {
                        let left: i64 = expr[..idx]
                            .trim()
                            .parse()
                            .map_err(|e| format!("math parse error: {e}"))?;
                        let right: i64 = expr[idx + 1..]
                            .trim()
                            .parse()
                            .map_err(|e| format!("math parse error: {e}"))?;
                        let result = if op == '+' { left + right } else { left - right };
                        return Ok(Value::Number(serde_json::Number::from(result)));
                    }
                }
                // Also support multiplication
                if let Some(idx) = expr.find('*') {
                    let left: i64 = expr[..idx]
                        .trim()
                        .parse()
                        .map_err(|e| format!("math parse error: {e}"))?;
                    let right: i64 = expr[idx + 1..]
                        .trim()
                        .parse()
                        .map_err(|e| format!("math parse error: {e}"))?;
                    return Ok(Value::Number(serde_json::Number::from(left * right)));
                }
                Err(format!("math handler cannot evaluate: {}", expr))
            }
        }
    }
}

// ── Native-only adapters ────────────────────────────────────────────

#[cfg(feature = "native")]
mod native {
    use super::*;
    use std::process::Command;

    fn run_subprocess(cmd: &mut Command, script: &str) -> Result<Value, String> {
        let output = cmd
            .arg(script)
            .output()
            .map_err(|e| format!("subprocess failed: {e}"))?;
        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout).to_string();
            Ok(Value::String(stdout))
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr).to_string();
            Err(format!("subprocess exited {}: {}", output.status, stderr))
        }
    }

    fn resolve_clm_root_path() -> std::path::PathBuf {
        if let Ok(val) = std::env::var("CLM_ROOT") {
            let path = crate::fs_utils::normalize_windows_path(std::path::Path::new(&val));
            if path.is_absolute() {
                return path;
            } else if let Ok(curr) = std::env::current_dir() {
                return curr.join(path);
            } else {
                return path;
            }
        }

        if let Ok(mut dir) = std::env::current_dir() {
            loop {
                if dir.join("computable_knowledge/Concrete/layer5_system/bootstrap/evaluator").is_dir()
                    || dir.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator").is_dir() {
                    return dir;
                }
                if dir.join("clm/computable_knowledge/Concrete/layer5_system/bootstrap/evaluator").is_dir()
                    || dir.join("clm/computable_knowledge/Abstract/layer5_system/bootstrap/evaluator").is_dir() {
                    return dir.join("clm");
                }
                if let Some(parent) = dir.parent() {
                    dir = parent.to_path_buf();
                } else {
                    break;
                }
            }
        }
        crate::fs_utils::get_clm_root()
    }

    fn resolve_python_cmd(clm_root: &str) -> String {
        let root_path = std::path::Path::new(clm_root);
        let venv_py_win = root_path.join(".venv/Scripts/python.exe");
        if venv_py_win.exists() {
            return venv_py_win.to_string_lossy().to_string();
        }
        let venv_py_unix = root_path.join(".venv/bin/python3");
        if venv_py_unix.exists() {
            return venv_py_unix.to_string_lossy().to_string();
        }
        let venv_py_unix_2 = root_path.join(".venv/bin/python");
        if venv_py_unix_2.exists() {
            return venv_py_unix_2.to_string_lossy().to_string();
        }

        if cfg!(target_os = "windows") {
            for cmd in &["python", "python3"] {
                if std::process::Command::new(cmd).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {
                    return cmd.to_string();
                }
            }
        } else {
            for cmd in &["python3", "python"] {
                if std::process::Command::new(cmd).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {
                    return cmd.to_string();
                }
            }
        }
        "python3".to_string()
    }

    /// Shell runtime adapter — executes scripts via `bash -c`.
    pub struct ShellRuntimeAdapter;

    impl RuntimeAdapter for ShellRuntimeAdapter {
        fn name(&self) -> &str {
            "shell"
        }

        fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
            let bash = crate::fs_utils::get_bash_command();
            let clm_root = resolve_clm_root_path();
            let clm_root_str = clm_root.to_string_lossy();
            let full_script = format!(
                "export CLM_ROOT=\"{clm_root}\"\n\
                 clm_root() {{ echo \"$CLM_ROOT\"; }}\n\
                 export -f clm_root 2>/dev/null || true\n\
                 source \"{clm_root}/computable_knowledge/Concrete/layer5_system/bootstrap/evaluator/shell_utils.sh\" 2>/dev/null || true\n\
                 source \"{clm_root}/computable_knowledge/Concrete/layer5_system/bootstrap/layer0_core/mcard_storage.sh\" 2>/dev/null || true\n\
                 {script}",
                clm_root = clm_root_str,
                script = script
            );
            let mut cmd = Command::new(bash);
            cmd.env("CLM_ROOT", clm_root_str.as_ref());
            cmd.arg("-c");
            run_subprocess(&mut cmd, &full_script)
        }
    }

    /// Python runtime adapter — executes scripts via `python3 -c`.
    pub struct PythonRuntimeAdapter;

    impl RuntimeAdapter for PythonRuntimeAdapter {
        fn name(&self) -> &str {
            "python"
        }

        fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
            let clm_root_path = resolve_clm_root_path();
            let clm_root_str = clm_root_path.to_string_lossy();
            let py_cmd = resolve_python_cmd(&clm_root_str);
            let mut cmd = Command::new(py_cmd);
            cmd.arg("-c");
            cmd.env("CLM_ROOT", clm_root_str.as_ref());
            cmd.env("PYTHONPATH", format!("{}/kernel/scripts", clm_root_str));
            run_subprocess(&mut cmd, script)
        }
    }

    /// Node.js runtime adapter — executes scripts via `node -e`.
    pub struct NodeRuntimeAdapter;

    impl RuntimeAdapter for NodeRuntimeAdapter {
        fn name(&self) -> &str {
            "node"
        }

        fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
            let mut cmd = Command::new("node");
            cmd.arg("-e");
            run_subprocess(&mut cmd, script)
        }
    }

    /// LLM runtime adapter — sends script as a prompt to an LLM API endpoint.
    ///
    /// Under native, uses `ureq` for synchronous HTTP POST.
    /// Under WASM, a scaffold is provided that returns an error (async HTTP fetch
    /// via `wasm-bindgen-futures` is future work).
    ///
    /// The endpoint URL and API key are read from `CLM_LLM_ENDPOINT` and
    /// `CLM_LLM_API_KEY` environment variables. If not set, defaults to
    /// `http://localhost:8080/v1/chat/completions` with no auth.
    pub struct LlmRuntimeAdapter {
        endpoint: String,
        api_key: Option<String>,
    }

    impl Default for LlmRuntimeAdapter {
        fn default() -> Self {
            Self::new()
        }
    }

    impl LlmRuntimeAdapter {
        pub fn new() -> Self {
            let endpoint = std::env::var("CLM_LLM_ENDPOINT")
                .unwrap_or_else(|_| "http://localhost:8080/v1/chat/completions".to_string());
            let api_key = std::env::var("CLM_LLM_API_KEY").ok();
            Self { endpoint, api_key }
        }
    }

    impl RuntimeAdapter for LlmRuntimeAdapter {
        fn name(&self) -> &str {
            "llm"
        }

        fn execute(&self, script: &str, input: &Value) -> Result<Value, String> {
            let user_message = if input.is_null() {
                script.to_string()
            } else {
                format!("{}\n{}", script, input)
            };

            let body = serde_json::json!({
                "messages": [
                    {"role": "user", "content": user_message}
                ],
                "stream": false
            });

            let mut req = ureq::post(&self.endpoint)
                .set("Content-Type", "application/json");
            if let Some(ref key) = self.api_key {
                req = req.set("Authorization", &format!("Bearer {}", key));
            }

            let response: Value = req
                .send_json(body)
                .map_err(|e| format!("LLM HTTP request failed: {}", e))?
                .into_json()
                .map_err(|e| format!("LLM response parse error: {}", e))?;

            // Extract the assistant's message content from the response.
            let content = response
                .get("choices")
                .and_then(|c| c.get(0))
                .and_then(|c| c.get("message"))
                .and_then(|m| m.get("content"))
                .and_then(|c| c.as_str())
                .unwrap_or("")
                .to_string();

            Ok(Value::String(content))
        }
    }
}

#[cfg(feature = "native")]
pub use native::{LlmRuntimeAdapter, NodeRuntimeAdapter, PythonRuntimeAdapter, ShellRuntimeAdapter};

// ── Tests ───────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_dispatcher_registers_builtin_handlers() {
        let d = RuntimeDispatcher::with_defaults();
        assert!(d.has("echo"));
        assert!(d.has("noop"));
        assert!(d.has("math"));
    }

    #[test]
    fn test_dispatcher_echo() {
        let d = RuntimeDispatcher::with_defaults();
        let result = d.dispatch("echo", "hello world", &Value::Null).unwrap();
        assert_eq!(result, Value::String("hello world".to_string()));
    }

    #[test]
    fn test_dispatcher_noop() {
        let d = RuntimeDispatcher::with_defaults();
        let result = d.dispatch("noop", "ignored", &Value::Null).unwrap();
        assert_eq!(result, Value::String(String::new()));
    }

    #[test]
    fn test_dispatcher_math_addition() {
        let d = RuntimeDispatcher::with_defaults();
        let result = d.dispatch("math", "3 + 4", &Value::Null).unwrap();
        assert_eq!(result, Value::Number(serde_json::Number::from(7)));
    }

    #[test]
    fn test_dispatcher_math_subtraction() {
        let d = RuntimeDispatcher::with_defaults();
        let result = d.dispatch("math", "10 - 3", &Value::Null).unwrap();
        assert_eq!(result, Value::Number(serde_json::Number::from(7)));
    }

    #[test]
    fn test_dispatcher_math_multiplication() {
        let d = RuntimeDispatcher::with_defaults();
        let result = d.dispatch("math", "6 * 7", &Value::Null).unwrap();
        assert_eq!(result, Value::Number(serde_json::Number::from(42)));
    }

    #[test]
    fn test_dispatcher_unknown_runtime_errors() {
        let d = RuntimeDispatcher::with_defaults();
        let result = d.dispatch("nonexistent", "script", &Value::Null);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("unknown runtime"));
    }

    #[test]
    fn test_dispatcher_list_runtimes() {
        let d = RuntimeDispatcher::with_defaults();
        let runtimes = d.list_runtimes();
        assert!(runtimes.contains(&"echo"));
        assert!(runtimes.contains(&"noop"));
        assert!(runtimes.contains(&"math"));
    }

    #[test]
    fn test_dispatcher_custom_adapter() {
        struct UpperAdapter;
        impl RuntimeAdapter for UpperAdapter {
            fn name(&self) -> &str {
                "upper"
            }
            fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
                Ok(Value::String(script.to_uppercase()))
            }
        }

        let mut d = RuntimeDispatcher::new();
        d.register("upper", Box::new(UpperAdapter));
        let result = d.dispatch("upper", "hello", &Value::Null).unwrap();
        assert_eq!(result, Value::String("HELLO".to_string()));
    }

    #[cfg(feature = "native")]
    #[test]
    fn test_dispatcher_has_native_adapters() {
        let d = RuntimeDispatcher::with_defaults();
        assert!(d.has("shell"));
        assert!(d.has("python"));
        assert!(d.has("node"));
        assert!(d.has("llm"));
    }

    #[cfg(feature = "native")]
    #[test]
    fn test_dispatcher_shell_echo() {
        let d = RuntimeDispatcher::with_defaults();
        let result = d.dispatch("shell", "echo hello_from_shell", &Value::Null).unwrap();
        assert!(result.as_str().unwrap().contains("hello_from_shell"));
    }

    #[test]
    fn test_wasm_adapter_implements_trait() {
        let echo: Box<dyn RuntimeAdapter> = Box::new(WasmRuntimeAdapter::Echo);
        assert_eq!(echo.name(), "echo");
        let result = echo.execute("test", &Value::Null).unwrap();
        assert_eq!(result, Value::String("test".to_string()));
    }
}