clm-kernel 0.0.9

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use serde_json::{Value, Serializer};
use serde_json::ser::PrettyFormatter;
use std::fs;
use std::path::Path;
use crate::db;
use crate::hash::prefixed;
use crate::utils::indent_lines;

pub fn split(clm_file: &str, clm_root: &str) -> Result<String, String> {
    // 1. Read CLM file
    let path = Path::new(clm_file);
    if !path.exists() {
        return Err(format!("File not found: {}", clm_file));
    }
    let yaml_content = fs::read_to_string(path)
        .map_err(|e| format!("Failed to read CLM file: {}", e))?;
    
    // Parse YAML using serde_yaml to preserve insertion order (via Value)
    let mut clm_val: Value = serde_yaml::from_str(&yaml_content)
        .map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
    
    let clm = clm_val.get_mut("clm")
        .ok_or_else(|| "Not a valid CLM file (missing 'clm:' root)".to_string())?;

    // Get clm_name
    let clm_name = clm.get("concrete_impl")
        .and_then(|c| c.get("operation"))
        .and_then(|o| o.as_str())
        .map(|s| s.to_string())
        .unwrap_or_else(|| {
            path.file_stem()
                .map(|s| s.to_string_lossy().to_string())
                .unwrap_or_else(|| "unknown".to_string())
        });

    let g_time = crate::fs_utils::compute_g_time();
    let output_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
    let _ = fs::create_dir_all(&output_dir);

    // -- 1. Extract A-MCard (abstract_spec) --
    let abstract_spec = clm.get("abstract_spec")
        .ok_or_else(|| "CLM has no abstract_spec section".to_string())?
        .clone();
    
    let a_content_json = to_string_pretty_2_spaces(&abstract_spec)?;
    let a_hash = sha256_hash_string(&a_content_json);

    let a_file = output_dir.join(format!("a_{}.yaml", &a_hash[..12]));
    let a_yaml_str = serde_yaml::to_string(&abstract_spec)
        .map_err(|e| format!("Failed to serialize abstract_spec: {}", e))?;
    let a_mcard_content = format!(
        "mcard:\n  hash: \"{}\"\n  g_time: \"{}\"\n  facet: \"abstract_spec\"\n  content_hash: \"{}\"\n  content:\n{}",
        prefixed(&a_hash), g_time, a_hash, indent_lines(&a_yaml_str, 4)
    );
    fs::write(&a_file, &a_mcard_content)
        .map_err(|e| format!("Failed to write A-MCard: {}", e))?;
    eprintln!("[DECOMPOSE] ✅ A-MCard: {}", a_file.to_string_lossy());
    eprintln!("[DECOMPOSE]   hash: {}", a_hash);

    // -- 2. Extract C-MCard (concrete_impl) --
    let mut concrete_impl = clm.get("concrete_impl")
        .ok_or_else(|| "CLM has no concrete_impl section".to_string())?
        .clone();
    
    // Strip gate-binding metadata: .precondition.vcard_pre, .postcondition.vcard_post
    if let Some(obj) = concrete_impl.as_object_mut() {
        if let Some(pre) = obj.get_mut("precondition")
            && let Some(pre_obj) = pre.as_object_mut() {
                pre_obj.remove("vcard_pre");
            }
        if let Some(post) = obj.get_mut("postcondition")
            && let Some(post_obj) = post.as_object_mut() {
                post_obj.remove("vcard_post");
            }
        // Inject a_hash
        obj.insert("a_hash".to_string(), Value::String(prefixed(&a_hash)));
    }

    let c_content_json = to_string_pretty_2_spaces(&concrete_impl)?;
    let c_hash = sha256_hash_string(&c_content_json);

    let c_original_yaml_str = serde_yaml::to_string(&clm.get("concrete_impl").unwrap())
        .map_err(|e| format!("Failed to serialize original concrete_impl: {}", e))?;
    
    let c_file = output_dir.join(format!("c_{}.yaml", &c_hash[..12]));
    let c_mcard_content = format!(
        "mcard:\n  hash: \"{}\"\n  g_time: \"{}\"\n  facet: \"concrete_impl\"\n  content_hash: \"{}\"\n  content:\n    a_hash: \"{}\"\n{}",
        prefixed(&c_hash), g_time, c_hash, prefixed(&a_hash), indent_lines(&c_original_yaml_str, 4)
    );
    fs::write(&c_file, &c_mcard_content)
        .map_err(|e| format!("Failed to write C-MCard: {}", e))?;
    eprintln!("[DECOMPOSE] ✅ C-MCard: {}", c_file.to_string_lossy());
    eprintln!("[DECOMPOSE]   hash: {}", c_hash);
    eprintln!("[DECOMPOSE]   a_hash: {}", a_hash);

    // -- 3. Extract B-MCard (balanced_exp) --
    let has_balanced = clm.get("balanced_exp").is_some();
    let mut b_mcard_content_opt = None;
    let b_hash = if has_balanced {
        let mut balanced_exp = clm.get("balanced_exp").unwrap().clone();
        if let Some(obj) = balanced_exp.as_object_mut() {
            obj.insert("c_hash".to_string(), Value::String(prefixed(&c_hash)));
        }
        let b_content_json = to_string_pretty_2_spaces(&balanced_exp)?;
        let b_hash_val = sha256_hash_string(&b_content_json);

        let b_file = output_dir.join(format!("b_{}.yaml", &b_hash_val[..12]));
        
        let expectation = clm.get("balanced_exp")
            .and_then(|b| b.get("expectation"))
            .and_then(|e| e.as_str())
            .unwrap_or("");
        
        let pending_cases = clm.get("balanced_exp")
            .and_then(|b| b.get("pending_cases"));

        let pending_cases_str = match pending_cases {
            Some(Value::Array(arr)) if !arr.is_empty() => {
                let y = serde_yaml::to_string(arr).unwrap_or_else(|_| "[]".to_string());
                format!("    pending_cases:\n{}", indent_lines(&y, 6))
            }
            _ => "    pending_cases: []".to_string(),
        };

        let b_mcard_content = format!(
            "mcard:\n  hash: \"{}\"\n  g_time: \"{}\"\n  facet: \"balanced_exp\"\n  content_hash: \"{}\"\n  content:\n    c_hash: \"{}\"\n    expectation: \"{}\"\n{}",
            prefixed(&b_hash_val), g_time, b_hash_val, prefixed(&c_hash), expectation, pending_cases_str
        );
        b_mcard_content_opt = Some(b_mcard_content.clone());
        fs::write(&b_file, &b_mcard_content)
            .map_err(|e| format!("Failed to write B-MCard: {}", e))?;
        eprintln!("[DECOMPOSE] ✅ B-MCard: {}", b_file.to_string_lossy());
        eprintln!("[DECOMPOSE]   hash: {}", b_hash_val);
        eprintln!("[DECOMPOSE]   c_hash: {}", c_hash);
        let pending_count = match pending_cases {
            Some(Value::Array(arr)) => arr.len(),
            _ => 0,
        };
        eprintln!("[DECOMPOSE]   pending_cases: {}", pending_count);

        b_hash_val
    } else {
        eprintln!("[DECOMPOSE] ⚠️  No balanced_exp section — B-MCard skipped");
        "none".to_string()
    };

    // -- 4. Compute Merkle Root Hash --
    let b_hash_for_root = if b_hash == "none" { "none" } else { &b_hash };
    let root_hash_input = format!("{}:{}:{}:{}:{}:{}", crate::hash::DEFAULT_HASH_PREFIX, a_hash, crate::hash::DEFAULT_HASH_PREFIX, c_hash, crate::hash::DEFAULT_HASH_PREFIX, b_hash_for_root);
    let clm_root_hash = sha256_hash_string(&root_hash_input);

    // -- 5. Register CLM handles in Database --
    let db_pillar = "content_memory";
    let root_content = format!(
        "{{\"@type\":\"CLM_Root\",\"clm_name\":\"{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"{}\",\"c_hash\":\"{}\",\"b_hash\":\"{}\"}}",
        clm_name, prefixed(&clm_root_hash), prefixed(&a_hash), prefixed(&c_hash), prefixed(&b_hash)
    );

    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}", clm_name), &clm_root_hash, &root_content);
    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}:a", clm_name), &a_hash, "");
    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}:c", clm_name), &c_hash, "");
    if b_hash != "none" {
        let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}:b", clm_name), &b_hash, "");
    }

    // Register facet handles to match shell split behavior exactly
    let a_mcard_hash = sha256_hash_string(&a_mcard_content);
    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("facet:a:{}", &a_hash[..12]), &a_mcard_hash, &a_mcard_content);

    let c_mcard_hash = sha256_hash_string(&c_mcard_content);
    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("facet:c:{}", &c_hash[..12]), &c_mcard_hash, &c_mcard_content);

    if let Some(ref b_mcard_content) = b_mcard_content_opt {
        let b_mcard_hash = sha256_hash_string(b_mcard_content);
        let _ = db::handle_register_batch(db_pillar, clm_root, &format!("facet:b:{}", &b_hash[..12]), &b_mcard_hash, b_mcard_content);
    }
    eprintln!("[DECOMPOSE] 🔗 Registered handles: clm:{} → {}", clm_name, prefixed(&clm_root_hash));

    // -- 6. Print composite reference exactly like decompose_clm --
    let mut out = String::new();
    out.push_str("\n######################################################\n");
    out.push_str("  Cubical Decomposition Complete\n");
    out.push_str("######################################################\n");
    out.push_str("clm:\n");
    out.push_str(&format!("  clm_root_hash: \"{}\"\n", prefixed(&clm_root_hash)));
    out.push_str(&format!("  clm_name: \"{}\"\n", clm_name));
    out.push_str(&format!("  a_hash: \"{}\"\n", prefixed(&a_hash)));
    out.push_str(&format!("  c_hash: \"{}\"\n", prefixed(&c_hash)));
    if b_hash != "none" {
        out.push_str(&format!("  b_hash: \"{}\"\n", prefixed(&b_hash)));
    }
    out.push('\n');
    out.push_str(&format!("# Chain: A({}) ← C({}) ← B({})\n", a_hash, c_hash, b_hash_for_root));
    out.push_str(&format!("# Root:  {} = H(a:c:b)\n", clm_root_hash));

    Ok(out)
}

pub fn merge(a_file: &str, c_file: &str, b_file: Option<&str>) -> Result<String, String> {
    // 1. Read A-MCard
    let a_path = Path::new(a_file);
    if !a_path.exists() {
        return Err(format!("File not found: {}", a_file));
    }
    let a_content = fs::read_to_string(a_path)
        .map_err(|e| format!("Failed to read A-MCard file: {}", e))?;
    let a_mcard: Value = serde_yaml::from_str(&a_content)
        .map_err(|e| format!("Failed to parse A-MCard YAML: {}", e))?;
    let abstract_spec = a_mcard.get("mcard")
        .and_then(|m| m.get("content"))
        .ok_or_else(|| "Missing 'mcard.content' in A-MCard".to_string())?;

    // 2. Read C-MCard
    let c_path = Path::new(c_file);
    if !c_path.exists() {
        return Err(format!("File not found: {}", c_file));
    }
    let c_content = fs::read_to_string(c_path)
        .map_err(|e| format!("Failed to read C-MCard file: {}", e))?;
    let c_mcard: Value = serde_yaml::from_str(&c_content)
        .map_err(|e| format!("Failed to parse C-MCard YAML: {}", e))?;
    let concrete_impl_val = c_mcard.get("mcard")
        .and_then(|m| m.get("content"))
        .ok_or_else(|| "Missing 'mcard.content' in C-MCard".to_string())?;
    
    // Strip a_hash from concrete_impl
    let mut concrete_impl = concrete_impl_val.clone();
    if let Some(obj) = concrete_impl.as_object_mut() {
        obj.remove("a_hash");
    }

    // 3. Read B-MCard (optional)
    let mut balanced_exp = None;
    if let Some(bf) = b_file {
        let b_path = Path::new(bf);
        if b_path.exists() {
            let b_content = fs::read_to_string(b_path)
                .map_err(|e| format!("Failed to read B-MCard file: {}", e))?;
            let b_mcard: Value = serde_yaml::from_str(&b_content)
                .map_err(|e| format!("Failed to parse B-MCard YAML: {}", e))?;
            let balanced_exp_val = b_mcard.get("mcard")
                .and_then(|m| m.get("content"))
                .ok_or_else(|| "Missing 'mcard.content' in B-MCard".to_string())?;
            
            // Strip c_hash from balanced_exp
            let mut b_val = balanced_exp_val.clone();
            if let Some(obj) = b_val.as_object_mut() {
                obj.remove("c_hash");
            }
            balanced_exp = Some(b_val);
        }
    }

    // Reconstruct CLM
    let mut clm_map = serde_json::Map::new();
    clm_map.insert("abstract_spec".to_string(), abstract_spec.clone());
    clm_map.insert("concrete_impl".to_string(), concrete_impl);
    if let Some(b_val) = balanced_exp {
        clm_map.insert("balanced_exp".to_string(), b_val);
    }
    
    let mut root_map = serde_json::Map::new();
    root_map.insert("clm".to_string(), Value::Object(clm_map));

    let root_val = Value::Object(root_map);
    serde_yaml::to_string(&root_val)
        .map_err(|e| format!("Failed to serialize reconstructed CLM: {}", e))
}

pub fn to_string_pretty_2_spaces<T: serde::Serialize>(value: &T) -> Result<String, String> {
    let mut buf = Vec::new();
    let formatter = PrettyFormatter::with_indent(b"  ");
    let mut ser = Serializer::with_formatter(&mut buf, formatter);
    value.serialize(&mut ser)
        .map_err(|e| format!("Failed to serialize pretty JSON: {}", e))?;
    Ok(String::from_utf8(buf).unwrap())
}

pub fn sha256_hash_string(s: &str) -> String {
    crate::hash::raw_hash_string(s)
}



#[allow(dead_code)]
pub fn substitute(clm_file: &str, new_impl_file_or_op: &str, clm_root: &str) -> Result<String, String> {
    let path = Path::new(clm_file);
    if !path.exists() {
        return Err(format!("File not found: {}", clm_file));
    }
    let yaml_content = fs::read_to_string(path)
        .map_err(|e| format!("Failed to read CLM file: {}", e))?;
    let mut clm_val: Value = serde_yaml::from_str(&yaml_content)
        .map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
    let clm = clm_val.get_mut("clm")
        .ok_or_else(|| "Not a valid CLM file (missing 'clm:' root)".to_string())?;

    let abstract_spec = clm.get("abstract_spec")
        .ok_or_else(|| "CLM has no abstract_spec section".to_string())?
        .clone();

    let new_c_spec: Value = if Path::new(new_impl_file_or_op).exists() {
        let c_content = fs::read_to_string(new_impl_file_or_op)
            .map_err(|e| format!("Failed to read new implementation file: {}", e))?;
        let parsed: Value = serde_yaml::from_str(&c_content)
            .map_err(|e| format!("Failed to parse new implementation YAML: {}", e))?;
        if let Some(c) = parsed.get("clm").and_then(|c| c.get("concrete_impl")) {
            c.clone()
        } else if parsed.get("concrete_impl").is_some() {
            parsed.get("concrete_impl").unwrap().clone()
        } else {
            parsed
        }
    } else {
        serde_json::json!({
            "runtime": "system",
            "operation": new_impl_file_or_op,
            "inputs": Vec::<String>::new(),
            "outputs": Vec::<String>::new(),
            "process": {
                "script_handle": format!("script:{}", new_impl_file_or_op)
            }
        })
    };

    let a_content_json = to_string_pretty_2_spaces(&abstract_spec)?;
    let a_hash = sha256_hash_string(&a_content_json);

    let mut concrete_impl = new_c_spec.clone();
    if let Some(obj) = concrete_impl.as_object_mut() {
        obj.insert("a_hash".to_string(), Value::String(prefixed(&a_hash)));
        if let Some(pre) = obj.get_mut("precondition")
            && let Some(pre_obj) = pre.as_object_mut() {
                pre_obj.remove("vcard_pre");
            }
        if let Some(post) = obj.get_mut("postcondition")
            && let Some(post_obj) = post.as_object_mut() {
                post_obj.remove("vcard_post");
            }
    }

    let c_content_json = to_string_pretty_2_spaces(&concrete_impl)?;
    let c_hash = sha256_hash_string(&c_content_json);

    let b_spec = clm.get("balanced_exp").cloned();
    let expectation = b_spec.as_ref()
        .and_then(|b| b.get("expectation"))
        .and_then(|e| e.as_str())
        .unwrap_or("Substituted implementation pending verification");
    let pending_cases = b_spec.as_ref()
        .and_then(|b| b.get("pending_cases"))
        .cloned()
        .unwrap_or(Value::Array(Vec::new()));

    let mut new_clm = serde_json::Map::new();
    new_clm.insert("abstract_spec".to_string(), abstract_spec);
    new_clm.insert("concrete_impl".to_string(), concrete_impl);
    
    let mut new_b = serde_json::Map::new();
    new_b.insert("expectation".to_string(), Value::String(expectation.to_string()));
    new_b.insert("pending_cases".to_string(), pending_cases);
    new_clm.insert("balanced_exp".to_string(), Value::Object(new_b));

    let mut new_root = serde_json::Map::new();
    new_root.insert("clm".to_string(), Value::Object(new_clm));

    let new_yaml = serde_yaml::to_string(&Value::Object(new_root))
        .map_err(|e| format!("Failed to serialize substituted CLM: {}", e))?;

    let output_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
    let _ = fs::create_dir_all(&output_dir);
    let sub_file = output_dir.join(format!("substituted_{}.yaml", &c_hash[..12]));
    fs::write(&sub_file, &new_yaml)
        .map_err(|e| format!("Failed to write substituted file: {}", e))?;

    // Register CLM handles in Database
    let root_hash_input = format!("{}:{}:{}:{}:{}:none", crate::hash::DEFAULT_HASH_PREFIX, a_hash, crate::hash::DEFAULT_HASH_PREFIX, c_hash, crate::hash::DEFAULT_HASH_PREFIX);
    let clm_root_hash = sha256_hash_string(&root_hash_input);
    let root_content = format!(
        "{{\"@type\":\"CLM_Root\",\"clm_name\":\"substituted_{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"{}\",\"c_hash\":\"{}\",\"b_hash\":\"none\"}}",
        &c_hash[..12], prefixed(&clm_root_hash), prefixed(&a_hash), prefixed(&c_hash)
    );

    let _ = db::handle_register_batch("content_memory", clm_root, &format!("clm:substituted_{}", &c_hash[..12]), &clm_root_hash, &root_content);

    Ok(sub_file.to_string_lossy().to_string())
}


#[path = "baldwin_augment.rs"]
mod baldwin_augment;
#[allow(unused_imports)]
pub use baldwin_augment::*;
#[cfg(test)]
#[path = "baldwin_tests.rs"]
mod tests;