clm-kernel 0.0.0

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
use serde_yaml::Value;

pub fn compose_conditions(
    clm_root: &Path,
    clm_file: &str,
    phase: &str,
    exit_code: i32,
    quiet: bool,
) -> Result<i32, String> {
    let clm_path = Path::new(clm_file);
    let mut custom_pcard = None;

    if clm_path.exists() {
        if let Ok(content) = std::fs::read_to_string(clm_path) {
            if let Ok(yaml) = serde_yaml::from_str::<Value>(&content) {
                // Try to find custom pre/post condition
                let root = yaml.get("clm").unwrap_or(&yaml);
                if let Some(concrete) = root.get("concrete_impl") {
                    if phase == "pre" {
                        if let Some(pre) = concrete.get("precondition") {
                            if let Some(v) = pre.get("vcard_pre") {
                                if let Some(s) = v.as_str() {
                                    custom_pcard = Some(s.to_string());
                                }
                            }
                        }
                    } else if phase == "post" {
                        if let Some(post) = concrete.get("postcondition") {
                            if let Some(v) = post.get("vcard_post") {
                                if let Some(s) = v.as_str() {
                                    custom_pcard = Some(s.to_string());
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // Materialize handle
    if let Some(ref mut pcard) = custom_pcard {
        if pcard.starts_with("gate:") {
            let gate_name = pcard.trim_start_matches("gate:");
            *pcard = format!("computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/{}.yaml", gate_name);
        } else if pcard.starts_with(crate::hash::DEFAULT_HASH_PREFIX) {
            let script = format!(
                "source {}/data/ipc/evaluator_cache.sh; materialize_handle \"{}\"",
                clm_root.display(),
                pcard
            );
            if let Ok(output) = Command::new(crate::fs_utils::get_bash_command()).arg("-c").arg(&script).output() {
                if output.status.success() {
                    let resolved = String::from_utf8_lossy(&output.stdout).trim().to_string();
                    if !resolved.is_empty() {
                        if !quiet {
                            eprintln!("[COMPOSE] Resolved {} gate reference: {} -> {}", phase, pcard, resolved);
                        }
                        if resolved.starts_with("gate:") {
                            let gate_name = resolved.trim_start_matches("gate:");
                            *pcard = format!("computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/{}.yaml", gate_name);
                        } else {
                            *pcard = resolved;
                        }
                    }
                }
            }
        }
    }

    if let Some(ref pcard_str) = custom_pcard {
        let resolved_path = if Path::new(pcard_str).is_absolute() {
            if Path::new(pcard_str).exists() { Some(PathBuf::from(pcard_str)) } else { None }
        } else {
            let joined = clm_root.join(pcard_str);
            if joined.exists() {
                Some(joined)
            } else if pcard_str.starts_with("clm/") {
                let suffix = &pcard_str[4..];
                let joined_suffix = clm_root.join(suffix);
                if joined_suffix.exists() {
                    Some(joined_suffix)
                } else {
                    None
                }
            } else {
                None
            }
        };

        let mut custom_gate_name = None;
        if let Some(ref path) = resolved_path {
            if let Ok(content) = std::fs::read_to_string(path) {
                if let Ok(yaml) = serde_yaml::from_str::<Value>(&content) {
                    let root = yaml.get("clm").unwrap_or(&yaml);
                    if let Some(concrete) = root.get("concrete_impl") {
                        if let Some(op) = concrete.get("operation") {
                            if let Some(s) = op.as_str() {
                                custom_gate_name = Some(s.to_string());
                            }
                        }
                    }
                }
            }
        }

        if let Some(gate_name) = custom_gate_name {
            if !quiet {
                eprintln!("[COMPOSE] Discovered custom {} gate: {} (from {})", phase, gate_name, pcard_str);
            }
        }
    }

    let expr;
    let override_gate = env::var("CLM_GATE_OVERRIDE").unwrap_or_else(|_| "0".to_string()) == "1";

    if phase == "pre" {
        if let Some(custom) = custom_pcard {
            if override_gate {
                expr = custom;
            } else if custom == "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml" || custom == "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/payload_nonempty.yaml" {
                expr = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml".to_string();
            } else {
                expr = format!("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml >>> {}", custom);
            }
        } else {
            expr = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml".to_string();
        }
    } else {
        if let Some(custom) = custom_pcard {
            if override_gate {
                expr = custom;
            } else if custom == "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml" || custom == "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/result_sealed.yaml" {
                expr = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml".to_string();
            } else {
                expr = format!("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml >>> {}", custom);
            }
        } else {
            expr = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml".to_string();
        }
    }

    execute_composed_pcard(clm_root, &expr, phase, exit_code, clm_file, quiet)
}

fn execute_composed_pcard(
    clm_root: &Path,
    expr: &str,
    phase: &str,
    exit_code: i32,
    payload: &str,
    quiet: bool,
) -> Result<i32, String> {
    // Split by >>>
    let seq_gates: Vec<&str> = expr.split(">>>").map(|s| s.trim()).collect();
    if seq_gates.len() > 1 {
        for gate in seq_gates {
            if !quiet {
                eprintln!("[COMPOSE] Executing Sequential Step: {}", gate);
            }
            let rc = execute_composed_pcard(clm_root, gate, phase, exit_code, payload, quiet)?;
            if rc != 0 {
                return Ok(rc);
            }
        }
        return Ok(0);
    }

    // Single gate
    let gate = expr.trim();
    if gate.is_empty() {
        return Ok(0);
    }

    if gate == "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml" {
        if !quiet {
            eprintln!("[COMPOSE] Executing verify_precondition natively (zero-fork)");
        }
        match crate::evaluator::verify::verify_precondition_internal(clm_root, payload, quiet) {
            Ok(_) => return Ok(0),
            Err(e) => {
                eprintln!("[COMPOSE] verify_precondition failed: {}", e);
                return Ok(1);
            }
        }
    }

    if gate == "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml" {
        if !quiet {
            eprintln!("[COMPOSE] Executing validate_postcondition natively (zero-fork)");
        }
        // Emit execution MCard (matches Python validate_postcondition behavior)
        let content = format!("exit code: {}", exit_code);
        let content_hash = crate::hash::raw_hash_string(&content);
        let extra_yaml = format!("content: \"{}\"", content);
        let operation = "validate_postcondition";
        match crate::db::emit_exec_mcard(operation, &content_hash, &extra_yaml, "", "", &clm_root.display().to_string()) {
            Ok(mcard_path) => {
                if !quiet {
                    eprintln!("[VCARD POST] ✅ Execution MCard generated: {}", mcard_path);
                    eprintln!("[VCARD POST]   content_hash: {}", content_hash);
                }
            }
            Err(e) => {
                eprintln!("[VCARD POST] ❌ Failed to emit execution MCard: {}", e);
            }
        }
        return Ok(0);
    }

    if !quiet {
        eprintln!("[COMPOSE] Executing Base Gate: {}", gate);
    }

    // Call evaluator::evaluate on the gate CLM
    // Strip "clm/" prefix if present, since clm_root.join("clm/...") would produce a non-existent path
    let gate_path = if gate.starts_with("clm/") {
        &gate[4..]
    } else {
        gate
    };
    let mut args = vec![gate_path.to_string()];
    if phase == "pre" {
        args.push(payload.to_string());
    } else {
        args.push(payload.to_string());
        args.push(exit_code.to_string());
    }

    // Instead of directly calling evaluate, we spawn clmEval-rs process so we don't conflict with global daemon state.
    // Use clmEval-rs directly (not the bash wrapper) because the Rust binary handles shell CLMs natively
    // via evaluate_non_rust_runtime which sources gate_library.sh. The bash wrapper dispatches to Python
    // which doesn't source shell gate libraries, causing "clm_log: command not found" errors.
    let clm_eval_rs = {
        let p1 = clm_root.join("kernel/scripts/clmEval-rs");
        let p2 = clm_root.join("kernel/clm_rust_core/target/release/clm_rust_core");
        let p3 = clm_root.join("kernel/clm_rust_core/target/debug/clm_rust_core");
        #[cfg(windows)]
        let p1 = clm_root.join("kernel/scripts/clmEval-rs.exe");
        #[cfg(windows)]
        let p2 = clm_root.join("kernel/clm_rust_core/target/release/clm_rust_core.exe");
        #[cfg(windows)]
        let p3 = clm_root.join("kernel/clm_rust_core/target/debug/clm_rust_core.exe");
        if p1.exists() { p1 } else if p2.exists() { p2 } else if p3.exists() { p3 } else { std::path::PathBuf::from("clmEval-rs") }
    };
    let mut cmd = Command::new(&clm_eval_rs);
    cmd.current_dir(clm_root);
    cmd.arg("evaluate");
    for arg in args {
        cmd.arg(arg);
    }
    cmd.env("CLM_NESTED_EXEC", "1");
    cmd.env("CLM_SKIP_CONDITIONS", "1");
    if quiet {
        cmd.env("CLM_QUIET", "1");
    }
    
    // Preserve critical environment variables for agent context
    for (key, value) in std::env::vars() {
        if key.starts_with("CLM_") || key == "ACTIVE_AGENT_DID" {
            cmd.env(key, value);
        }
    }
    match cmd.status() {
        Ok(status) => Ok(status.code().unwrap_or(1)),
        Err(e) => {
            eprintln!("[COMPOSE] Failed to execute gate {}: {}", gate, e);
            Ok(1)
        }
    }
}