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, PathBuf};

pub fn resolve_python_cmd(clm_root: &str) -> String {
    let local_venv = Path::new(clm_root).join(".venv");
    if local_venv.exists() {
        let venv_py = if cfg!(target_os = "windows") {
            local_venv.join("Scripts").join("python.exe")
        } else {
            local_venv.join("bin").join("python")
        };
        if venv_py.exists() {
            return venv_py.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();
            }
        }
    }
    
    if cfg!(target_os = "windows") {
        "python".to_string()
    } else {
        "python3".to_string()
    }
}

pub fn get_interpreter_version(interpreter: &str, clm_root: &str) -> Option<String> {
    let cmd_name = match interpreter {
        "python" | "python3" => resolve_python_cmd(clm_root),
        other => other.to_string(),
    };
    let output = std::process::Command::new(&cmd_name)
        .arg("--version")
        .output()
        .ok();
    if let Some(out) = output {
        let text = String::from_utf8_lossy(&out.stdout).to_string()
            + String::from_utf8_lossy(&out.stderr).as_ref();
        let re = regex::Regex::new(r"(\d+\.\d+(?:\.\d+)?)").unwrap();
        if let Some(caps) = re.captures(&text) {
            return Some(caps[1].to_string());
        }
    }
    None
}

pub fn compare_versions(current: &str, op: &str, req: &str) -> bool {
    let parse_ver = |s: &str| -> (u32, u32, u32) {
        let parts: Vec<&str> = s.split('.').collect();
        let major = parts.first().and_then(|v| v.parse().ok()).unwrap_or(0);
        let minor = parts.get(1).and_then(|v| v.parse().ok()).unwrap_or(0);
        let patch = parts.get(2).and_then(|v| v.parse().ok()).unwrap_or(0);
        (major, minor, patch)
    };
    let v1 = parse_ver(current);
    let v2 = parse_ver(req);
    match op {
        ">=" => v1 >= v2,
        "<=" => v1 <= v2,
        ">" => v1 > v2,
        "<" => v1 < v2,
        _ => v1 == v2,
    }
}

pub fn check_precondition(req_str: &str, clm_root: &str) -> bool {
    let re = regex::Regex::new(r"^interpreter:([a-zA-Z0-9_-]+)(>=|<=|>|<|==|=)([0-9.]+)$").unwrap();
    if let Some(caps) = re.captures(req_str) {
        let interpreter = &caps[1];
        let op = &caps[2];
        let req_ver = &caps[3];
        if let Some(current_ver) = get_interpreter_version(interpreter, clm_root) {
            compare_versions(&current_ver, op, req_ver)
        } else {
            false
        }
    } else {
        true
    }
}

pub fn resolve_self_exe(clm_root: &str) -> PathBuf {
    if let Ok(self_exe) = std::env::current_exe() {
        if self_exe.to_string_lossy().contains("deps") {
            let alt_exe = Path::new(clm_root).join({
                #[cfg(windows)] { "kernel/clm_rust_core/target/debug/clm_rust_core.exe" }
                #[cfg(not(windows))] { "kernel/clm_rust_core/target/debug/clm_rust_core" }
            });
            if alt_exe.exists() {
                return alt_exe;
            }
            let alt_exe_release = Path::new(clm_root).join({
                #[cfg(windows)] { "kernel/clm_rust_core/target/release/clm_rust_core.exe" }
                #[cfg(not(windows))] { "kernel/clm_rust_core/target/release/clm_rust_core" }
            });
            if alt_exe_release.exists() {
                return alt_exe_release;
            }
        }
        if let Some(parent) = self_exe.parent() {
            let local_exe = parent.join({
                #[cfg(windows)] { "clm_rust_core.exe" }
                #[cfg(not(windows))] { "clm_rust_core" }
            });
            if local_exe.exists() {
                return local_exe;
            }
        }
        return self_exe;
    }
    Path::new(clm_root).join({
        #[cfg(windows)] { "kernel/clm_rust_core/target/release/clm_rust_core.exe" }
        #[cfg(not(windows))] { "kernel/clm_rust_core/target/release/clm_rust_core" }
    })
}

pub fn create_sandboxed_command(
    program: &str,
    args: &[String],
    envs: &HashMap<String, String>,
    clm_root: &str,
) -> std::process::Command {
    let clm_no_sandbox = envs.get("CLM_NO_SANDBOX").map(|v| v == "true").unwrap_or_else(|| {
        crate::cross_cutting::context::CLMContext::get_scoped_or_env("CLM_NO_SANDBOX")
            .unwrap_or_default()
            == "true"
    });
    let has_sandbox_exec = std::process::Command::new("which")
        .arg("sandbox-exec")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    let mut cmd = if !clm_no_sandbox && has_sandbox_exec {
        let home_dir = std::env::var("HOME").unwrap_or_default();
        let profile = format!(
            r#"(version 1)
(deny default)
(allow file-read-metadata)
(allow file-read-data)
(allow file-write-data)
(allow file-read*
    (subpath "/usr")
    (subpath "/System")
    (subpath "/Library")
    (subpath "/private")
    (subpath "/var")
    (subpath "/tmp")
    (subpath "/etc")
    (subpath "/opt")
    (subpath "/dev")
    (subpath "{}")
    (subpath "{}"))
(allow file-write*
    (subpath "{}/data")
    (subpath "{}/db")
    (subpath "{}/types/meta")
    (literal "{}/result_open_interpreter.txt")
    (subpath "{}/.clm")
    (subpath "/private/var")
    (subpath "/private/tmp")
    (subpath "/var")
    (subpath "/tmp")
    (literal "/dev/null")
    (literal "/dev/zero"))
(allow file-map-executable
    (subpath "/usr")
    (subpath "/System")
    (subpath "/Library")
    (subpath "/opt")
    (subpath "{}")
    (subpath "{}"))
(allow process-exec
    (subpath "/bin")
    (subpath "/usr/bin")
    (subpath "/usr/local/bin")
    (subpath "/opt/homebrew")
    (subpath "/Library/Frameworks/Python.framework")
    (subpath "/Library/Developer/CommandLineTools")
    (subpath "/private/var")
    (subpath "/var")
    (subpath "/tmp")
    (subpath "{}")
    (subpath "{}"))
(allow process-fork)
(allow process-info*)
(allow ipc-posix*)
(allow sysctl-read)
(allow mach-lookup)
(allow dynamic-code-generation)
(allow network-bind)
(allow network-inbound)
(allow network-outbound)
(deny file-read*
    (literal "/private/etc/passwd")
    (literal "/etc/passwd"))
(deny file-read-data
    (literal "/private/etc/passwd")
    (literal "/etc/passwd"))"#,
            clm_root, home_dir, clm_root, clm_root, clm_root, clm_root, home_dir, clm_root, home_dir, clm_root, home_dir
        );

        let mut scmd = std::process::Command::new("sandbox-exec");
        scmd.arg("-p").arg(profile).arg(program);
        scmd
    } else {
        std::process::Command::new(program)
    };

    for var_name in &["CLM_ACTIVE_A_HASH", "CLM_ACTIVE_C_HASH", "CLM_ACTIVE_INSTANCE_ID", "CLM_CALLING_PCARD", "CLM_SYSTEM_CALL"] {
        if let Some(val) = crate::cross_cutting::context::CLMContext::get_scoped_or_env(var_name) {
            cmd.env(var_name, val);
        }
    }
    crate::cross_cutting::context::CLMContext::apply_current_to_command(&mut cmd);
    for (k, v) in envs {
        cmd.env(k, v);
    }
    for a in args {
        cmd.arg(a);
    }
    cmd
}

pub fn normalize_output(raw_out: &str) -> String {
    use serde_json::Value;
    let stripped = raw_out.replace('\r', "");
    let stripped = stripped.trim_end().to_string();
    if let Ok(val) = serde_json::from_str::<Value>(&stripped) {
        serde_json::to_string(&val).unwrap_or(stripped)
    } else {
        stripped
    }
}

pub fn print_diff(first_norm: &str, second_norm: &str) {
    let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
    let f1 = temp_dir.join(format!("norm_f1_{}", std::process::id()));
    let f2 = temp_dir.join(format!("norm_f2_{}", std::process::id()));
    let _ = std::fs::write(&f1, first_norm);
    let _ = std::fs::write(&f2, second_norm);
    
    let diff_output = std::process::Command::new("diff")
        .arg("-u")
        .arg(&f1)
        .arg(&f2)
        .output();
    if let Ok(out) = diff_output {
        let text = String::from_utf8_lossy(&out.stdout);
        eprintln!("{}", text);
    }
    
    let _ = std::fs::remove_file(f1);
    let _ = std::fs::remove_file(f2);
}