clm-kernel 0.0.10

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

pub fn assess_equivalence(clm_root: &str, clm_file: &str) -> Result<(i32, String), String> {
    use std::fs;
    use std::path::{Path, PathBuf};

    // 1. Read and Parse Spec Properties
    let content = fs::read_to_string(clm_file)
        .map_err(|e| format!("Failed to read equivalence spec: {}", e))?;
    let parsed: serde_yaml::Value = serde_yaml::from_str(&content)
        .map_err(|e| format!("Failed to parse equivalence YAML: {}", e))?;

    let clm_val = parsed.get("clm").unwrap_or(&parsed);
    let process_val = clm_val.get("concrete_impl")
        .and_then(|v| v.get("process"))
        .or_else(|| clm_val.get("process"))
        .ok_or_else(|| "No process block found in equivalence spec".to_string())?;

    let ref_pcard = process_val.get("process_ref")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "Missing process_ref in spec".to_string())?;

    let cand_pcard = process_val.get("process_cand")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "Missing process_cand in spec".to_string())?;

    let relation_type = process_val.get("relation_type")
        .and_then(|v| v.as_str())
        .unwrap_or("identity");

    let domain_val = process_val.get("domain")
        .ok_or_else(|| "Missing domain in spec".to_string())?;

    let mut inputs = Vec::new();
    if let Some(arr) = domain_val.as_sequence() {
        for item in arr {
            if let Some(s) = item.as_str() {
                inputs.push(s.to_string());
            } else if let Some(n) = item.as_i64() {
                inputs.push(n.to_string());
            } else if let Some(b) = item.as_bool() {
                inputs.push(b.to_string());
            }
        }
    }

    if inputs.is_empty() {
        return Err("Equivalence domain cannot be empty".to_string());
    }

    // Parse optional relation_options (backward-compatible: all default to false/None)
    let mut opts = RelationOptions::default();
    if let Some(ro) = process_val.get("relation_options") {
        opts.normalize_newlines = ro.get("normalize_newlines").and_then(|v| v.as_bool()).unwrap_or(false);
        opts.trim_whitespace = ro.get("trim_whitespace").and_then(|v| v.as_bool()).unwrap_or(false);
        opts.ignore_ansi = ro.get("ignore_ansi").and_then(|v| v.as_bool()).unwrap_or(false);
        opts.ignore_case = ro.get("ignore_case").and_then(|v| v.as_bool()).unwrap_or(false);
        opts.stop_on_first_mismatch = ro.get("stop_on_first_mismatch").and_then(|v| v.as_bool()).unwrap_or(false);
        opts.required_degree = ro.get("required_degree").and_then(|v| v.as_f64());
    }

    // Resolve absolute path to process files
    let ref_path = if Path::new(ref_pcard).is_absolute() {
        PathBuf::from(ref_pcard)
    } else {
        Path::new(clm_root).join(ref_pcard)
    };
    let cand_path = if Path::new(cand_pcard).is_absolute() {
        PathBuf::from(cand_pcard)
    } else {
        Path::new(clm_root).join(cand_pcard)
    };

    let ref_hash = crate::fs_utils::compute_stripped_file_hash(&ref_path)
        .unwrap_or_else(|_| format!("{}unknown_ref", crate::hash::DEFAULT_HASH_PREFIX));
    let cand_hash = crate::fs_utils::compute_stripped_file_hash(&cand_path)
        .unwrap_or_else(|_| format!("{}unknown_cand", crate::hash::DEFAULT_HASH_PREFIX));

    let domain_json = serde_json::to_string(&inputs).unwrap_or_default();
    let domain_hash = crate::fs_utils::compute_content_hash(&domain_json);

    let mut matched = 0;
    let mut total = 0;
    let mut witness_lines = Vec::new();
    let mut ref_total_ms = 0;
    let mut cand_total_ms = 0;

    let mut thread_results = Vec::new();
    std::thread::scope(|s| {
        let mut handles = Vec::new();
        for input in &inputs {
            let handle_ref = s.spawn(|| {
                let start = std::time::Instant::now();
                let res = execute_pcard(clm_root, ref_pcard, input);
                let elapsed = start.elapsed().as_millis() as u64;
                (res, elapsed)
            });
            let handle_cand = s.spawn(|| {
                let start = std::time::Instant::now();
                let res = execute_pcard(clm_root, cand_pcard, input);
                let elapsed = start.elapsed().as_millis() as u64;
                (res, elapsed)
            });
            handles.push((input, handle_ref, handle_cand));
        }

        for (input, h_ref, h_cand) in handles {
            let (out_ref_res, ref_elapsed) = h_ref.join().unwrap();
            let (out_cand_res, cand_elapsed) = h_cand.join().unwrap();
            thread_results.push((input, out_ref_res, ref_elapsed, out_cand_res, cand_elapsed));
        }
    });

    for (input, out_ref_res, ref_elapsed, out_cand_res, cand_elapsed) in thread_results {
        total += 1;
        ref_total_ms += ref_elapsed;
        cand_total_ms += cand_elapsed;

        let (out_ref, ref_err) = match out_ref_res {
            Ok(s) => (s, None),
            Err(e) => (String::new(), Some(e)),
        };
        let (out_cand, cand_err) = match out_cand_res {
            Ok(s) => (s, None),
            Err(e) => (String::new(), Some(e)),
        };

        // Normalize outputs before comparison
        let norm_ref = normalize_output(&out_ref, &opts);
        let norm_cand = normalize_output(&out_cand, &opts);

        let mut result = "fail";
        let mut comp_made = false;

        // If both executed successfully, perform comparison
        if ref_err.is_none() && cand_err.is_none() {
            comp_made = true;
            match relation_type {
                "identity" => {
                    if norm_ref == norm_cand {
                        result = "pass";
                        matched += 1;
                    }
                }
                "structural" => {
                    if let (Ok(ref_v), Ok(cand_v)) = (parse_json_or_yaml(&norm_ref), parse_json_or_yaml(&norm_cand)) {
                        let clean_ref = canonical_value(&clean_data(&ref_v));
                        let clean_cand = canonical_value(&clean_data(&cand_v));
                        if clean_ref == clean_cand {
                            result = "pass";
                            matched += 1;
                        }
                    }
                }
                "numerical" => {
                    if compare_numerical(&norm_ref, &norm_cand) {
                        result = "pass";
                        matched += 1;
                    }
                }
                "hash_invariant" => {
                    if norm_ref == norm_cand {
                        result = "pass";
                        matched += 1;
                    } else {
                        if let Ok(eq) = check_content_equivalent(clm_root, &norm_ref, &norm_cand)
                            && eq {
                                result = "pass";
                                matched += 1;
                            }
                    }
                }
                "invariant" => {
                    if norm_ref == norm_cand {
                        result = "pass";
                        matched += 1;
                    }
                }
                _ => return Err(format!("Unknown comparison relation: {}", relation_type)),
            }
        } else {
            // Execution failure is a first-class outcome, distinct from a
            // genuine output mismatch (WI-2). It is not counted as matched.
            result = "error";
        }

        // Build witness JSON with richer fields
        let ref_trunc = if out_ref.len() > 64 { &out_ref[0..64] } else { &out_ref };
        let cand_trunc = if out_cand.len() > 64 { &out_cand[0..64] } else { &out_cand };

        let mut witness_parts = vec![
            format!("\"input\":\"{}\"", input.replace('"', "\\\"")),
            format!("\"ref\":\"{}\"", ref_trunc.trim().replace('"', "\\\"").replace('\n', " ")),
            format!("\"cand\":\"{}\"", cand_trunc.trim().replace('"', "\\\"").replace('\n', " ")),
            format!("\"result\":\"{}\"", result),
        ];
        if let Some(ref_e) = &ref_err {
            witness_parts.push(format!("\"ref_error\":\"{}\"", ref_e.replace('"', "\\\"").replace('\n', " ")));
        }
        if let Some(cand_e) = &cand_err {
            witness_parts.push(format!("\"cand_error\":\"{}\"", cand_e.replace('"', "\\\"").replace('\n', " ")));
        }
        if result == "fail" && comp_made
            && let Some((idx, ac, bc)) = find_divergence(&norm_ref, &norm_cand) {
                witness_parts.push(format!("\"diff_at\":{},\"expected_char\":\"{}\",\"actual_char\":\"{}\"", idx, ac, bc));
            }

        let witness = format!("{{{}}}", witness_parts.join(","));
        witness_lines.push(witness);

        // Optional early stop on first mismatch
        if opts.stop_on_first_mismatch && result == "fail" {
            break;
        }
    }

    let degree = (matched as f64) / (total as f64);
    let timestamp = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
    let agent_did = std::env::var("CLM_AGENT_DID").unwrap_or_else(|_| "did:clm:bootstrap".to_string());

    let vcard_yaml = format!(
        "clm:\n  equivalence_vcard:\n    process_ref_hash: \"{}\"\n    process_cand_hash: \"{}\"\n    domain_hash: \"{}\"\n    relation_type: \"{}\"\n    degree_of_equivalence: {:.4}\n    witness_trail: [{}]\n    performance_differential:\n      ref_total_ms: {}\n      cand_total_ms: {}\n    timestamp: \"{}\"\n    agent_did: \"{}\"",
        ref_hash,
        cand_hash,
        domain_hash,
        relation_type,
        degree,
        witness_lines.join(","),
        ref_total_ms,
        cand_total_ms,
        timestamp,
        agent_did
    );

    let vcard_hash = crate::fs_utils::compute_content_hash(&vcard_yaml);
    // The stored coordinate must name the algorithm that produced the digest (charter L2);
    // the bare ISO value stays inside the hashed YAML as content.
    let g_time = crate::fs_utils::compute_g_time();

    // Save to Database
    if let Ok(conn) = crate::db::get_connection("content_memory", clm_root) {
        let _ = conn.execute(
            "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?);",
            rusqlite::params![vcard_hash, vcard_yaml, g_time],
        );
        let handle_name = format!("vcard:equivalence:{}", vcard_hash);
        let _ = conn.execute(
            "INSERT OR IGNORE INTO handle_registry (handle, current_hash, updated_at) VALUES (?, ?, ?);",
            rusqlite::params![handle_name, vcard_hash, timestamp],
        );
    }

    // Cache write-through
    let handle_name = format!("vcard:equivalence:{}", vcard_hash);
    crate::cache::setter_mcard_cache_handle(&handle_name, &vcard_hash);
    crate::cache::setter_mcard_cache(&vcard_hash, &vcard_yaml);

    // Save to execution_logs dir unless Zero-FS is true
    let zero_fs = crate::utils::is_zero_fs();
    if !zero_fs {
        let logs_dir = Path::new(clm_root).join("data").join("execution_logs");
        let _ = fs::create_dir_all(&logs_dir);
        let file_path = logs_dir.join(format!("equiv_{}.yaml", &vcard_hash[0..8]));
        let _ = fs::write(&file_path, &vcard_yaml);
    }

    // Output VCard hash
    let threshold = opts.required_degree.unwrap_or(1.0);
    let exit_code = if degree >= threshold { 0 } else { 1 };
    Ok((exit_code, format!("{}\n", vcard_hash)))
}