clm-kernel 0.0.11

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
#![allow(unused_imports)]
use super::*;

/// Execute a script in the named runtime and return (exit_code, stdout, stderr).
///
/// This is a standalone runtime dispatch function that handles shell, python, node,
/// and rust runtimes with environment variables, entry points, and cargo test support.
/// It is called by the `exec-runtime-script` CLI command to enable Python code to
/// delegate runtime execution to the Rust binary instead of spawning subprocesses.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RuntimeScriptInput {
    pub runtime: String,
    pub script: String,
    #[serde(default)]
    pub env: HashMap<String, String>,
    #[serde(default)]
    pub entry_point: String,
    #[serde(default)]
    pub cargo_test: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub clm_root: String,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RuntimeScriptOutput {
    pub exit_code: i32,
    pub stdout: String,
    pub stderr: String,
}

pub fn exec_runtime_script(input: &RuntimeScriptInput) -> Result<RuntimeScriptOutput, String> {
    let clm_root = if input.clm_root.is_empty() {
        std::env::var("CLM_ROOT").unwrap_or_default()
    } else {
        input.clm_root.clone()
    };

    let runtime = input.runtime.as_str();
    let script_content = input.script.as_str();
    let entry_point = input.entry_point.as_str();
    let cargo_test_name = input.cargo_test.as_str();
    let pos_args = &input.args;

    let (code, out, err) = match runtime {
        "shell" => {
            let entry_call = if !entry_point.is_empty() {
                let mut call = format!("{} ", entry_point);
                for a in pos_args {
                    call.push_str(&format!("\"{}\" ", a.replace('"', "\\\"")));
                }
                call
            } else {
                String::new()
            };
            let full_script = format!("{}\n{}", script_content, entry_call);
            let mut cmd = create_sandboxed_command(
                &crate::fs_utils::get_bash_command(),
                &["-c".to_string(), full_script],
                &input.env,
                &clm_root,
            );
            let output = cmd.output().map_err(|e| format!("Failed to spawn bash: {}", e))?;
            (
                output.status.code().unwrap_or(0),
                String::from_utf8_lossy(&output.stdout).into_owned(),
                String::from_utf8_lossy(&output.stderr).into_owned(),
            )
        }
        "python" => {
            let py_cmd = resolve_python_cmd(&clm_root);
            let mut cmd_args = vec!["-c".to_string(), script_content.to_string()];
            cmd_args.extend(pos_args.clone());
            let mut py_env = input.env.clone();
            py_env.insert("PYTHONPATH".to_string(), format!("{}/kernel/scripts", clm_root));
            let mut cmd = create_sandboxed_command(&py_cmd, &cmd_args, &py_env, &clm_root);
            let output = cmd.output().map_err(|e| format!("Failed to spawn python: {}", e))?;
            (
                output.status.code().unwrap_or(0),
                String::from_utf8_lossy(&output.stdout).into_owned(),
                String::from_utf8_lossy(&output.stderr).into_owned(),
            )
        }
        "node" => {
            let rand_id = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0);
            let pid = std::process::id();
            let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
            let _ = std::fs::create_dir_all(&temp_dir);
            let temp_file = temp_dir.join(format!("clm_node_inline_{}_{}.cjs", rand_id, pid));
            std::fs::write(&temp_file, script_content)
                .map_err(|e| format!("Failed to write node inline script: {}", e))?;
            let mut cmd_args = vec!["--trace-uncaught".to_string(), temp_file.to_string_lossy().to_string()];
            cmd_args.extend(pos_args.clone());
            let mut cmd = create_sandboxed_command("node", &cmd_args, &input.env, &clm_root);
            let output = cmd.output();
            let _ = std::fs::remove_file(&temp_file);
            let output = output.map_err(|e| format!("Failed to spawn node: {}", e))?;
            (
                output.status.code().unwrap_or(0),
                String::from_utf8_lossy(&output.stdout).into_owned(),
                String::from_utf8_lossy(&output.stderr).into_owned(),
            )
        }
        "rust" => {
            if !cargo_test_name.is_empty() {
                let self_exe = resolve_self_exe(&clm_root);
                let mut cmd = create_sandboxed_command(
                    &self_exe.to_string_lossy(),
                    &["run-test".to_string(), cargo_test_name.to_string()],
                    &input.env,
                    &clm_root,
                );
                cmd.current_dir(Path::new(&clm_root).join("kernel/clm_rust_core"));
                let output = cmd.output().map_err(|e| format!("Failed to spawn clm_rust_core: {}", e))?;
                (
                    output.status.code().unwrap_or(if output.status.success() { 0 } else { 1 }),
                    String::from_utf8_lossy(&output.stdout).into_owned(),
                    String::from_utf8_lossy(&output.stderr).into_owned(),
                )
            } else {
                let rand_id = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_nanos())
                    .unwrap_or(0);
                let pid = std::process::id();
                let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
                let _ = std::fs::create_dir_all(&temp_dir);
                let src_file = temp_dir.join(format!("clm_rust_inline_{}_{}.rs", rand_id, pid));
                let bin_file = temp_dir.join(format!("clm_rust_bin_{}_{}", rand_id, pid));
                let full_rust_src = if !script_content.contains("fn main") {
                    format!("use std::io::{{self, Read}};\nfn main() {{\n{}\n}}", script_content)
                } else {
                    script_content.to_string()
                };
                std::fs::write(&src_file, full_rust_src)
                    .map_err(|e| format!("Failed to write rust inline source: {}", e))?;
                let compile_output = std::process::Command::new("rustc")
                    .arg("-O")
                    .arg("-o")
                    .arg(&bin_file)
                    .arg(&src_file)
                    .output();
                let _ = std::fs::remove_file(&src_file);
                let compile_res = compile_output.map_err(|e| format!("Failed to run rustc: {}", e))?;
                if !compile_res.status.success() {
                    return Ok(RuntimeScriptOutput {
                        exit_code: 1,
                        stdout: String::new(),
                        stderr: format!("Rust compilation failed:\n{}", String::from_utf8_lossy(&compile_res.stderr)),
                    });
                }
                let mut cmd = std::process::Command::new(&bin_file);
                for a in pos_args {
                    cmd.arg(a);
                }
                for (k, v) in &input.env {
                    cmd.env(k, v);
                }
                cmd.current_dir(&clm_root);
                let output = cmd.output();
                let _ = std::fs::remove_file(&bin_file);
                let output = output.map_err(|e| format!("Failed to run rust binary: {}", e))?;
                (
                    output.status.code().unwrap_or(0),
                    String::from_utf8_lossy(&output.stdout).into_owned(),
                    String::from_utf8_lossy(&output.stderr).into_owned(),
                )
            }
        }
        _ => {
            return Err(format!("Unsupported runtime: {}", runtime));
        }
    };

    Ok(RuntimeScriptOutput {
        exit_code: code,
        stdout: out,
        stderr: err,
    })
}