clm-kernel 0.0.15

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use crate::fs_utils::compute_sha256_hex;

pub(super) fn handle_gate_intercepts(
    operation: &str,
    clm_root: &Path,
    clm_file: &str,
    payload: Option<&str>,
    post_rc: Option<i32>,
    quiet: bool,
    concrete_impl: &serde_yaml::Value,
    clm_data: &serde_yaml::Value,
) -> Option<Result<i32, String>> {
    if operation == "verify_precondition" {
        if !quiet {
            eprintln!("[clmEval-rs] ⚡ Native gate intercept: verify_precondition (zero-fork)");
        }
        match super::super::verify::verify_precondition_internal(clm_root, clm_file, quiet) {
            Ok(()) => return Some(Ok(0)),
            Err(e) => {
                eprintln!("[clmEval-rs] ❌ Pre-Gate Failed: {}", e);
                return Some(Ok(1));
            }
        }
    }

    if operation == "validate_postcondition" {
        if !quiet {
            eprintln!("[clmEval-rs] ⚡ Native gate intercept: validate_postcondition (zero-fork)");
        }
        let rc = post_rc.unwrap_or(0);
        let content = format!("exit code: {}", rc);
        let content_hash = format!("sha256:{}", compute_sha256_hex(content.as_bytes()));
        
        let mut op = "unknown".to_string();
        let mut impl_hash = "unknown".to_string();
        if let Some(pay) = payload {
            let pay_path = if Path::new(pay).is_absolute() {
                PathBuf::from(pay)
            } else {
                clm_root.join(pay)
            };
            
            let resolved_pay_path = if pay_path.exists() {
                pay_path
            } else if pay.starts_with("clm/") {
                clm_root.join(&pay[4..])
            } else {
                pay_path
            };
            
            if resolved_pay_path.exists() {
                if let Ok(c) = fs::read_to_string(&resolved_pay_path)
                    && let Ok(yaml) = serde_yaml::from_str::<serde_yaml::Value>(&c) {
                        let inner = yaml.get("clm").unwrap_or(&yaml);
                        if let Some(concrete) = inner.get("concrete_impl")
                            && let Some(operation_val) = concrete.get("operation").and_then(|v| v.as_str()) {
                                op = operation_val.to_string();
                            }
                    }
                if let Ok(bytes) = fs::read(&resolved_pay_path) {
                    let normalized: Vec<u8> = bytes.into_iter().filter(|&b| b != b'\r').collect();
                    impl_hash = format!("sha256:{}", compute_sha256_hex(&normalized));
                }
            }
        }
        
        let a_hash = env::var("CLM_ACTIVE_A_HASH").unwrap_or_default();
        let c_hash = env::var("CLM_ACTIVE_C_HASH").unwrap_or_default();
        let extra_yaml = format!("content: \"{}\"\noperation: \"{}\"\nimpl_hash: \"{}\"", content, op, impl_hash);
        
        match crate::db::emit_exec_mcard(
            "validate_postcondition",
            &content_hash,
            &extra_yaml,
            &a_hash,
            &c_hash,
            clm_root.to_str().unwrap_or(""),
        ) {
            Ok(exec_mcard_path) => {
                if !quiet {
                    eprintln!("[VCARD POST] ✅ Execution MCard generated: {}", exec_mcard_path);
                    eprintln!("[VCARD POST]   g_time: {}", crate::fs_utils::compute_g_time());
                    eprintln!("[VCARD POST]   content_hash: {}", content_hash);
                }
            }
            Err(e) => {
                eprintln!("[VCARD POST] ❌ Failed to generate execution MCard: {}", e);
                return Some(Ok(1));
            }
        }
        
        return Some(Ok(0));
    }

    if operation.starts_with("ci_validate_") {
        let content_type = concrete_impl.get("content_type");
        let mime = content_type
            .and_then(|ct| ct.get("mime"))
            .and_then(|m| m.as_str())
            .unwrap_or("");
        
        let payload_file = match payload {
            Some(p) => p,
            None => return Some(Err("No payload file specified for validation".to_string())),
        };
        
        if !quiet {
            eprintln!("[clmEval-rs] ⚡ Native validation intercept: {} for file {} (zero-fork)", operation, payload_file);
        }
        
        if let Err(e) = super::super::verify::verify_precondition_internal(clm_root, clm_file, quiet) {
            eprintln!("CRITICAL: Pre-Gate Failed: {}", e);
            return Some(Ok(1));
        }

        let is_valid = crate::mime::validate(clm_root.to_str().unwrap_or(""), payload_file, Some(mime));
        let exit_code = if is_valid { 0 } else { 1 };
        let output = "";
        let clm_root_str = clm_root.to_str().unwrap_or("");
        
        if exit_code == 0 {
            let a_hash_str = clm_data.get("_meta").and_then(|m| m.get("a_hash")).and_then(|v| v.as_str())
                .map(|s| s.to_string())
                .unwrap_or_else(|| {
                    let spec = clm_data.get("abstract_spec").cloned().unwrap_or(serde_yaml::Value::Null);
                    let serialized = serde_yaml::to_string(&spec).unwrap_or_default();
                    format!("sha256:{}", compute_sha256_hex(serialized.replace('\r', "").as_bytes()))
                });
            
            let c_hash_str = clm_data.get("_meta").and_then(|m| m.get("c_hash")).and_then(|v| v.as_str())
                .map(|s| s.to_string())
                .unwrap_or_else(|| {
                    let spec = clm_data.get("concrete_impl").cloned().unwrap_or(serde_yaml::Value::Null);
                    let serialized = serde_yaml::to_string(&spec).unwrap_or_default();
                    format!("sha256:{}", compute_sha256_hex(serialized.replace('\r', "").as_bytes()))
                });

            let output_hash = format!("sha256:{}", compute_sha256_hex(output.as_bytes()));
            let extra_yaml = format!("content: |\n  {}", output.replace('\n', "\n  "));
            let _ = crate::db::emit_exec_mcard(
                operation, &output_hash, &extra_yaml, &a_hash_str, &c_hash_str, clm_root_str,
            );
        }
        
        return Some(Ok(exit_code));
    }

    None
}