clm-kernel 0.0.6

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use serde_json::Value;
use std::env;
use std::fs;
use std::path::Path;
use crate::db::handle_register_batch;
use crate::fs_utils::compute_sha256_hex;

pub fn jsonl_emit(
    event_type: &str,
    kv_args: Vec<String>,
    clm_root: &str,
) -> Result<String, String> {
    let mut map = serde_json::Map::new();
    map.insert("event".to_string(), Value::String(event_type.to_string()));

    let timestamp = crate::utils::now_iso8601();
    map.insert("timestamp".to_string(), Value::String(timestamp));

    let agent_did = env::var("CLM_AGENT_DID")
        .unwrap_or_else(|_| "did:clm:bootstrap".to_string());
    map.insert("agent_did".to_string(), Value::String(agent_did));

    for kv in kv_args {
        if let Some(pos) = kv.find('=') {
            let key = &kv[..pos];
            let val_str = &kv[pos + 1..];

            let val = if val_str == "null" {
                Value::Null
            } else if val_str.starts_with('[') && val_str.ends_with(']') {
                if let Ok(parsed_arr) = serde_json::from_str::<Value>(val_str) {
                    parsed_arr
                } else {
                    Value::String(val_str.to_string())
                }
            } else if val_str.starts_with('{') && val_str.ends_with('}') {
                if let Ok(parsed_obj) = serde_json::from_str::<Value>(val_str) {
                    parsed_obj
                } else {
                    Value::String(val_str.to_string())
                }
            } else if let Ok(num) = val_str.parse::<i64>() {
                Value::Number(num.into())
            } else {
                Value::String(val_str.to_string())
            };

            map.insert(key.to_string(), val);
        }
    }

    if !map.contains_key("seq") {
        static EVENT_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
        let seq = EVENT_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        map.insert("seq".to_string(), Value::Number(seq.into()));
    }

    let json_line = Value::Object(map).to_string();
    let zero_fs = crate::utils::is_zero_fs();

    // 1. File write
    let events_dir = Path::new(clm_root).join("data").join("events");
    let log_file_str = env::var("CLM_EVENT_LOG_PATH")
        .unwrap_or_else(|_| events_dir.join("token_events.jsonl").to_string_lossy().to_string());
    let log_file = Path::new(&log_file_str);

    if !zero_fs || log_file_str.contains("/tmp") {
        if let Some(parent) = log_file.parent() {
            let _ = fs::create_dir_all(parent);
        }
        let mut open_opts = fs::OpenOptions::new();
        open_opts.create(true).append(true);
        if let Ok(mut file) = open_opts.open(log_file) {
            use std::io::Write;
            let _ = writeln!(file, "{}", json_line);
        }
    }

    // 2. DB write if CLM_RUN_ID is set.
    //
    // ONE EVENT, ONE CARD — and the SEQUENCE lives in `handle_history`, which is what a
    // revision record is for (`ORC-29`: `handle_history` IS the revision record).
    //
    // THIS PREVIOUSLY ACCUMULATED. It read the whole log back, concatenated one line, and
    // registered the WHOLE THING as a new card. `card` is content-addressed and written
    // `INSERT OR IGNORE`, so every distinct accumulation became a NEW ROW: N events, N cards,
    // averaging N/2 lines — O(n²) bytes. Measured 2026-10-08: 31,075 events cost 114 GB in
    // the tape against 20.9 MB in the append-only file beside it, 5,469×, from this block.
    // A log is a SEQUENCE OF EVENTS, not a sequence of snapshots of one.
    //
    // The handle NAMES the kind (`INV-TAPE-03`): one handle per (run, event type), so the
    // number of events of a type is the length of that handle's history.
    let run_id_res = env::var("CLM_RUN_ID");
    if let Ok(run_id) = run_id_res
        && !run_id.is_empty() {
            let handle_name = format!("run:{}:event:{}", run_id, event_type);
            let new_hash = compute_sha256_hex(json_line.as_bytes());
            if let Err(e) = handle_register_batch("execution_log", clm_root, &handle_name, &new_hash, &json_line) {
                eprintln!("[RUST JSONL_EMIT] ❌ Failed to register event in DB: {}", e);
            }
        }

    // println!("{}", json_line);
    Ok(json_line)
}