clm-kernel 0.0.14

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
pub mod metrics;
pub mod config;
pub mod case_runner;
pub mod verdict;

pub use metrics::*;
pub use config::*;
pub use case_runner::*;
pub use verdict::*;

#[path = "../polyglot_runtime_script.rs"]
mod polyglot_runtime_script;
#[allow(unused_imports)]
pub use polyglot_runtime_script::*;

use serde_json::Value;
use crate::{memorize, yaml};

pub fn exec_polyglot(
    file_path: &str,
    payload: Option<&str>,
    clm_root: &str,
) -> std::result::Result<(i32, String), String> {
    let payload = payload.filter(|s| !s.is_empty());

    // Register CLM manifest file and its AST cards in the database
    memorize::check_and_register_file_mcard(file_path, clm_root)?;

    // 1. Load the manifest content as JSON
    let json_str = yaml::parse_to_mcards(file_path).map_err(|e| e.to_string())?;
    let parsed: Value = serde_json::from_str(&json_str)
        .map_err(|e| format!("Failed to parse JSON AST: {}", e))?;

    // 2. Locate polyglot cases
    let polyglot_cases = yaml::evaluate_jq(&parsed, ".clm.balanced_exp.polyglot_cases");
    let cases_arr = match polyglot_cases {
        Value::Array(arr) => arr,
        _ => return Err("No polyglot_cases found".to_string()),
    };

    // 3. Find the target cases to run
    let mut target_cases = Vec::new();
    if let Some(p) = payload {
        let mut found = false;
        for c in cases_arr.iter() {
            if let Some(name) = c.get("name").and_then(|v| v.as_str())
                && name == p {
                    target_cases.push(c.clone());
                    found = true;
                    break;
                }
        }
        if !found {
            return Err(format!("Case matching payload '{}' not found", p));
        }
    } else {
        // Run all cases
        for c in cases_arr.iter() {
            target_cases.push(c.clone());
        }
    }

    if target_cases.is_empty() {
        return Err("No cases to execute".to_string());
    }

    let target_runtime = std::env::var("CLM_POLYGLOT_RUNTIME").ok();
    if let Some(target) = &target_runtime {
        eprintln!("[PAL:polyglot] Active runtime choice: {}", target);
    }

    // Resolve active hashes
    let active_a_hash = std::env::var("CLM_ACTIVE_A_HASH").unwrap_or_default();
    let active_c_hash = std::env::var("CLM_ACTIVE_C_HASH").unwrap_or_default();

    let mut last_case_output = String::new();
    let mut consensus_exit_code = 0;

    for case in &target_cases {
        let case_name = case.get("name").and_then(|v| v.as_str()).unwrap_or("unnamed_case");
        let given = case.get("given").ok_or_else(|| format!("No given block found in case '{}'", case_name))?;

        // Extract runtimes list and determine active runtime choice
        let runtimes = match given.get("runtimes") {
            Some(Value::Array(arr)) => arr.iter().filter_map(|v| v.as_str()).map(|s| s.to_string()).collect::<Vec<String>>(),
            _ => return Err(format!("No runtimes found in given block of case '{}'", case_name)),
        };

        let active_runtimes = if let Some(target) = &target_runtime {
            vec![target.clone()]
        } else {
            runtimes.clone()
        };

        let (mut inputs, mut env_vars, mut pos_args) = (serde_json::Map::new(), std::collections::HashMap::new(), Vec::new());
        if let Value::Object(map) = given {
            for (k, v) in map {
                if k != "runtimes" && k != "requires" {
                    inputs.insert(k.clone(), v.clone());
                    let val_str = if let Value::String(s) = v { s.clone() } else { v.to_string() };
                    env_vars.insert(k.clone(), val_str.clone());
                    pos_args.push(val_str);
                }
            }
        }

        for (k, v) in crate::utils::collect_clm_mock_vars() {
            env_vars.insert(k, v);
        }

        // Mutual exclusivity checks
        let then = case.get("then").ok_or_else(|| format!("No then block found in case '{}'", case_name))?;
        let internal_ref = then.get("internal_reference").and_then(|v| v.as_str());
        let native_harness = then.get("native_harness");
        
        if internal_ref.is_some() && native_harness.is_some() {
            return Err(format!("Schema validation failed in case '{}': internal_reference and native_harness are mutually exclusive", case_name));
        }

        // SLA specifications
        let sla = then.get("performance_sla");
        let max_forks = sla.and_then(|s| s.get("max_forks")).and_then(|v| v.as_i64());
        if internal_ref.is_some() && let Some(mf) = max_forks && mf != 0 {
            return Err(format!("Schema validation failed in case '{}': max_forks must be 0 for internal_reference cases", case_name));
        }

        let (mut executed_runtimes, mut runtime_outputs) = (Vec::new(), Vec::new());
        let (mut runtime_exit_codes, mut runtime_exec_hashes) = (Vec::new(), Vec::new());

        for runtime in &active_runtimes {
            // Enforce Gherkin cover check
            if !runtimes.contains(runtime) {
                eprintln!("[PAL:polyglot] ⏭️ Target runtime '{}' not requested in Gherkin cover: {:?}", runtime, runtimes);
                continue;
            }

            // Verify supported runtimes
            if runtime != "shell" && runtime != "python" && runtime != "node" && runtime != "rust" {
                if target_runtime.is_some() {
                    return Err(format!("Target runtime '{}' is not supported in Sprint 97", runtime));
                } else {
                    eprintln!("[PAL:polyglot] ⏭️ Skipping unsupported runtime '{}' in cover", runtime);
                    continue;
                }
            }

            // Check preconditions
            if let Some(req_guard) = given.get("requires").and_then(|v| v.get(runtime)).and_then(|v| v.as_str())
                && !check_precondition(req_guard, clm_root) {
                    eprintln!("[PAL:polyglot] ⏭️ Pruning runtime '{}' (precondition not met: {})", runtime, req_guard);
                    continue;
                }

            let run_res = match execute_runtime_case(
                runtime,
                case_name,
                &parsed,
                internal_ref,
                native_harness,
                &pos_args,
                &env_vars,
                file_path,
                clm_root,
            ) {
                Ok(res) => res,
                Err(e) if e.starts_with("Skipping runtime") => {
                    eprintln!("[PAL:polyglot] {}", e);
                    continue;
                }
                Err(e) => return Err(e),
            };

            if !run_res.stderr_data.is_empty() {
                eprintln!("{}", run_res.stderr_data);
            }

            // Enforce SLA resource usage checks
            verify_sla(case_name, runtime, then, run_res.elapsed_ms, run_res.peak_rss_val, run_res.fork_count)?;

            // Register Execution MCard
            let exec_hash = record_exec_mcard(
                case_name,
                runtime,
                &inputs,
                &run_res.stdout_data,
                run_res.run_status,
                &active_a_hash,
                &active_c_hash,
                clm_root,
            )?;

            executed_runtimes.push(runtime.clone());
            runtime_outputs.push(run_res.stdout_data);
            runtime_exit_codes.push(run_res.run_status);
            runtime_exec_hashes.push(exec_hash);
        }

        let (code, out) = verify_parity_and_record_consensus(
            case_name,
            &executed_runtimes,
            &runtime_outputs,
            &runtime_exit_codes,
            &runtime_exec_hashes,
            &active_a_hash,
            &active_c_hash,
            clm_root,
        )?;

        consensus_exit_code = code;
        last_case_output = out;
    }

    Ok((consensus_exit_code, last_case_output))
}