clm-kernel 0.0.22

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

#[cfg(test)]
const UPSERT_ESCALATION_HANDLE_SQL: &str = "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES ('escalation:latest', ?, ?)";

pub(crate) fn run_fallback_internal_reference(
    _clm_root: &str,
    clm_file: &str,
    module_path: &str,
    _quiet: bool,
) -> Result<(i32, String), String> {
    let test_name = module_path.split("::").last().unwrap_or(module_path);
    crate::integration::shell_runner::run_shell_test(clm_file, test_name, None)
        .map(|out| (0, out))
}

pub(super) fn evaluate_native_governance_gate(
    clm_root: &Path,
    entry_point: &str,
    payload: Option<&str>,
) -> Result<(i32, String), String> {
    let clm_root_str = clm_root.to_str().unwrap_or("");
    match entry_point {
        "gate_agent_write_scope" => {
            let target_path = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_TARGET_PATH)
                .ok()
                .filter(|s| !s.is_empty())
                .or_else(|| payload.map(|s| s.split_whitespace().next().unwrap_or("").to_string()))
                .unwrap_or_default();
            if target_path.is_empty() {
                return Ok((1, "[GATE] write-scope: fail-closed (empty target path)\n".to_string()));
            }
            let schema_file = clm_root.join("types/governance/agent_write_scope.yaml");
            let schema_content = match fs::read_to_string(&schema_file) {
                Ok(c) if serde_yaml::from_str::<serde_yaml::Value>(&c).is_ok() => c,
                _ => return Ok((1, "[GATE] write-scope: fail-closed (missing or invalid schema)\n".to_string())),
            };
            let _ = schema_content;
            let agent_param = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_AGENT_CLASS)
                .ok()
                .filter(|s| !s.is_empty())
                .or_else(|| crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_AGENT_ROLE).ok().filter(|s| !s.is_empty()))
                .unwrap_or_default();
            let agent_class = match agent_param.as_str() {
                "EOA" | "winston" | "pm" => "EOA".to_string(),
                "CA" | "amelia" | "tea" | "paige" => "CA".to_string(),
                "" => {
                    let did = crate::layer0::environment::var("ACTIVE_AGENT_DID")
                        .or_else(|_| crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_AGENT_DID))
                        .unwrap_or_default();
                    if did == crate::layer0::vocabulary_identities::DID_CLM_BOOTSTRAP {
                        "EOA".to_string()
                    } else if did.ends_with(":winston") || did.ends_with(":pm") {
                        "EOA".to_string()
                    } else if did.ends_with(":amelia") || did.ends_with(":tea") || did.ends_with(":paige") {
                        "CA".to_string()
                    } else {
                        String::new()
                    }
                }
                _ => String::new(),
            };
            if agent_class.is_empty() {
                return Ok((1, "[GATE] write-scope: fail-closed (unresolved agent class)\n".to_string()));
            }
            let clean = target_path.trim_start_matches("./");
            if clean.starts_with("types/") || clean == "types" || clean == "Makefile" || clean == "CLAUDE.md" {
                if agent_class == "EOA" {
                    Ok((0, format!("[GATE] write-scope PASS (EOA on layer3_schema: {})\n", clean)))
                } else {
                    Ok((2, format!("[GATE] write-scope ESCALATION_REQUIRED (CA on layer3_schema: {})\n", clean)))
                }
            } else if clean.starts_with("kernel/") || clean.starts_with("scripts/") || clean.starts_with("tests/") {
                if agent_class == "EOA" {
                    Ok((0, format!("[GATE] write-scope PASS (EOA on layer1_raw: {})\n", clean)))
                } else {
                    Ok((1, format!("[GATE] write-scope DENIED (CA on layer1_raw: {})\n", clean)))
                }
            } else if clean.starts_with("docs/") || clean == "docs" || clean.starts_with("computable_knowledge/") {
                Ok((0, format!("[GATE] write-scope PASS ({} on layer2_wiki: {})\n", agent_class, clean)))
            } else {
                Ok((1, format!("[GATE] write-scope: fail-closed (unclassifiable path: {})\n", clean)))
            }
        }
        "gate_escalation" | "gate_escalation_gate" => {
            let schema_file = clm_root.join("types/governance/escalation_gate.yaml");
            match fs::read_to_string(&schema_file) {
                Ok(c) if serde_yaml::from_str::<serde_yaml::Value>(&c).is_ok() => {}
                _ => return Ok((1, "[GATE] escalation: fail-closed (missing or invalid schema)\n".to_string())),
            }
            let risk_level = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_RISK_LEVEL)
                .ok()
                .filter(|s| !s.is_empty())
                .or_else(|| payload.map(|s| s.split_whitespace().next().unwrap_or("").to_string()))
                .unwrap_or_default();
            let risk_upper = risk_level.to_ascii_uppercase();
            if !matches!(risk_upper.as_str(), "LOW" | "MEDIUM" | "HIGH" | "CRITICAL") {
                return Ok((1, "[GATE] escalation: fail-closed (invalid risk level)\n".to_string()));
            }
            let approval_ref = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_EOA_APPROVAL).unwrap_or_default();
            let (decision, rc) = if risk_upper == "LOW" || risk_upper == "MEDIUM" {
                ("proceed", 0)
            } else if approval_ref == crate::layer0::vocabulary_identities::DID_CLM_BOOTSTRAP || (!approval_ref.is_empty() && crate::db::get_connection("agent_identities", clm_root_str).map(|conn| {
                let c1: i64 = conn.query_row("SELECT count(*) FROM card WHERE hash = ?", [&approval_ref], |r| r.get(0)).unwrap_or(0);
                let c2: i64 = conn.query_row("SELECT count(*) FROM handle_registry WHERE handle = ? OR current_hash = ?", [&approval_ref, &approval_ref], |r| r.get(0)).unwrap_or(0);
                c1 + c2 > 0
            }).unwrap_or(false)) {
                ("proceed", 0)
            } else {
                ("escalate", 2)
            };
            if let Ok(writer_arc) = crate::db::get_writer_connection(crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG, clm_root_str)
                && let Ok(conn) = writer_arc.lock()
            {
                let now = crate::utils::now_iso8601();
                let agent_did = crate::layer0::environment::var("ACTIVE_AGENT_DID")
                    .or_else(|_| crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_AGENT_DID))
                    .unwrap_or_else(|_| "unknown_agent".to_string());
                let event_card = format!(
                    "event: escalation_decision\nrisk_level: {}\ndecision: {}\nstatus: {}\napproval_ref: {}\nagent_did: {}\ntimestamp: {}",
                    risk_upper,
                    decision,
                    rc,
                    if approval_ref.is_empty() { "none" } else { &approval_ref },
                    agent_did,
                    now
                );
                crate::layer2::record_store::store_named_content(&conn, "escalation:latest", event_card.as_bytes())?;
            }
            Ok((rc, format!("[GATE] escalation decision={} rc={}\n", decision, rc)))
        }
        "agent_refinement_loop" => {
            let (esc_rc, esc_out) = evaluate_native_governance_gate(clm_root, "gate_escalation", payload)?;
            if esc_rc != 0 {
                return Ok((esc_rc, esc_out));
            }
            evaluate_native_governance_gate(clm_root, "gate_agent_write_scope", payload)
        }
        _ => Ok((0, format!("[GATE] PASS ({})\n", entry_point))),
    }
}

#[cfg(test)]
mod tests {
    use super::UPSERT_ESCALATION_HANDLE_SQL;

    #[test]
    fn escalation_handle_upsert_matches_canonical_schema() {
        let connection = rusqlite::Connection::open_in_memory().unwrap();
        connection
            .execute_batch(crate::db::CANONICAL_SCHEMA)
            .unwrap();
        let card_hash = "sha256:escalation-test";
        let now = "2026-10-18T00:00:00Z";

        connection
            .execute(
                "INSERT INTO card (hash, content, g_time) VALUES (?, ?, ?)",
                rusqlite::params![card_hash, "test escalation event", now],
            )
            .unwrap();
        connection
            .execute(
                UPSERT_ESCALATION_HANDLE_SQL,
                rusqlite::params![card_hash, now],
            )
            .unwrap();

        let stored: (String, String) = connection
            .query_row(
                "SELECT current_hash, updated_at FROM handle_registry WHERE handle = 'escalation:latest'",
                [],
                |row| Ok((row.get(0)?, row.get(1)?)),
            )
            .unwrap();
        assert_eq!(stored, (card_hash.to_string(), now.to_string()));
    }
}

// ── Internal Helpers ────────────────────────────────────────

pub(super) fn resolve_script_body(clm_root: &Path, process: &serde_yaml::Value, runner_type: &str) -> Result<String, String> {
    eprintln!("[DEBUG] resolve_script_body called with runner_type: {}", runner_type);
    eprintln!("[DEBUG] process object: {:?}", process);
    if let Some(script) = process.get("script").and_then(|v| v.as_str()) {
        eprintln!("[DEBUG] resolve_script_body: found 'script' field, length: {}", script.len());
        if !script.is_empty() {
            return Ok(script.to_string());
        }
    }

    if let Some(handle) = process.get("script_handle").and_then(|v| v.as_str()) {
        eprintln!("[DEBUG] resolve_script_body: trying to resolve handle: {:?}", handle);
        if handle.starts_with("script:") {
            let handle_name = handle.trim_start_matches("script:");
            // First check database
            match crate::db::resolve_handle_content(crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY, clm_root.to_str().unwrap_or(""), handle) {
                Ok(Some(content)) if !content.is_empty() => {
                    eprintln!("[DEBUG] resolve_script_body: resolved '{}' from content_memory DB ({} bytes)", handle, content.len());
                    return Ok(content);
                }
                Ok(_) => eprintln!("[DEBUG] resolve_script_body: '{}' not in DB, falling back to disk search", handle),
                Err(e) => eprintln!("[DEBUG] resolve_script_body: DB resolve error for '{}': {}, falling back to disk search", handle, e),
            }

            // Search on disk for polyglot scripts (.py, .js, .cjs)
            let extensions = match runner_type {
                "python" => vec![".py"],
                "node" | "javascript" => vec![".js", ".cjs"],
                _ => vec![".py", ".js", ".cjs"],
            };
            eprintln!("[DEBUG] resolve_script_handle: searching for '{}' with extensions {:?}", handle_name, extensions);
            let search_dirs = ["scripts", "tests", "kernel/clm_py_core", "computable_knowledge"];
            for dir_name in &search_dirs {
                let dir_path = clm_root.join(dir_name);
                if dir_path.exists()
                    && let Some(path) = find_script_file(&dir_path, handle_name, &extensions) {
                        eprintln!("[DEBUG] found path: {:?}, trying to read...", path);
                        match fs::read_to_string(&path) {
                            Ok(content) => return Ok(content),
                            Err(e) => eprintln!("[DEBUG] failed to read {:?}: {}", path, e),
                        }
                    }
            }
        } else {
            return Ok(format!("echo '[GATE] {}'\n", handle));
        }
    }

    Err("Empty script body and failed to resolve script_handle".to_string())
}

pub(super) fn find_script_file(dir: &Path, script_name: &str, extensions: &[&str]) -> Option<PathBuf> {
    // Handle names may contain path separators (e.g. "finetuning/dataset_intake").
    // Extract the basename for matching against file names.
    let basename = script_name.rsplit('/').next().unwrap_or(script_name);
    // eprintln!("[DEBUG] find_script_file: searching dir {:?}", dir); // too noisy
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() {
                if let Some(file_name) = path.file_name().and_then(|s| s.to_str()) {
                    if file_name.contains(basename) {
                        eprintln!("[DEBUG] file_name: '{}', script_name: '{}', basename: '{}'", file_name, script_name, basename);
                    }
                    for ext in extensions {
                        if file_name.contains(basename) {
                            eprintln!("[DEBUG] comparing '{}' with '{}' and '{}'", file_name, format!("{}{}", script_name, ext), format!("{}{}", basename, ext));
                        }
                        if file_name == format!("{}{}", script_name, ext)
                            || file_name == format!("{}{}", basename, ext)
                        {
                            return Some(path);
                        }
                    }
                }
            } else if path.is_dir()
                && let Some(p) = find_script_file(&path, script_name, extensions) {
                    return Some(p);
                }
        }
    }
    None
}

pub(super) fn run_command_and_capture(mut cmd: std::process::Command) -> Result<(i32, String), String> {
    let prog = cmd.get_program().to_string_lossy().to_string();
    let args_vec: Vec<String> = cmd.get_args().map(|a| a.to_string_lossy().to_string()).collect();
    crate::cross_cutting::context::CLMContext::check_current_process_policy(&prog, &args_vec)
        .map_err(|e| e.to_string())?;
    eprintln!("[DEBUG] run_command_and_capture: spawning {:?} ({} args), waiting for exit...", cmd.get_program(), cmd.get_args().count());
    let output = cmd.output().map_err(|e| format!("Failed to execute process: {}", e))?;
    eprintln!("[DEBUG] run_command_and_capture: {:?} exited with {:?}", cmd.get_program(), output.status.code());
    if !output.stderr.is_empty() {
        use std::io::Write;
        std::io::stderr().write_all(&output.stderr).ok();
    }
    let exit_code = output.status.code().unwrap_or(1);
    let stdout_str = String::from_utf8_lossy(&output.stdout).to_string();
    Ok((exit_code, stdout_str))
}