clm-kernel 0.0.14

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
#![allow(unused_imports)]
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
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,
/// rust, and formal runtimes with environment variables, entry points, and cargo test support.
#[derive(Debug, Clone, Default, 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,
    #[serde(default)]
    pub source_file: Option<String>,
    #[serde(default)]
    pub source_name: Option<String>,
    #[serde(default)]
    pub theorem_name: Option<String>,
    #[serde(default)]
    pub profile_id: Option<String>,
    #[serde(default)]
    pub config_file: Option<String>,
    #[serde(default)]
    pub staged_files: BTreeMap<String, String>,
    #[serde(default)]
    pub strict: bool,
    #[serde(default)]
    pub isolated_empty_path: bool,
}

/// Output payload produced by `exec_runtime_script`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RuntimeScriptOutput {
    pub exit_code: i32,
    pub stdout: String,
    pub stderr: String,
}

#[cfg(feature = "native")]
fn dispatch_formal_input(
    runtime: &str,
    input: &RuntimeScriptInput,
    clm_root: &str,
) -> Result<crate::layer4::FormalDispatchOutcome, String> {
    let target = crate::layer4::formal_contract::resolve_formal_target(
        runtime,
        input.profile_id.as_deref(),
        None,
        None,
        clm_root,
    )?;
    let ep_raw = input.entry_point.as_str();
    let (prof_id, ep_opt) = if let Some(p) = input.profile_id.as_deref().filter(|s| !s.is_empty()) {
        (Some(p.to_string()), (!ep_raw.is_empty()).then(|| ep_raw.to_string()))
    } else if !ep_raw.is_empty() && target.known_profiles.contains(ep_raw) {
        (Some(ep_raw.to_string()), None)
    } else {
        (None, (!ep_raw.is_empty()).then(|| ep_raw.to_string()))
    };
    let (src_file, src_text, src_name, extra_args) =
        if let Some(sf) = input.source_file.as_deref().filter(|s| !s.is_empty()) {
            (Some(sf.to_string()), None, None, input.args.clone())
        } else if !input.script.is_empty() || input.source_name.as_deref().is_some_and(|s| !s.is_empty()) {
            let sname = input
                .source_name
                .as_deref()
                .filter(|s| !s.is_empty())
                .map(String::from)
                .unwrap_or_else(|| format!("Spec{}", target.default_extension));
            (None, Some(input.script.clone()), Some(sname), input.args.clone())
        } else if let Some((first, rest)) = input.args.split_first() {
            (Some(first.clone()), None, None, rest.to_vec())
        } else {
            return Err("Formal oracle requires script content or source file path".to_string());
        };
    let req = crate::layer4::FormalExecutionRequest {
        runtime_id: runtime.to_string(),
        profile_id: prof_id,
        source_file: src_file,
        source_text: src_text,
        source_name: src_name,
        theorem_name: input.theorem_name.clone(),
        entry_point: ep_opt,
        extra_args,
        config_file: input.config_file.clone(),
        staged_files: input.staged_files.clone(),
        strict: input.strict,
        isolated_empty_path: input.isolated_empty_path,
        clm_root: clm_root.to_string(),
        ..Default::default()
    };
    let env_ref = if input.env.is_empty() && !input.isolated_empty_path { None } else { Some(&input.env) };
    crate::layer4::formal_oracle_runner::execute_formal_request(&req, env_ref)
}

/// Dispatch a `RuntimeScriptInput` across host shell, Python, Node, Rust, and formal toolchains.
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_norm = input.runtime.trim().to_ascii_lowercase();
    let runtime = runtime_norm.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 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, std::process::id()));
            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);
                cmd.args(pos_args).envs(&input.env).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(),
                )
            }
        }
        #[cfg(feature = "native")]
        "lean" | "coq" | "rocq" | "julia" | "tlaplus" | "tla" | "tlc" | "apalache" | "java" => {
            let outcome = dispatch_formal_input(runtime, input, &clm_root)?;
            (outcome.exit_code, outcome.stdout, outcome.stderr)
        }
        _ => return Err(format!("Unsupported runtime: {}", input.runtime)),
    };

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

#[cfg(all(test, feature = "native"))]
mod formal_dispatch_tests {
    use super::*;

    #[test]
    fn test_formal_oracle_dispatches_native() {
        let valid_input = RuntimeScriptInput {
            runtime: "lean".to_string(),
            script: "theorem clc02_rust_bridge_ok : 2 + 2 = 4 := rfl\n".to_string(),
            ..Default::default()
        };
        let valid_out = exec_runtime_script(&valid_input).expect("native formal dispatch");
        let valid_witness: crate::layer4::OracleWitness = serde_json::from_str(&valid_out.stdout).expect("witness json");
        assert_eq!(valid_out.exit_code, 0);
        assert_eq!(valid_witness.status, crate::layer4::OracleWitnessStatus::Verified);
        assert_eq!(valid_witness.argv, vec!["lean", "--json", "Spec.lean"]);

        let sorry_input = RuntimeScriptInput {
            runtime: "lean".to_string(),
            script: "theorem clc02_rust_bridge_sorry : 1 = 1 := by sorry\n".to_string(),
            ..Default::default()
        };
        let sorry_out = exec_runtime_script(&sorry_input).expect("native formal sorry dispatch");
        let sorry_witness: crate::layer4::OracleWitness = serde_json::from_str(&sorry_out.stdout).expect("sorry witness json");
        assert_eq!(sorry_out.exit_code, 1);
        assert_eq!(sorry_witness.status, crate::layer4::OracleWitnessStatus::Refuted);

        let tla_isolated = RuntimeScriptInput {
            runtime: "tla".to_string(),
            script: "---- MODULE M ----\n====\n".to_string(),
            source_name: Some("M.tla".to_string()),
            isolated_empty_path: true,
            ..Default::default()
        };
        let tla_out = exec_runtime_script(&tla_isolated).expect("tla alias dispatch");
        let tla_w: crate::layer4::OracleWitness = serde_json::from_str(&tla_out.stdout).expect("tla witness json");
        assert_eq!(tla_w.runtime_id, "tlaplus");
        assert_eq!(tla_w.profile_id, "tlc");
        assert_eq!(tla_w.status, crate::layer4::OracleWitnessStatus::SkippedUnavailable);
    }
}