clm-kernel 0.0.14

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use serde_json::{json, Value};
use crate::cpn::solver::solve_nullspace;
use crate::memorize::memorize_mcard_string;

fn compute_sha256(text: &str) -> String {
    crate::hash::raw_hash_string(text)
}

fn resolve_sub_net_content(r#ref: &str, db_path: &str, clm_root: &str) -> Result<(String, String), String> {
    if r#ref.contains('/') || r#ref.ends_with(".yaml") || Path::new(r#ref).exists() {
        let mut target_path = r#ref.to_string();
        if !Path::new(&target_path).exists() {
            let possible = Path::new(clm_root).join(r#ref);
            if possible.exists() {
                target_path = possible.to_string_lossy().to_string();
            } else {
                return Err(format!("Sub-net file not found: {}", r#ref));
            }
        }
        let content = fs::read_to_string(&target_path)
            .map_err(|e| format!("Failed to read sub-net file {}: {}", target_path, e))?;
        let sha = compute_sha256(&content);
        return Ok((content, crate::hash::prefixed(&sha)));
    }

    if db_path.is_empty() || !Path::new(db_path).exists() {
        return Err(format!("Database not found at {} to resolve handle {}", db_path, r#ref));
    }

    let conn = rusqlite::Connection::open(db_path)
        .map_err(|e| format!("Failed to open DB: {}", e))?;

    let content_hash = if r#ref.starts_with(crate::hash::DEFAULT_HASH_PREFIX) {
        r#ref.to_string()
    } else {
        let mut stmt = conn.prepare("SELECT current_hash FROM handle_registry WHERE handle = ?")
            .map_err(|e| e.to_string())?;
        let hash_opt: Option<String> = stmt.query_row([r#ref], |row| row.get(0)).ok();
        match hash_opt {
            Some(h) => h,
            None => return Err(format!("Handle not found in registry: {}", r#ref)),
        }
    };

    let mut stmt = conn.prepare("SELECT content FROM card WHERE hash = ?")
        .map_err(|e| e.to_string())?;
    let content_opt: Option<String> = stmt.query_row([&content_hash], |row| row.get(0)).ok();
    match content_opt {
        Some(c) => Ok((c, content_hash)),
        None => Err(format!("Content not found for hash: {}", content_hash)),
    }
}

fn flatten_net(
    net_val: &Value,
    prefix: &str,
    rename_map: &HashMap<String, String>,
    db_path: &str,
    clm_root: &str,
    telemetry: &mut Value,
    flat_places: &mut Vec<Value>,
    flat_transitions: &mut Vec<Value>,
) -> Result<(), String> {
    let petri_net = net_val.get("petri_net").ok_or("Missing 'petri_net' object")?;
    let places = petri_net.get("places").and_then(|v| v.as_array()).ok_or("Missing or invalid 'places' array")?;
    let transitions = petri_net.get("transitions").and_then(|v| v.as_array()).ok_or("Missing or invalid 'transitions' array")?;

    let mut local_rename_map = rename_map.clone();
    for p in places {
        let pid = p.get("id").and_then(|v| v.as_str()).ok_or("Place missing 'id'")?;
        if !local_rename_map.contains_key(pid) {
            let mapped_id = if prefix.is_empty() { pid.to_string() } else { format!("{}{}", prefix, pid) };
            local_rename_map.insert(pid.to_string(), mapped_id.clone());

            let mut new_p = p.clone();
            new_p["id"] = Value::String(mapped_id);
            flat_places.push(new_p);
        }
    }

    for t in transitions {
        let t_id = t.get("id").and_then(|v| v.as_str()).ok_or("Transition missing 'id'")?;
        let prefixed_tid = if prefix.is_empty() { t_id.to_string() } else { format!("{}{}", prefix, t_id) };

        if let Some(sub_net_ref) = t.get("sub_net").and_then(|v| v.as_str()) {
            let (sub_content, sub_hash) = resolve_sub_net_content(sub_net_ref, db_path, clm_root)?;
            telemetry["sub_net_hashes"].as_array_mut().unwrap().push(Value::String(sub_hash));

            let sub_val: Value = serde_yaml::from_str(&sub_content)
                .map_err(|e| format!("Failed to parse sub-net YAML {}: {}", sub_net_ref, e))?;
            let sub_petri = sub_val.get("petri_net").ok_or("Sub-net missing 'petri_net'")?;
            let sub_ingress = sub_petri.get("ingress").and_then(|v| v.as_str())
                .ok_or("Sub-net missing 'ingress' place")?;
            let sub_egress = sub_petri.get("egress").and_then(|v| v.as_str())
                .ok_or("Sub-net missing 'egress' place")?;

            let t_inputs = t.get("inputs").and_then(|v| v.as_array())
                .ok_or("Transition representing sub-net missing 'inputs'")?;
            let t_outputs = t.get("outputs").and_then(|v| v.as_array())
                .ok_or("Transition representing sub-net missing 'outputs'")?;

            if t_inputs.is_empty() || t_outputs.is_empty() {
                return Err(format!("Transition {} representing sub-net must have input and output places.", t_id));
            }

            let parent_input_raw = t_inputs[0].as_str().ok_or("Invalid transition input ID")?;
            let parent_output_raw = t_outputs[0].as_str().ok_or("Invalid transition output ID")?;

            let parent_input = local_rename_map.get(parent_input_raw).cloned()
                .unwrap_or_else(|| parent_input_raw.to_string());
            let parent_output = local_rename_map.get(parent_output_raw).cloned()
                .unwrap_or_else(|| parent_output_raw.to_string());

            let new_prefix = format!("{}{}__", prefix, t_id);
            let mut sub_rename_map = HashMap::new();
            sub_rename_map.insert(sub_ingress.to_string(), parent_input.clone());
            sub_rename_map.insert(sub_egress.to_string(), parent_output.clone());

            let boundary_entry = json!({
                "parent_transition": prefixed_tid,
                "sub_net_ingress": sub_ingress,
                "sub_net_egress": sub_egress,
                "ingress_mapped_to": parent_input,
                "egress_mapped_to": parent_output
            });
            telemetry["boundary_map"].as_array_mut().unwrap().push(boundary_entry);

            flatten_net(&sub_val, &new_prefix, &sub_rename_map, db_path, clm_root, telemetry, flat_places, flat_transitions)?;
        } else {
            let mut new_t = t.clone();
            new_t["id"] = Value::String(prefixed_tid);

            if let Some(inputs) = t.get("inputs").and_then(|v| v.as_array()) {
                let mut new_inputs = Vec::new();
                for inp in inputs {
                    let inp_str = inp.as_str().ok_or("Invalid input place ID")?;
                    let mapped = local_rename_map.get(inp_str).cloned()
                        .unwrap_or_else(|| if prefix.is_empty() { inp_str.to_string() } else { format!("{}{}", prefix, inp_str) });
                    new_inputs.push(Value::String(mapped));
                }
                new_t["inputs"] = Value::Array(new_inputs);
            }

            if let Some(outputs) = t.get("outputs").and_then(|v| v.as_array()) {
                let mut new_outputs = Vec::new();
                for out in outputs {
                    let out_str = out.as_str().ok_or("Invalid output place ID")?;
                    let mapped = local_rename_map.get(out_str).cloned()
                        .unwrap_or_else(|| if prefix.is_empty() { out_str.to_string() } else { format!("{}{}", prefix, out_str) });
                    new_outputs.push(Value::String(mapped));
                }
                new_t["outputs"] = Value::Array(new_outputs);
            }

            flat_transitions.push(new_t);
        }
    }

    Ok(())
}

pub fn compose_nets(net_path: &str, output_path: &str, telemetry_path: &str, db_path: &str, clm_root: &str) -> Result<String, String> {
    if !Path::new(net_path).exists() {
        return Err(format!("Error: Input net not found: {}", net_path));
    }

    let root_content = fs::read_to_string(net_path)
        .map_err(|e| format!("Failed to read input net: {}", e))?;
    let root_hash = crate::hash::prefixed(&compute_sha256(&root_content));

    let root_dict: Value = serde_yaml::from_str(&root_content)
        .map_err(|e| format!("Failed to parse root net: {}", e))?;

    let mut telemetry = json!({
        "root_net_hash": root_hash,
        "sub_net_hashes": [],
        "boundary_map": []
    });

    let mut flat_places = Vec::new();
    let mut flat_transitions = Vec::new();

    flatten_net(&root_dict, "", &HashMap::new(), db_path, clm_root, &mut telemetry, &mut flat_places, &mut flat_transitions)?;

    let mut flat_dict = json!({
        "petri_net": {
            "name": root_dict.get("petri_net").and_then(|v| v.get("name")).unwrap_or(&Value::String("compiled_flat_net".to_string())),
            "places": flat_places,
            "transitions": flat_transitions
        }
    });

    // Copy non-places/transitions keys from root petri_net
    if let Some(petri_net) = root_dict.get("petri_net").and_then(|v| v.as_object()) {
        for (k, v) in petri_net {
            if k != "places" && k != "transitions" {
                flat_dict["petri_net"][k] = v.clone();
            }
        }
    }

    let flat_yaml = serde_yaml::to_string(&flat_dict)
        .map_err(|e| format!("Failed to serialize flat net to YAML: {}", e))?;

    // Matrix size validation
    let place_count = flat_places.len();
    let trans_count = flat_transitions.len();

    if place_count > 100 {
        return Err(format!("❌ [MATRIX_SIZE_GATE] Hard Abort: Combined place count {} exceeds the security threshold of 100 places!", place_count));
    } else if place_count > 50 {
        eprintln!("⚠️  [MATRIX_SIZE_GATE] Warning: Combined place count {} exceeds 50 places.", place_count);
    }

    // Compile Matrix D and solve P-invariants
    let mut place_to_idx = HashMap::new();
    for (i, p) in flat_places.iter().enumerate() {
        let pid = p["id"].as_str().ok_or("Missing place ID")?;
        place_to_idx.insert(pid.to_string(), i);
    }

    let mut trans_to_idx = HashMap::new();
    for (j, t) in flat_transitions.iter().enumerate() {
        let tid = t["id"].as_str().ok_or("Missing transition ID")?;
        trans_to_idx.insert(tid.to_string(), j);
    }

    let mut d_minus = vec![vec![0; trans_count]; place_count];
    let mut d_plus = vec![vec![0; trans_count]; place_count];
    for (j, t) in flat_transitions.iter().enumerate() {
        if let Some(inputs) = t.get("inputs").and_then(|v| v.as_array()) {
            for inp in inputs {
                if let Some(inp_str) = inp.as_str()
                    && let Some(&pidx) = place_to_idx.get(inp_str) {
                        d_minus[pidx][j] += 1;
                    }
            }
        }
        if let Some(outputs) = t.get("outputs").and_then(|v| v.as_array()) {
            for outp in outputs {
                if let Some(outp_str) = outp.as_str()
                    && let Some(&pidx) = place_to_idx.get(outp_str) {
                        d_plus[pidx][j] += 1;
                    }
            }
        }
    }

    let mut d = vec![vec![0; trans_count]; place_count];
    for r in 0..place_count {
        for c in 0..trans_count {
            d[r][c] = d_plus[r][c] - d_minus[r][c];
        }
    }

    let basis_vectors = solve_nullspace(&d, place_count, trans_count, true);

    // Verify Noetherian positive basis
    let mut has_positive_basis = false;
    let mut certificate_basis_strings = Vec::new();
    for basis in &basis_vectors {
        let basis_str = basis.iter().map(|v| v.to_string()).collect::<Vec<String>>().join(" ");
        certificate_basis_strings.push(basis_str);

        let mut is_positive = true;
        let mut has_any_positive = false;
        for &val in basis {
            if val < 0 {
                is_positive = false;
            }
            if val > 0 {
                has_any_positive = true;
            }
        }
        if is_positive && has_any_positive {
            has_positive_basis = true;
        }
    }

    if !has_positive_basis {
        let mut error_msg = format!(
            "❌ [NOETHER_ERR] Noetherian verification failed: Compiled net has no non-trivial, positive place conservation invariant (P-invariant)!\n  [NUM_BASIS_VECTORS]: {}\n",
            basis_vectors.len()
        );
        for (idx, vec) in basis_vectors.iter().enumerate() {
            error_msg.push_str(&format!("    Basis #{}: {:?}\n", idx, vec));
        }
        return Err(error_msg);
    }

    // Verify structural P-invariant coverage
    for r in 0..place_count {
        let mut place_covered = false;
        for basis in &basis_vectors {
            // Check if basis is positive and component r is > 0
            let mut is_positive = true;
            for &val in basis {
                if val < 0 {
                    is_positive = false;
                }
            }
            if is_positive && basis[r] > 0 {
                place_covered = true;
                break;
            }
        }
        if !place_covered {
            return Err("❌ [NOETHER_ERR] Noetherian verification failed: Compiled net violates P-invariant place conservation (some places are not covered by any positive place conservation law)!".to_string());
        }
    }

    // Construct manifest YAML
    let mut manifest_content = String::new();
    manifest_content.push_str("composition_manifest:\n");
    manifest_content.push_str(&format!("  root_net_hash: \"{}\"\n", telemetry["root_net_hash"].as_str().unwrap_or("")));
    manifest_content.push_str("  sub_net_hashes:\n");
    for sub in telemetry["sub_net_hashes"].as_array().unwrap() {
        manifest_content.push_str(&format!("    - \"{}\"\n", sub.as_str().unwrap_or("")));
    }
    manifest_content.push_str("  boundary_map:\n");
    for bound in telemetry["boundary_map"].as_array().unwrap() {
        manifest_content.push_str("    - parent_transition: \"");
        manifest_content.push_str(bound["parent_transition"].as_str().unwrap_or(""));
        manifest_content.push_str("\"\n      sub_net_ingress: \"");
        manifest_content.push_str(bound["sub_net_ingress"].as_str().unwrap_or(""));
        manifest_content.push_str("\"\n      sub_net_egress: \"");
        manifest_content.push_str(bound["sub_net_egress"].as_str().unwrap_or(""));
        manifest_content.push_str("\"\n      ingress_mapped_to: \"");
        manifest_content.push_str(bound["ingress_mapped_to"].as_str().unwrap_or(""));
        manifest_content.push_str("\"\n      egress_mapped_to: \"");
        manifest_content.push_str(bound["egress_mapped_to"].as_str().unwrap_or(""));
        manifest_content.push_str("\"\n");
    }
    manifest_content.push_str("  p_invariant_nullspace_certificate:\n");
    manifest_content.push_str("    basis_vectors:\n");
    for vec_str in &certificate_basis_strings {
        manifest_content.push_str(&format!("      - \"{}\"\n", vec_str));
    }

    let manifest_hash = compute_sha256(&manifest_content);
    let manifest_size = manifest_content.len();
    let g_time = crate::utils::now_iso8601();

    let mut mcard_content = String::new();
    mcard_content.push_str("mcard:\n");
    mcard_content.push_str(&format!("  g_time: \"{}\"\n", g_time));
    mcard_content.push_str(&format!("  content_hash: \"{}\"\n", manifest_hash));
    mcard_content.push_str("  source:\n");
    mcard_content.push_str("    filename: \"composition_manifest.yaml\"\n");
    mcard_content.push_str("    mime_type: \"application/yaml\"\n");
    mcard_content.push_str(&format!("    size_bytes: {}\n", manifest_size));
    mcard_content.push_str("    encoding: \"inline\"\n");
    mcard_content.push_str("  content: |\n");
    for line in manifest_content.lines() {
        mcard_content.push_str(&format!("    {}\n", line));
    }

    // Memorize Composition Manifest MCard
    memorize_mcard_string(&mcard_content, "content", clm_root, Some("composition_manifest.yaml"))?;

    // Write flat net and telemetry files if not "MEMORY"
    let zero_fs = crate::utils::is_zero_fs();
    if !zero_fs && output_path != "MEMORY" {
        fs::write(output_path, &flat_yaml)
            .map_err(|e| format!("Failed to write flat net to file {}: {}", output_path, e))?;
    }
    if !zero_fs && telemetry_path != "MEMORY" && !telemetry_path.is_empty() {
        let tele_str = serde_json::to_string_pretty(&telemetry)
            .map_err(|e| format!("Failed to serialize telemetry to JSON: {}", e))?;
        fs::write(telemetry_path, &tele_str)
            .map_err(|e| format!("Failed to write telemetry to file {}: {}", telemetry_path, e))?;
    }

    // Construct standard output output (matching compose_nets.sh expected segments)
    let mut out_buf = String::new();
    if output_path == "MEMORY" {
        out_buf.push_str("===FLAT_NET_YAML===\n");
        out_buf.push_str(&flat_yaml);
        out_buf.push_str("===END_FLAT_NET_YAML===\n");
    }
    if telemetry_path == "MEMORY" {
        out_buf.push_str("===TELEMETRY_JSON===\n");
        out_buf.push_str(&serde_json::to_string_pretty(&telemetry).unwrap());
        out_buf.push_str("\n===END_TELEMETRY_JSON===\n");
    }
    if output_path != "MEMORY" && telemetry_path != "MEMORY" {
        out_buf.push_str(&format!("Compiler successfully compiled {} places and {} transitions.\n", place_count, trans_count));
    }

    Ok(out_buf)
}