clm-kernel 0.0.19

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use std::collections::HashMap;
use std::path::Path;
use serde_json::Value;
use super::metrics::{get_peak_rss_kb, get_children_peak_rss_kb};
use super::config::{create_sandboxed_command, resolve_python_cmd, resolve_self_exe};
use crate::yaml;

pub struct RuntimeRunResult {
    pub run_status: i32,
    pub stdout_data: String,
    pub stderr_data: String,
    pub elapsed_ms: i64,
    pub peak_rss_val: i64,
    pub fork_count: i64,
}

pub fn execute_runtime_case(
    runtime: &str,
    case_name: &str,
    parsed: &Value,
    internal_ref: Option<&str>,
    native_harness: Option<&Value>,
    pos_args: &[String],
    env_vars: &HashMap<String, String>,
    file_path: &str,
    clm_root: &str,
) -> Result<RuntimeRunResult, String> {
    let mut fork_count = 0;
    let elapsed_ms;
    let peak_rss_val;

    let (run_status, stdout_data, stderr_data) = if runtime == "rust" && internal_ref.is_some() {
        let ref_path = internal_ref.unwrap();
        let func = crate::evaluator::get_internal_registry(ref_path)
            .ok_or_else(|| format!("No internal function registered for path '{}'", ref_path))?;
        
        let start_time = std::time::Instant::now();
        let _start_rss = get_peak_rss_kb();

        let run_res = {
            let _sandbox_guard = crate::db::DatabaseSandboxGuard::activate(case_name);
            func(clm_root, file_path)
        };

        elapsed_ms = start_time.elapsed().as_millis() as i64;
        let end_rss = get_peak_rss_kb();
        peak_rss_val = end_rss;

        let (code, out) = run_res.map_err(|e| format!("Internal dispatch error: {}", e))?;
        (code, out, String::new())
    } else if let Some(harness) = native_harness {
        let tool = harness.get("tool").and_then(|v| v.as_str()).ok_or("No tool specified in native_harness")?;
        let cmd_arg = harness.get("command").and_then(|v| v.as_str()).ok_or("No command specified in native_harness")?;
        
        fork_count += 1;
        let full_cmd = format!("{} {}", tool, cmd_arg);
        let start_time = std::time::Instant::now();
        let start_rss = get_children_peak_rss_kb();

        let mut cmd = create_sandboxed_command(&crate::fs_utils::get_bash_command(), &["-c".to_string(), full_cmd], env_vars, clm_root);
        let output = cmd.output().map_err(|e| format!("Failed to spawn native_harness: {}", e))?;
        
        elapsed_ms = start_time.elapsed().as_millis() as i64;
        let end_rss = get_children_peak_rss_kb();
        peak_rss_val = if end_rss > start_rss { end_rss - start_rss } else { 0 };

        (output.status.code().unwrap_or(0), String::from_utf8_lossy(&output.stdout).into_owned(), String::from_utf8_lossy(&output.stderr).into_owned())
    } else {
        let impl_path = format!(".clm.concrete_impl.process.implementations.{}", runtime);
        let script_val = yaml::evaluate_jq(parsed, &format!("{}.script", impl_path));
        let handle_val = yaml::evaluate_jq(parsed, &format!("{}.script_handle", impl_path));
        let cargo_val = yaml::evaluate_jq(parsed, &format!("{}.cargo_test", impl_path));
        
        let mut script_content = script_val.as_str().unwrap_or("").to_string();
        let cargo_test_name = cargo_val.as_str().unwrap_or("").to_string();

        if script_content.is_empty() && let Some(handle) = handle_val.as_str() && handle.starts_with("script:") {
            let s_name = handle.trim_start_matches("script:");
            let sh_path = Path::new(clm_root).join("scripts").join(format!("{}.sh", s_name));
            if let Ok(content) = std::fs::read_to_string(&sh_path) {
                script_content = content;
            } else {
                let sh_path = Path::new(clm_root).join("tests").join("00_microkernel").join(format!("{}.sh", s_name));
                if let Ok(content) = std::fs::read_to_string(&sh_path) {
                    script_content = content;
                }
            }
        }

        if script_content.is_empty() && cargo_test_name.is_empty() {
            return Err(format!("Skipping runtime '{}' because no script or cargo_test is defined", runtime));
        }

        let entry_point_val = yaml::evaluate_jq(parsed, ".clm.concrete_impl.process.entry_point");
        let entry_point = entry_point_val.as_str().unwrap_or("");

        fork_count += 1;
        let start_time = std::time::Instant::now();
        let _start_rss = get_children_peak_rss_kb();

        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 {
                    "".to_string()
                };
                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], env_vars, 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.iter().cloned());
                let mut py_env_vars = env_vars.clone();
                py_env_vars.insert("PYTHONPATH".to_string(), format!("{}/kernel/clm_py_core", clm_root));
                let mut cmd = create_sandboxed_command(&py_cmd, &cmd_args, &py_env_vars, 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.iter().cloned());
                let mut cmd = create_sandboxed_command("node", &cmd_args, env_vars, 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()],
                        env_vars,
                        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 Err(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 env_vars {
                        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(),
                    )
                }
            }
            _ => unreachable!(),
        };

        elapsed_ms = start_time.elapsed().as_millis() as i64;
        let end_rss = get_children_peak_rss_kb();
        #[cfg(unix)]
        {
            peak_rss_val = if end_rss > _start_rss { end_rss - _start_rss } else { 0 };
        }
        #[cfg(windows)]
        {
            peak_rss_val = end_rss;
        }

        (code, out, err)
    };

    Ok(RuntimeRunResult {
        run_status,
        stdout_data,
        stderr_data,
        elapsed_ms,
        peak_rss_val,
        fork_count,
    })
}