clm-kernel 0.0.11

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use crate::epiplexity::EpiplexityMetrics;
use super::types::{PlaceYaml, hash_string};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::Path;

pub fn write_marking_dir(
    marking_dir: &str,
    place_id: &str,
    tokens: i64,
    color: Option<&str>,
) {
    if marking_dir.is_empty() {
        return;
    }
    let _ = fs::create_dir_all(marking_dir);
    let p_path = Path::new(marking_dir).join(place_id);
    let _ = fs::write(&p_path, tokens.to_string());

    if let Some(c) = color
        && !c.is_empty() && c != "null" {
            let c_path = Path::new(marking_dir).join(format!("{}.color", place_id));
            let _ = fs::write(&c_path, c);
        }
}

pub fn serialize_pcard(
    conn: &rusqlite::Connection,
    operation: &str,
    runtime: &str,
    script_hash: &str,
    input_place_hashes: &[String],
    timestamp: &str,
    clm_root: &str,
) -> Result<String, String> {
    let mut pcard_yaml = format!(
        "pcard_token:\n  operation: \"{}\"\n  runtime: \"{}\"\n  script_hash: \"{}\"\n  timestamp: \"{}\"\n",
        operation, runtime, script_hash, timestamp
    );
    if input_place_hashes.is_empty() {
        pcard_yaml.push_str("  input_place_hashes: []");
    } else {
        pcard_yaml.push_str("  input_place_hashes:\n");
        for h in input_place_hashes {
            pcard_yaml.push_str(&format!("    - \"{}\"\n", h));
        }
        if pcard_yaml.ends_with('\n') {
            pcard_yaml.pop();
        }
    }

    let pcard_hash = hash_string(&pcard_yaml);
    let now = crate::utils::now_iso8601();
    // The stored coordinate must name the algorithm that produced the digest (charter L2).
    let g_time = crate::fs_utils::compute_g_time();

    conn.execute(
        "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
        rusqlite::params![pcard_hash, pcard_yaml, g_time],
    )
    .map_err(|e| e.to_string())?;

    // ORC-24: the grammar names the KIND, and `pcard:program` is the kind a PCard body has
    // (`urn:mcard:<sector>:<kind>[:<subject>]`). This wrote `pcard:{operation}:{hash}` — the
    // last legacy handle form in the kernel, and the reason the hub's declared consumption of
    // `urn:pcard:*` had no tape to satisfy it. A handle outside the grammar is a kind
    // nothing can resolve.
    let handle_name = format!("urn:pcard:program:{}", pcard_hash);
    conn.execute(
        "INSERT OR IGNORE INTO handle_registry (handle, current_hash, updated_at) VALUES (?, ?, ?)",
        rusqlite::params![handle_name, pcard_hash, now],
    )
    .map_err(|e| e.to_string())?;

    crate::cache::setter_mcard_cache_handle(&handle_name, &pcard_hash);
    crate::cache::setter_mcard_cache(&pcard_hash, &pcard_yaml);

    let input_place_hashes_json = serde_json::Value::Array(
        input_place_hashes
            .iter()
            .map(|h| serde_json::Value::String(h.clone()))
            .collect(),
    )
    .to_string();

    let kv_args = vec![
        format!("pcard_hash={}", pcard_hash),
        format!("operation={}", operation),
        format!("runtime={}", runtime),
        format!("script_hash={}", script_hash),
        format!("input_place_hashes={}", input_place_hashes_json),
    ];
    let _ = crate::jsonl::jsonl_emit("pcard_serialized", kv_args, clm_root);

    Ok(pcard_hash)
}

pub fn vcard_gate(
    conn: &rusqlite::Connection,
    mode: &str,
    pcard_hash: &str,
    triggering_dispatch_hash_or_exit_code: &str,
    input_place_hashes_or_downstream_targets: &[String],
    timestamp: &str,
    agent_did: &str,
    sponsor_did: &str,
    delegation_proof: &str,
    execution_locale_hash: &str,
    transport_ref: &str,
    clm_root: &str,
    epiplexity_metrics: Option<&EpiplexityMetrics>,
    threshold_signature: Option<&str>,
    guardian_dids: Option<&[String]>,
) -> Result<String, String> {
    let mut vcard_yaml;
    
    
    let mut gate_result = "pass";
    let mut failure_reason = String::new();

    let (handle_prefix, event_type) = if mode == "callback" {
        let triggering_dispatch_hash = triggering_dispatch_hash_or_exit_code;
        vcard_yaml = format!(
            "vcard_token:\n  gate_type: \"callback\"\n  result: \"{}\"\n  pcard_hash: \"{}\"\n  triggering_dispatch_hash: \"{}\"\n  timestamp: \"{}\"\n  agent_did: \"{}\"\n  sponsor_did: \"{}\"\n  delegation_proof: \"{}\"\n  execution_locale_hash: \"{}\"\n  transport_ref: \"{}\"",
            gate_result, pcard_hash, triggering_dispatch_hash, timestamp, agent_did, sponsor_did, delegation_proof, execution_locale_hash, transport_ref
        );
        if !input_place_hashes_or_downstream_targets.is_empty() {
            vcard_yaml.push_str("\n  input_place_hashes:\n");
            for h in input_place_hashes_or_downstream_targets {
                vcard_yaml.push_str(&format!("    - \"{}\"\n", h));
            }
            if vcard_yaml.ends_with('\n') {
                vcard_yaml.pop();
            }
        }
        ("vcard:callback", "vcard_callback")
    } else {
        let exec_exit_code = triggering_dispatch_hash_or_exit_code;
        if exec_exit_code != "0" {
            gate_result = "fail";
            failure_reason = format!("PCard execution failed with exit code {}", exec_exit_code);
        }
        vcard_yaml = format!(
            "vcard_token:\n  gate_type: \"dispatch\"\n  result: \"{}\"\n  pcard_hash: \"{}\"\n  timestamp: \"{}\"\n  agent_did: \"{}\"\n  sponsor_did: \"{}\"\n  delegation_proof: \"{}\"\n  execution_locale_hash: \"{}\"\n  transport_ref: \"{}\"",
            gate_result, pcard_hash, timestamp, agent_did, sponsor_did, delegation_proof, execution_locale_hash, transport_ref
        );
        if gate_result == "fail" {
            vcard_yaml.push_str(&format!("\n  failure_reason: \"{}\"", failure_reason));
        }
        if input_place_hashes_or_downstream_targets.is_empty() {
            vcard_yaml.push_str("\n  downstream_callback_targets: []");
        } else {
            vcard_yaml.push_str("\n  downstream_callback_targets:\n");
            for t in input_place_hashes_or_downstream_targets {
                vcard_yaml.push_str(&format!("    - \"{}\"\n", t));
            }
            if vcard_yaml.ends_with('\n') {
                vcard_yaml.pop();
            }
        }
        if let Some(metrics) = epiplexity_metrics {
            vcard_yaml.push_str(&format!(
                "\n  epiplexity_metrics:\n    s_t: {}\n    h_t: {}\n    l: {}\n    delta_l: {}",
                metrics.s_t, metrics.h_t, metrics.l, metrics.delta_l
            ));
        }
        if let Some(sig) = threshold_signature {
            vcard_yaml.push_str(&format!("\n  threshold_signature: \"{}\"", sig));
        }
        if let Some(dids) = guardian_dids
            && !dids.is_empty() {
                vcard_yaml.push_str("\n  guardian_dids:");
                for did in dids {
                    vcard_yaml.push_str(&format!("\n    - \"{}\"", did));
                }
            }
        ("vcard:dispatch", "vcard_dispatch")
    };

    let vcard_hash = hash_string(&vcard_yaml);
    let g_time = crate::fs_utils::compute_g_time();
    conn.execute(
        "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
        rusqlite::params![vcard_hash, vcard_yaml, g_time],
    )
    .map_err(|e| e.to_string())?;

    let handle_name = format!("{}:{}", handle_prefix, vcard_hash);
    let now = crate::utils::now_iso8601();
    conn.execute(
        "INSERT OR IGNORE INTO handle_registry (handle, current_hash, updated_at) VALUES (?, ?, ?)",
        rusqlite::params![handle_name, vcard_hash, now],
    )
    .map_err(|e| e.to_string())?;

    let kv_args = vec![
        format!("vcard_hash={}", vcard_hash),
        format!("gate_type={}", mode),
        format!("result={}", gate_result),
        format!("pcard_hash={}", pcard_hash),
    ];
    let _ = crate::jsonl::jsonl_emit(event_type, kv_args, clm_root);

    Ok(vcard_hash)
}

pub fn emit_state_token(
    conn: &rusqlite::Connection,
    pcard_hash: &str,
    vcard_dispatch_hash: &str,
    content_input: &str,
    clm_root: &str,
) -> Result<String, String> {
    let timestamp = crate::utils::now_iso8601();
    let agent_did = env::var("CLM_AGENT_DID")
        .unwrap_or_else(|_| "did:clm:bootstrap".to_string());

    let content_snapshot = if Path::new(content_input).exists() {
        let metadata = fs::metadata(content_input).map_err(|e| e.to_string())?;
        let file_size = metadata.len();
        if file_size > 4096 {
            let hash = crate::fs_utils::compute_stripped_file_hash(Path::new(content_input))
                .map_err(|e| e.to_string())?;
            crate::hash::prefixed(&hash)
        } else {
            fs::read_to_string(content_input).map_err(|e| e.to_string())?
        }
    } else {
        content_input.to_string()
    };

    let escaped_snapshot = content_snapshot.replace('"', "\\\"");
    let state_yaml = format!(
        "state_token:\n  token_type: \"state\"\n  producer_pcard_hash: \"{}\"\n  vcard_dispatch_hash: \"{}\"\n  timestamp: \"{}\"\n  agent_did: \"{}\"\n  content_snapshot: \"{}\"",
        pcard_hash, vcard_dispatch_hash, timestamp, agent_did, escaped_snapshot
    );

    let state_hash = hash_string(&state_yaml);
    let g_time = crate::fs_utils::compute_g_time();
    conn.execute(
        "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
        rusqlite::params![state_hash, state_yaml, g_time],
    )
    .map_err(|e| e.to_string())?;

    let handle_name = format!("mcard:state:{}", state_hash);
    let now = crate::utils::now_iso8601();
    conn.execute(
        "INSERT OR IGNORE INTO handle_registry (handle, current_hash, updated_at) VALUES (?, ?, ?)",
        rusqlite::params![handle_name, state_hash, now],
    )
    .map_err(|e| e.to_string())?;

    // Sync to membroker if active
    if crate::db::is_membroker_backend() {
        let esc_hash = state_hash.replace('\'', "''");
        let esc_yaml = state_yaml.replace('\'', "''");
        let esc_ts = timestamp.replace('\'', "''");
        let esc_handle = handle_name.replace('\'', "''");
        let esc_now = now.replace('\'', "''");
        crate::db::membroker_sync("execution_log", &format!(
            "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES ('{}', '{}', '{}')",
            esc_hash, esc_yaml, esc_ts
        ));
        crate::db::membroker_sync("execution_log", &format!(
            "INSERT OR IGNORE INTO handle_registry (handle, current_hash, updated_at) VALUES ('{}', '{}', '{}')",
            esc_handle, esc_hash, esc_now
        ));
    }

    crate::cache::setter_mcard_cache_handle(&handle_name, &state_hash);
    crate::cache::setter_mcard_cache(&state_hash, &state_yaml);

    let kv_args = vec![
        format!("state_hash={}", state_hash),
        format!("producer_pcard_hash={}", pcard_hash),
        format!("vcard_dispatch_hash={}", vcard_dispatch_hash),
    ];
    let _ = crate::jsonl::jsonl_emit("state_emitted", kv_args, clm_root);

    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 unix_ts = chrono::Utc::now().timestamp();
        let log_file = logs_dir.join(format!("state_{}_{}.yaml", unix_ts, &state_hash[0..8]));
        let _ = fs::write(log_file, &state_yaml);
    }

    Ok(state_hash)
}

pub fn emit_state_failed(
    pcard_hash: &str,
    exit_code: i64,
    reason: &str,
    clm_root: &str,
) -> Result<(), String> {
    let kv_args = vec![
        format!("pcard_hash={}", pcard_hash),
        format!("exit_code={}", exit_code),
        format!("reason={}", reason),
    ];
    let _ = crate::jsonl::jsonl_emit("state_failed", kv_args, clm_root);
    Ok(())
}

pub fn build_marking_json(
    topology_hash: &str,
    places: &[PlaceYaml],
    place_markings: &HashMap<String, i64>,
    place_colors: &HashMap<String, String>,
    sponsor_did: &str,
    firer_did: &str,
    parent_hash: &str,
    fired_transition: Option<&str>,
) -> serde_json::Value {
    let mut markings = serde_json::Map::new();
    let mut colors = serde_json::Map::new();
    for p in places {
        let val = place_markings.get(&p.id).cloned().unwrap_or(0);
        markings.insert(p.id.clone(), serde_json::Value::Number(val.into()));
        if let Some(col) = place_colors.get(&p.id)
            && !col.is_empty() {
                colors.insert(p.id.clone(), serde_json::Value::String(col.clone()));
            }
    }

    let mut obj = serde_json::Map::new();
    obj.insert(
        "@type".to_string(),
        serde_json::Value::String("PetriNetMarking".to_string()),
    );
    obj.insert(
        "topology_hash".to_string(),
        serde_json::Value::String(crate::hash::prefixed(topology_hash)),
    );
    obj.insert("markings".to_string(), serde_json::Value::Object(markings));
    obj.insert("colors".to_string(), serde_json::Value::Object(colors));

    if !sponsor_did.is_empty() {
        obj.insert(
            "sponsor_did".to_string(),
            serde_json::Value::String(sponsor_did.to_string()),
        );
    }
    obj.insert(
        "fired_by".to_string(),
        serde_json::Value::String(firer_did.to_string()),
    );
    if !parent_hash.is_empty() {
        obj.insert(
            "parent_marking_hash".to_string(),
            serde_json::Value::String(parent_hash.to_string()),
        );
    }
    if let Some(ft) = fired_transition {
        obj.insert(
            "fired_transition".to_string(),
            serde_json::Value::String(ft.to_string()),
        );
    }

    serde_json::Value::Object(obj)
}