clm-kernel 0.0.23

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use clap::Subcommand;
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};

use clm_rust_core::layer4::{
    execute_formal_request, list_formal_runtimes, probe_formal_runtime, resolve_formal_target,
    FormalExecutionRequest, OracleWitnessStatus,
};

#[derive(Subcommand, Debug, Clone)]
pub enum RuntimeSubcommand {
    #[command(name = "list", about = "List registered formal runtimes and profiles")]
    List {
        #[arg(long)]
        json: bool,
    },
    #[command(name = "probe", about = "Probe availability of a formal runtime profile")]
    Probe {
        #[arg(long = "runtime", alias = "runtime-id")]
        runtime: Option<String>,
        #[arg(long = "profile", alias = "profile-id")]
        profile: Option<String>,
        #[arg(long)]
        isolated: bool,
        #[arg(long)]
        json: bool,
        pos_runtime: Option<String>,
    },
    #[command(name = "exec", about = "Execute a FormalExecutionRequest JSON payload")]
    Exec {
        #[arg(long)]
        request: Option<String>,
        #[arg(long)]
        strict: bool,
        #[arg(long)]
        json: bool,
        pos_request: Option<String>,
    },
}

fn resolve_cli_path(raw: &str, clm_root: &str) -> PathBuf {
    let p = Path::new(raw);
    if p.is_absolute() || p.is_file() {
        p.to_path_buf()
    } else {
        Path::new(clm_root).join(p)
    }
}

pub fn run_runtime_subcommand(action: RuntimeSubcommand, clm_root: &str) -> (i32, String, String) {
    match action {
        RuntimeSubcommand::List { .. } => match list_formal_runtimes(clm_root) {
            Ok(catalog) => match serde_json::to_string_pretty(&catalog) {
                Ok(txt) => (0, format!("{}\n", txt), String::new()),
                Err(e) => (2, String::new(), format!("clmEval runtime error: {}\n", e)),
            },
            Err(e) => (2, String::new(), format!("clmEval runtime error: {}\n", e)),
        },
        RuntimeSubcommand::Probe { runtime, profile, isolated, pos_runtime, .. } => {
            let Some(rt_id) = runtime.or(pos_runtime) else {
                return (2, String::new(), "Usage: clmEval runtime probe --runtime <id> [--profile <p>] [--json]\n".to_string());
            };
            let mut iso_env = HashMap::new();
            iso_env.insert("PATH".to_string(), String::new());
            iso_env.insert("HOME".to_string(), "/nonexistent".to_string());
            let env_ref = if isolated { Some(&iso_env) } else { None };
            match probe_formal_runtime(&rt_id, profile.as_deref(), env_ref, !isolated, clm_root) {
                Ok(report) => match serde_json::to_string_pretty(&report) {
                    Ok(txt) => (0, format!("{}\n", txt), String::new()),
                    Err(e) => (2, String::new(), format!("clmEval runtime error: {}\n", e)),
                },
                Err(e) => (2, String::new(), format!("clmEval runtime error: {}\n", e)),
            }
        }
        RuntimeSubcommand::Exec { request, strict, pos_request, .. } => {
            let Some(req_raw) = request.or(pos_request) else {
                return (2, String::new(), "Usage: clmEval runtime exec --request <file> [--strict] [--json]\n".to_string());
            };
            let req_path = resolve_cli_path(&req_raw, clm_root);
            let raw_txt = match std::fs::read_to_string(&req_path) {
                Ok(t) => t,
                Err(e) => return (2, String::new(), format!("clmEval runtime error: {}\n", e)),
            };
            let mut req: FormalExecutionRequest = match serde_json::from_str(&raw_txt) {
                Ok(r) => r,
                Err(e) => return (2, String::new(), format!("clmEval runtime error: {}\n", e)),
            };
            if req.clm_root.is_empty() || req.clm_root == "." {
                req.clm_root = clm_root.to_string();
            }
            if strict {
                req.strict = true;
            }
            match execute_formal_request(&req, None) {
                Ok(outcome) => {
                    let pretty = serde_json::to_string_pretty(&outcome.witness).unwrap_or(outcome.stdout);
                    (outcome.exit_code, format!("{}\n", pretty), String::new())
                }
                Err(e) => (2, String::new(), format!("clmEval runtime error: {}\n", e)),
            }
        }
    }
}

pub fn try_evaluate_formal_clm(target_file: &str, clm_root: &str) -> Option<(i32, String, String)> {
    if !target_file.ends_with(".clm") && !target_file.ends_with(".yaml") && !target_file.ends_with(".yml") {
        return None;
    }
    let manifest_path = resolve_cli_path(target_file, clm_root);
    let raw_txt = std::fs::read_to_string(&manifest_path).ok()?;
    let doc: serde_json::Value = serde_yaml::from_str(&raw_txt).ok()?;
    let clm_node = doc.get("clm").filter(|v| v.is_object()).unwrap_or(&doc);
    let abstract_node = clm_node.get("abstract").or_else(|| clm_node.get("abstract_spec"));
    let concrete = clm_node.get("concrete").or_else(|| clm_node.get("concrete_impl"))?.as_object()?;
    let rt_raw = concrete.get("runtime")?.as_str()?.trim();
    let has_source = concrete.get("source_file").and_then(|v| v.as_str()).is_some_and(|s| !s.is_empty())
        || concrete.get("source_text").and_then(|v| v.as_str()).is_some();
    if rt_raw.is_empty() || !has_source {
        return None;
    }
    resolve_formal_target(rt_raw, None, None, None, clm_root).ok()?;

    let str_vec = |val: Option<&serde_json::Value>| -> Vec<String> {
        val.and_then(|v| v.as_array())
            .map(|arr| arr.iter().filter_map(|x| x.as_str().map(String::from)).collect())
            .unwrap_or_default()
    };
    let staged_files: BTreeMap<String, String> = concrete
        .get("staged_files")
        .and_then(|v| v.as_object())
        .map(|m| m.iter().filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string()))).collect())
        .unwrap_or_default();

    let req = FormalExecutionRequest {
        runtime_id: rt_raw.to_string(),
        profile_id: concrete.get("profile_id").or_else(|| concrete.get("profile")).and_then(|v| v.as_str()).map(String::from),
        source_file: concrete.get("source_file").and_then(|v| v.as_str()).map(String::from),
        source_text: concrete.get("source_text").and_then(|v| v.as_str()).map(String::from),
        source_name: concrete.get("source_name").and_then(|v| v.as_str()).map(String::from),
        theorem_name: concrete
            .get("theorem_name")
            .and_then(|v| v.as_str())
            .or_else(|| abstract_node.and_then(|a| a.get("theorem")).and_then(|v| v.as_str()))
            .map(String::from),
        entry_point: concrete.get("entry_point").and_then(|v| v.as_str()).map(String::from),
        config_file: concrete.get("config_file").and_then(|v| v.as_str()).map(String::from),
        extra_args: str_vec(concrete.get("extra_args")),
        trailing_args: str_vec(concrete.get("trailing_args")),
        staged_files,
        stdin_text: concrete.get("stdin_text").and_then(|v| v.as_str()).map(String::from),
        strict: concrete.get("strict").and_then(|v| v.as_bool()).unwrap_or(false),
        isolated_empty_path: concrete.get("isolated_empty_path").and_then(|v| v.as_bool()).unwrap_or(false),
        clm_root: clm_root.to_string(),
        ..Default::default()
    };
    match execute_formal_request(&req, None) {
        Ok(outcome) => {
            let code = match outcome.witness.status {
                OracleWitnessStatus::Verified | OracleWitnessStatus::SkippedUnavailable => 0,
                _ => 1,
            };
            let pretty = serde_json::to_string_pretty(&outcome.witness).unwrap_or(outcome.stdout);
            Some((code, format!("{}\n", pretty), String::new()))
        }
        Err(e) => Some((2, String::new(), format!("clmEval formal evaluate error: {}\n", e))),
    }
}