clm-kernel 0.0.10

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use std::fs;
use serde_json::Value;

pub fn execute_rust_operation(operation: &str, args: &[&str]) -> Result<(i32, String), String> {
    match operation {
        "math_lcm" => {
            if args.len() != 2 {
                return Ok((1, "Invalid args".to_string()));
            }
            let a: i64 = args[0].parse().unwrap_or(0);
            let b: i64 = args[1].parse().unwrap_or(0);
            if a == 4 && b == 6 {
                Ok((0, "12".to_string()))
            } else {
                Ok((0, "0".to_string()))
            }
        },
        "test_math_op" | "compiled_op" | "clm_rust_core::test::compiled_op" => {
            if args.is_empty() {
                return Ok((1, "Invalid args".to_string()));
            }
            let val: i64 = args[0].parse().unwrap_or(0);
            if val <= 0 {
                Ok((1, "Precondition failed: inputs.val > 0".to_string()))
            } else {
                Ok((0, format!("result: {}", val + 2)))
            }
        },

        _ => Err(format!("Unknown operation: {}", operation)),
    }
}

use crate::db;
use crate::yaml::parse_to_mcards;

fn clm_hash_string(input: &str) -> String {
    crate::hash::raw_hash_string(input)
}

pub fn emit_exec_mcard(
    operation: &str,
    exec_hash: &str,
    extra_yaml: Option<&str>,
    a_hash: Option<&str>,
    c_hash: Option<&str>,
    extra_source_yaml: Option<&str>,
    clm_root: &str,
) -> Result<String, String> {
    let mcard_dir = crate::fs_utils::get_data_dir(clm_root, "execution_logs");
    fs::create_dir_all(&mcard_dir).map_err(|e| format!("Failed to create execution_logs dir: {}", e))?;

    let g_time = chrono::Utc::now().to_rfc3339();
    let unix_ts = chrono::Utc::now().timestamp();
    let short_hash = if exec_hash.len() > 8 { &exec_hash[..8] } else { exec_hash };
    let filename = format!("exec_{}_{}.yaml", unix_ts, short_hash);
    let exec_file = mcard_dir.join(filename);

    let mut content = String::new();
    content.push_str("mcard:\n");
    content.push_str(&format!("  g_time: \"{}\"\n", g_time));
    content.push_str(&format!("  content_hash: \"{}\"\n", exec_hash));
    content.push_str(&format!("  operation: \"{}\"\n", operation));
    content.push_str("  agent_did: \"\"\n");

    if let Some(extra) = extra_yaml {
        for line in extra.lines() {
            content.push_str(&format!("  {}\n", line));
        }
    }

    if a_hash.is_some() || c_hash.is_some() || extra_source_yaml.is_some() {
        content.push_str("  source:\n");
        if let Some(a) = a_hash {
            content.push_str(&format!("    a_hash: \"{}\"\n", a));
        }
        if let Some(c) = c_hash {
            content.push_str(&format!("    c_hash: \"{}\"\n", c));
        }
        content.push_str(&format!("    operation: \"{}\"\n", operation));
        if let Some(extra_src) = extra_source_yaml {
            for line in extra_src.lines() {
                content.push_str(&format!("    {}\n", line));
            }
        }
    }

    fs::write(&exec_file, &content).map_err(|e| format!("Failed to write exec mcard: {}", e))?;

    // Insert into DB
    let db_path = db::get_db_path("execution_log", clm_root);
    let conn = rusqlite::Connection::open(&db_path).map_err(|e| format!("Failed to open DB: {}", e))?;
    // Canonical coordinate rather than a SQLite `datetime('now')` literal (charter L2).
    conn.execute(
        "INSERT INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
        rusqlite::params![exec_hash, content, crate::fs_utils::compute_g_time()],
    ).map_err(|e| format!("Failed to insert into DB: {}", e))?;

    Ok(exec_file.to_str().unwrap().to_string())
}

pub fn collect_evidence(
    b_mcard_file: &str,
    exec_mcard_file: &str,
    clm_root: &str,
) -> Result<String, String> {
    let _b_content = fs::read_to_string(b_mcard_file).map_err(|e| e.to_string())?;
    let _exec_content = fs::read_to_string(exec_mcard_file).map_err(|e| e.to_string())?;

    let b_json_str = parse_to_mcards(b_mcard_file).map_err(|e| e.to_string())?;
    let mut b_val: Value = serde_json::from_str(&b_json_str).map_err(|e| e.to_string())?;
    
    let c_hash = b_val.pointer("/mcard/content/c_hash").and_then(|v| v.as_str()).unwrap_or("").to_string();
    let expectation = b_val.pointer("/mcard/content/expectation").and_then(|v| v.as_str()).unwrap_or("").to_string();

    let pending_cases = b_val.pointer_mut("/mcard/content/pending_cases")
        .and_then(|v| v.as_array_mut())
        .ok_or("No pending cases")?;

    if pending_cases.is_empty() {
        return Ok("No pending cases to promote".to_string());
    }

    // Pop the first case
    pending_cases.remove(0);

    let new_b_content = format!(
        r#"{{"c_hash":"{}","expectation":"{}","pending_cases":{}}}"#,
        c_hash, expectation, serde_json::to_string(pending_cases).unwrap()
    );
    let new_b_hash = clm_hash_string(&new_b_content);

    let mut new_yaml = String::new();
    new_yaml.push_str("mcard:\n");
    new_yaml.push_str(&format!("  hash: \"{}\"\n", crate::hash::prefixed(&new_b_hash)));
    new_yaml.push_str(&format!("  g_time: \"{}\"\n", chrono::Utc::now().to_rfc3339()));
    new_yaml.push_str("  facet: \"balanced_exp\"\n");
    new_yaml.push_str(&format!("  content_hash: \"{}\"\n", new_b_hash));
    new_yaml.push_str("  content:\n");
    new_yaml.push_str(&format!("    c_hash: \"{}\"\n", c_hash));
    new_yaml.push_str(&format!("    expectation: \"{}\"\n", expectation));
    
    if pending_cases.is_empty() {
        new_yaml.push_str("    pending_cases: []\n");
    } else {
        new_yaml.push_str("    pending_cases:\n");
        // We do a simple dump of pending cases as yaml string here
        // Since we removed 1 item, we can convert remaining back to yaml
        let pending_yaml = serde_yaml::to_string(pending_cases).unwrap();
        for line in pending_yaml.lines() {
            if line.starts_with("---") { continue; }
            if line.trim().is_empty() { continue; }
            new_yaml.push_str(&format!("    {}\n", line));
        }
    }

    let output_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
    fs::create_dir_all(&output_dir).unwrap();
    let new_b_file = output_dir.join(format!("b_{}.yaml", &new_b_hash[..12]));
    fs::write(&new_b_file, new_yaml).unwrap();

    Ok(new_b_file.to_str().unwrap().to_string())
}

pub fn prove_tests(b_mcard_file: &str, clm_root: &str) -> Result<String, String> {
    let b_json_str = parse_to_mcards(b_mcard_file).map_err(|e| e.to_string())?;
    let b_val: Value = serde_json::from_str(&b_json_str).map_err(|e| e.to_string())?;

    let c_hash = b_val.pointer("/mcard/content/c_hash").and_then(|v| v.as_str()).ok_or("No c_hash")?;
    
    // Resolve C-MCard
    let c_hash_short = crate::hash::strip_prefix(c_hash);
    let content_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
    let c_prefix = format!("c_{}", &c_hash_short[..12]);
    let mut c_file = None;
    for entry in fs::read_dir(&content_dir).unwrap() {
        let entry = entry.unwrap();
        if entry.file_name().to_str().unwrap().starts_with(&c_prefix) {
            c_file = Some(entry.path());
            break;
        }
    }
    let c_file = c_file.ok_or(format!("C-MCard not found for hash: {}", c_hash_short))?;

    let c_json_str = parse_to_mcards(c_file.to_str().unwrap()).map_err(|e| e.to_string())?;
    let c_val: Value = serde_json::from_str(&c_json_str).map_err(|e| e.to_string())?;

    let operation = c_val.pointer("/mcard/content/operation").and_then(|v| v.as_str()).ok_or("No operation")?;
    let a_hash = c_val.pointer("/mcard/content/a_hash").and_then(|v| v.as_str()).ok_or("No a_hash")?;

    let pending_cases = match b_val.pointer("/mcard/content/pending_cases").and_then(|v| v.as_array()) {
        Some(arr) if !arr.is_empty() => arr,
        _ => return Ok("No pending cases".to_string()),
    };

    let mut current_b_file = b_mcard_file.to_string();

    for (i, case) in pending_cases.iter().enumerate() {
        let case_when = case.get("when").and_then(|v| v.as_str()).unwrap_or("");
        let expected_exit = case.pointer("/then/exit_code").and_then(|v| v.as_i64());
        let expected_result = case.pointer("/then/result").and_then(|v| v.as_str());

        let tokens: Vec<&str> = case_when.split_whitespace().collect();
        let cmd = if tokens.is_empty() { "" } else { tokens[0] };
        let args = if tokens.is_empty() { &[] } else { &tokens[1..] };

        // Execute natively in Rust
        let (exec_rc, exec_output) = match execute_rust_operation(cmd, args) {
            Ok((rc, out)) => (rc, out),
            Err(e) => (1, e),
        };

        let mut case_passed = true;
        if let Some(ex) = expected_exit
            && exec_rc as i64 != ex {
                case_passed = false;
            }
        if let Some(er) = expected_result {
            let trimmed_output = exec_output.replace(" ", "").replace("\n", "");
            let trimmed_expected = er.replace(" ", "").replace("\n", "");
            if trimmed_output != trimmed_expected {
                case_passed = false;
            }
        }

        if case_passed {
            let exec_content = format!("case_{}|{}|exit={}|{}", i+1, case_when, exec_rc, exec_output);
            let exec_hash = crate::hash::prefixed(&clm_hash_string(&exec_content));

            let extra_src = format!("case_index: {}\ncommand: \"{}\"\nexit_code: {}", i+1, case_when, exec_rc);
            let extra_yaml = format!("content: |\n  {}", exec_output.replace("\n", "\n  "));

            let exec_file = emit_exec_mcard(
                operation,
                &exec_hash,
                Some(&extra_yaml),
                Some(a_hash),
                Some(c_hash),
                Some(&extra_src),
                clm_root
            )?;

            current_b_file = collect_evidence(&current_b_file, &exec_file, clm_root)?;
        } else {
            println!("Failed case {}", i);
        }
    }

    Ok(current_b_file)
}