clm-kernel 0.0.21

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
#![allow(unused_imports)]
use super::*;

/// Extract an inline shell `script:` from a PCard YAML, if the process is a
/// trivial `type: shell` card with an inline script (no `script_handle`).
/// Returns None for polyglot, handle-based, or gated PCards so they take the
/// full evaluate path.
pub(super) fn extract_inline_shell_script(clm_root: &str, clm_file: &str) -> Option<String> {
    let path = if std::path::Path::new(clm_file).is_absolute() {
        std::path::PathBuf::from(clm_file)
    } else {
        std::path::Path::new(clm_root).join(clm_file)
    };
    let content = std::fs::read_to_string(&path).ok()?;
    let parsed: serde_yaml::Value = serde_yaml::from_str(&content).ok()?;

    let clm_val = parsed.get("clm").unwrap_or(&parsed);
    let process = clm_val
        .get("concrete_impl")
        .and_then(|v| v.get("process"))
        .or_else(|| clm_val.get("process"))?;

    // Process may be a mapping or a sequence of runtime impls; handle the shell case.
    let shell_map = match process {
        serde_yaml::Value::Mapping(_) => Some(process),
        serde_yaml::Value::Sequence(seq) => seq.iter().find(|v| {
            v.get("type").and_then(|t| t.as_str()) == Some("shell")
        }),
        _ => None,
    }?;

    let ptype = shell_map.get("type").and_then(|t| t.as_str()).unwrap_or("shell");
    if ptype != "shell" {
        return None;
    }
    // Only fast-path inline scripts; defer handle-based scripts to the full evaluator.
    if shell_map.get("script_handle").and_then(|v| v.as_str()).is_some() {
        return None;
    }
    let script = shell_map.get("script").and_then(|v| v.as_str())?;
    Some(script.to_string())
}

pub(super) fn execute_pcard(clm_root: &str, clm_file: &str, payload: &str) -> Result<String, String> {
    // -- Zero-fork fast path: run trivial inline shell PCards directly --------
    // Avoids the heavy (and Windows-fragile) bash bootstrap for simple
    // `type: shell` cards, eliminating ~18s/run overhead and the
    // "clmEval: -c: line N: syntax error" failure on Git Bash/MSYS2.
    if let Some(script) = extract_inline_shell_script(clm_root, clm_file) {
        let bash = crate::fs_utils::get_bash_command();
        let mut cmd = std::process::Command::new(bash);
        cmd.current_dir(clm_root)
            .arg("-c")
            .arg(&script)
            .arg("clm_pcard") // $0
            .arg(payload)     // $1
            .env(crate::layer0::vocabulary_env::ENV_CLM_PAYLOAD, payload)
            .env(crate::layer0::vocabulary_env::ENV_CLM_NESTED_EXEC, "1")
            .stdin(std::process::Stdio::null());

        let output = cmd.output()
            .map_err(|e| format!("Failed to execute inline shell PCard: {}", e))?;
        if output.status.success() {
            let stdout_str = String::from_utf8_lossy(&output.stdout).into_owned();
            return Ok(stdout_str.trim().to_string());
        } else {
            let code = output.status.code().unwrap_or(-1);
            let stderr_str = String::from_utf8_lossy(&output.stderr).trim().to_string();
            let msg = if stderr_str.is_empty() {
                format!("inline shell PCard exited with code {}", code)
            } else {
                format!("exit {}: {}", code, stderr_str)
            };
            return Err(msg);
        }
    }

    let self_exe = std::env::current_exe()
        .map_err(|e| format!("Failed to get current executable path: {}", e))?;
    
    let mut cmd = std::process::Command::new(self_exe);
    cmd.current_dir(clm_root)
        .arg("evaluate")
        .arg(clm_file)
        .arg(payload)
        .arg("--quiet");
    
    cmd.envs(crate::layer0::environment::vars());
    cmd.env(crate::layer0::vocabulary_env::ENV_CLM_PAYLOAD, payload);
    cmd.env(crate::layer0::vocabulary_env::ENV_CLM_NESTED_EXEC, "1");
    cmd.env(crate::layer0::vocabulary_env::ENV_CLM_ZERO_FS, "true"); // Nested runs should always run in memory-only mode to prevent lock collisions on DB
    cmd.env(crate::layer0::vocabulary_env::ENV_CLM_SKIP_GRAMMAR, "1"); // Skip grammar checks for target process cards
    cmd.stdin(std::process::Stdio::null()); // explicitly close stdin to prevent hanging interactive shells

    
    let output = cmd.output()
        .map_err(|e| format!("Failed to execute process: {}", e))?;
    
    if output.status.success() {
        let stdout_str = String::from_utf8_lossy(&output.stdout).into_owned();
        let out = if let Some(idx) = stdout_str.find("[POST] V_post:") {
            stdout_str[..idx].to_string()
        } else {
            stdout_str
        };
        let log_prefixes: &[&str] = &[
            "[clmEval", "[VERIFY]", "[VCARD POST]", "[MCARD_KERNEL]",
            "[COMPOSE]", "[DEBUG", "[GATE]", "[TYPE", "[POST]", "[PAL]",
            "PASS:", "━━", "clmEval —", "Evaluating:", "SCRIPT CONTENT",
        ];
        let filtered: Vec<&str> = out.lines()
            .filter(|line| {
                let trimmed = line.trim();
                !trimmed.starts_with('[') && !trimmed.starts_with("SCRIPT CONTENT") && !log_prefixes.iter().any(|prefix| trimmed.starts_with(prefix))
            })
            .collect();
        let result = filtered.join("\n");
        Ok(result.trim().to_string())
    } else {
        Err(String::from_utf8_lossy(&output.stderr).to_string())
    }
}



pub(super) fn parse_json_or_yaml(s: &str) -> Result<Value, String> {
    let trimmed = s.trim();
    if trimmed.is_empty() {
        return Ok(Value::Null);
    }
    if let Ok(val) = serde_json::from_str::<Value>(trimmed) {
        return Ok(val);
    }
    if let Ok(yaml_val) = serde_yaml::from_str::<serde_yaml::Value>(trimmed) {
        let json_str = serde_json::to_string(&yaml_val)
            .map_err(|e| format!("Failed to serialize YAML value: {}", e))?;
        let val = serde_json::from_str::<Value>(&json_str)
            .map_err(|e| format!("Failed to parse deserialized YAML: {}", e))?;
        return Ok(val);
    }
    Err("Not valid JSON or YAML".to_string())
}

pub(super) fn clean_data(val: &Value) -> Value {
    match val {
        Value::Object(obj) => {
            let mut cleaned = serde_json::Map::new();
            for (k, v) in obj {
                if k == "timestamp"
                    || k == "g_time"
                    || k == "run_id"
                    || k == "previous_hash"
                    || k == "changed_at"
                    || k == "created_at"
                    || k == "updated_at"
                    || k == "witness_trail"
                    || k == "performance_differential"
                    || k == "agent_did"
                    || k == "uuid"
                    || k == "g_time_note"
                    || k == "genesis_hash"
                    || k == "genesis_note"
                {
                    continue;
                }
                cleaned.insert(k.clone(), clean_data(v));
            }
            Value::Object(cleaned)
        }
        Value::Array(arr) => {
            let mut cleaned_list = Vec::new();
            for item in arr {
                cleaned_list.push(clean_data(item));
            }
            cleaned_list.sort_by_key(|v| serde_json::to_string(v).unwrap_or_default());
            Value::Array(cleaned_list)
        }
        _ => val.clone(),
    }
}

pub(super) fn canonical_value(val: &Value) -> Value {
    match val {
        Value::Object(obj) => {
            let mut sorted = std::collections::BTreeMap::new();
            for (k, v) in obj {
                sorted.insert(k.clone(), canonical_value(v));
            }
            let mut res = serde_json::Map::new();
            for (k, v) in sorted {
                res.insert(k, v);
            }
            Value::Object(res)
        }
        Value::Array(arr) => {
            let mut res = Vec::new();
            for item in arr {
                res.push(canonical_value(item));
            }
            Value::Array(res)
        }
        _ => val.clone(),
    }
}

pub(super) fn compare_numerical(s_a: &str, s_b: &str) -> bool {
    let val_a = s_a.trim().parse::<f64>();
    let val_b = s_b.trim().parse::<f64>();
    match (val_a, val_b) {
        (Ok(a), Ok(b)) => (a - b).abs() <= 1e-6,
        _ => false,
    }
}

pub(super) fn check_content_equivalent(clm_root: &str, hash_a: &str, hash_b: &str) -> Result<bool, String> {
    if hash_a == hash_b {
        return Ok(true);
    }
    // Temporarily bypass sandbox so content lookups hit the real on-disk DB
    // rather than an ephemeral in-memory sandbox DB.
    let was_sandbox = crate::db::TEST_SANDBOX_ACTIVE.with(|a| a.get());
    let prev_id = crate::db::TEST_SANDBOX_DB_ID.with(|id| id.borrow().clone());
    let prev_depth = crate::db::thread_local_depth_get();
    crate::db::TEST_SANDBOX_ACTIVE.with(|a| a.set(false));
    crate::db::TEST_SANDBOX_DB_ID.with(|id| *id.borrow_mut() = None);
    crate::db::set_sandbox_depth(0);

    let result = (|| {
        let content_a = crate::db::get_card_content(crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY, clm_root, hash_a)
            .map_err(|e| e.to_string())?;
        let content_b = crate::db::get_card_content(crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY, clm_root, hash_b)
            .map_err(|e| e.to_string())?;
        Ok(match (content_a, content_b) {
            (Some(a), Some(b)) => a == b,
            _ => false,
        })
    })();

    crate::db::TEST_SANDBOX_ACTIVE.with(|a| a.set(was_sandbox));
    crate::db::TEST_SANDBOX_DB_ID.with(|id| *id.borrow_mut() = prev_id);
    crate::db::set_sandbox_depth(prev_depth);

    result
}