clm-kernel 0.0.23

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 super::types::{PetriNetYaml, RootTopologyYaml, hash_string};
use super::zta::authorize_kenotic_sponsor;
use super::token_ops::build_marking_json;

/// Parse and deserialize the Petri net topology YAML file.
pub fn parse_topology(topo_file: &str) -> Result<(PetriNetYaml, String), String> {
    let topo_content = if Path::new(topo_file).exists() {
        fs::read_to_string(topo_file)
            .map_err(|e| format!("Failed to read topology file: {}", e))?
    } else {
        return Err(format!("Topology file not found: {}", topo_file));
    };

    let root_topo: RootTopologyYaml = serde_yaml::from_str(&topo_content)
        .map_err(|e| format!("Failed to parse topology YAML: {}", e))?;
    Ok((root_topo.petri_net, topo_content))
}

pub fn resolve_run_paths(clm_root: &str, net_name: &str) -> (String, String, bool, String) {
    let zero_fs = crate::utils::is_zero_fs();
    let run_id = crate::cross_cutting::context::CLMContext::get_scoped_or_env(crate::layer0::vocabulary_env::ENV_CLM_RUN_ID).unwrap_or_else(|| {
        let ts = chrono::Utc::now().timestamp();
        format!("pn_{}_{}_{}", net_name, ts, std::process::id())
    });

    let log_path = crate::cross_cutting::context::CLMContext::get_scoped_or_env(crate::layer0::vocabulary_env::ENV_CLM_EVENT_LOG_PATH).unwrap_or_else(|| {
        let scratch_dir = if zero_fs {
            Path::new(&crate::layer0::environment::var("TMPDIR").unwrap_or_else(|_| "/tmp".to_string()))
                .join(format!(".{}_scratch", run_id))
        } else {
            Path::new(clm_root).join("data").join("execution_logs").join(format!(".{}_scratch", run_id))
        };
        scratch_dir.join("token_events.jsonl").to_string_lossy().to_string()
    });

    let marking_dir = if zero_fs {
        String::new()
    } else {
        crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_PETRI_MARKING_DIR).unwrap_or_else(|_| {
            let scratch_dir = Path::new(clm_root).join("data").join("execution_logs").join(&run_id);
            scratch_dir.join("marking").to_string_lossy().to_string()
        })
    };

    (run_id, marking_dir, zero_fs, log_path)
}

pub fn format_invariants_banner(
    active_p_invariants: &[Vec<i64>],
    active_p_constants: &[i64],
    active_t_invariants: &[Vec<i64>],
) -> String {
    let mut out_buf = String::new();
    out_buf.push_str(&format!("  🔍 Noetherian P-Invariants active: {}\n", active_p_invariants.len()));
    for (pi_idx, weights) in active_p_invariants.iter().enumerate() {
        let weights_str = weights.iter().map(|w| w.to_string()).collect::<Vec<_>>().join(" ");
        out_buf.push_str(&format!("    P-Inv #{}: [{}] (Expected Constant: {})\n", pi_idx, weights_str, active_p_constants[pi_idx]));
    }
    out_buf.push_str(&format!("  🔍 Noetherian T-Invariants active: {}\n", active_t_invariants.len()));
    for (ti_idx, firings) in active_t_invariants.iter().enumerate() {
        let firings_str = firings.iter().map(|f| f.to_string()).collect::<Vec<_>>().join(" ");
        out_buf.push_str(&format!("    T-Inv #{}: [{}]\n", ti_idx, firings_str));
    }
    out_buf
}

pub fn sync_sqlite_markings(
    places: &[super::types::PlaceYaml],
    place_markings: &HashMap<String, i64>,
    place_colors: &HashMap<String, String>,
    run_id: &str,
    clm_root: &str,
) -> Result<(), String> {
    let mut markings_map = serde_json::Map::new();
    let mut colors_map = serde_json::Map::new();
    for p in places {
        let tok = place_markings.get(&p.id).cloned().unwrap_or(0);
        markings_map.insert(p.id.clone(), serde_json::Value::Number(tok.into()));
        if let Some(col) = place_colors.get(&p.id)
            && !col.is_empty() {
                colors_map.insert(p.id.clone(), serde_json::Value::String(col.clone()));
            }
    }
    let markings_json = serde_json::json!({
        "run_id": run_id,
        "markings": markings_map,
        "colors": colors_map
    }).to_string();

    let handle_name = format!("run:{}:markings", run_id);
    let markings_hash = hash_string(&markings_json);
    crate::db::handle_register_batch(
        crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG, clm_root, &handle_name, &markings_hash, &markings_json,
    ).map_err(|e| e.to_string())
}

pub fn init_kenotic_state(
    net: &PetriNetYaml,
    topo_content: &str,
    place_markings: &HashMap<String, i64>,
    place_colors: &HashMap<String, String>,
    run_id: &str,
    clm_root: &str,
    sponsor_did: &str,
    vm_ctx: &mut crate::cross_cutting::context::CLMContext,
) -> Result<String, String> {
    let topo_hash = hash_string(topo_content);
    crate::db::handle_register_batch(
        crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG, clm_root, &format!("run:{}:topology", run_id), &topo_hash, topo_content,
    ).map_err(|e| e.to_string())?;

    authorize_kenotic_sponsor(sponsor_did, &net.authorized_sponsors)?;

    let sponsor_hash = hash_string(sponsor_did);
    crate::db::handle_register_batch(
        crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG, clm_root, &format!("run:{}:sponsor", run_id), &sponsor_hash, sponsor_did,
    ).map_err(|e| e.to_string())?;

    let init_marking_json = build_marking_json(
        &topo_hash, &net.places, place_markings, place_colors, sponsor_did, sponsor_did, "", None,
    );
    let init_marking_str = init_marking_json.to_string();
    let init_marking_hash = hash_string(&init_marking_str);

    crate::db::handle_register_batch(
        crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG, clm_root, &format!("run:{}:marking", run_id), &init_marking_hash, &init_marking_str,
    ).map_err(|e| e.to_string())?;

    vm_ctx.set_var(crate::layer0::vocabulary_env::ENV_CLM_KENOTIC_CURRENT_MARKING_HASH, &init_marking_hash);
    vm_ctx.set_var(crate::layer0::vocabulary_env::ENV_CLM_KENOTIC_SPONSOR_DID, sponsor_did);

    Ok(init_marking_hash)
}