clm-kernel 0.0.1

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use wasm_bindgen::prelude::*;

use crate::db_wasm;

fn sha256_hex(input: &str) -> String {
    crate::hash::raw_hash_string(input)
}

/// Initialize the WASM kernel: set up panic messages and any global state.
#[wasm_bindgen(start)]
pub fn start() {
    console_error_panic_hook::set_once();
}

/// Evaluate a CLM YAML file against an optional payload.
/// Mirrors `Commands::Evaluate` from the native CLI.
#[wasm_bindgen]
pub fn evaluate(clm_file: &str, payload: Option<String>) -> Result<i32, String> {
    // TODO(Sprint 139.1): wire to WASM-compiled evaluator once dependencies are ported.
    let _ = clm_file;
    let _ = payload;
    Err("evaluate() not yet implemented for WASM target".to_string())
}

/// Validate a value against a named type in the compiled type lattice.
#[wasm_bindgen]
pub fn validate_type(type_name: &str, value: &str) -> Result<(), String> {
    let lattice = crate::type_lattice::default_lattice();
    lattice.validate(type_name, value, 99).map_err(|e| e.to_string())
}

/// Validate a value using the O(1) compiled type lattice (Story 139.2.2).
/// Uses pre-compiled regexes and hash sets for faster verification.
#[wasm_bindgen]
pub fn validate_type_compiled(type_name: &str, value: &str) -> Result<(), String> {
    let lattice = crate::type_lattice::default_lattice();
    let compiled = crate::type_lattice::compiled_lattice();
    compiled.verify(type_name, value, 99, &lattice).map_err(|e| e.to_string())
}

/// Check if a value hash matches an allowed enum hash for a type (O(1) fast path).
#[wasm_bindgen]
pub fn verify_type_by_hash(type_name: &str, value: &str) -> bool {
    let compiled = crate::type_lattice::compiled_lattice();
    let hash = crate::type_lattice::hash_value(value);
    compiled.verify_by_hash(type_name, &hash)
}

/// Initialize the tri-database pillars in WASM linear memory.
#[wasm_bindgen]
pub fn init_tridb() -> Result<(), String> {
    db_wasm::init_tridb()
}

/// Load a YAML document into the `content_memory` pillar.
/// In the WASM stub the caller passes the document body as `file`.
#[wasm_bindgen]
pub fn yaml_load_once(file: &str) -> Result<String, String> {
    let content_hash = sha256_hex(file);
    db_wasm::execute(
        "content_memory",
        &format!(
            "INSERT INTO card (hash, content, kind) VALUES ('{}', '{}', 'yaml')",
            content_hash, file
        ),
    )?;
    Ok(content_hash)
}

/// Memorize an MCard document into the named pillar.
/// In the WASM stub the caller passes the document body as `mcard_file`.
#[wasm_bindgen]
pub fn memorize_mcard(mcard_file: &str, pillar: &str) -> Result<i32, String> {
    let content_hash = sha256_hex(mcard_file);
    db_wasm::execute(
        pillar,
        &format!(
            "INSERT INTO card (hash, content, kind) VALUES ('{}', '{}', 'mcard')",
            content_hash, mcard_file
        ),
    )?;
    Ok(1)
}

/// Run a Colored Petri Net topology file.
/// In the WASM stub the caller passes the topology YAML body as `topo_file`.
#[wasm_bindgen]
pub fn petri_run_net(topo_file: &str) -> Result<String, String> {
    crate::cpn_wasm::run_net(topo_file)
}

/// Compile an A-MCard to a target runtime.
#[wasm_bindgen]
pub fn compile(a_mcard_path: &str, target: &str) -> Result<String, String> {
    let _ = a_mcard_path;
    let _ = target;
    Err("compile() not yet implemented for WASM target".to_string())
}

/// Compose pre/post conditions for a given phase and exit code.
#[wasm_bindgen]
pub fn compose_conditions(clm_file: &str, phase: &str, exit_code: i32) -> Result<i32, String> {
    let _ = clm_file;
    let _ = phase;
    let _ = exit_code;
    Err("compose_conditions() not yet implemented for WASM target".to_string())
}

// ── OKF Adapter WASM bindings (Stage 6) ──

/// Mount an OKF directory from an in-memory file map (JSON).
/// Returns a JSON-serialized OkfMount.
#[wasm_bindgen]
pub fn okf_mount(mount_path: &str, mode: &str, files_json: &str) -> Result<String, String> {
    let mode = match mode {
        "before" => crate::okf_adapter::MountMode::Before,
        "after" => crate::okf_adapter::MountMode::After,
        "instead" => crate::okf_adapter::MountMode::Instead,
        _ => return Err(format!("invalid mount mode: {} (expected before/after/instead)", mode)),
    };
    let files: std::collections::HashMap<String, String> =
        serde_json::from_str(files_json).map_err(|e| format!("invalid files JSON: {}", e))?;
    let mount = crate::okf_adapter::OkfMount::mount(mount_path, mode, files)?;
    serde_json::to_string(&mount).map_err(|e| e.to_string())
}

/// Sync disk files to MCard handles. Returns JSON array of SyncEvent.
#[wasm_bindgen]
pub fn okf_sync_disk_to_mcard(mount_json: &str, files_json: &str) -> Result<String, String> {
    let mut mount: crate::okf_adapter::OkfMount =
        serde_json::from_str(mount_json).map_err(|e| format!("invalid mount JSON: {}", e))?;
    let files: std::collections::HashMap<String, String> =
        serde_json::from_str(files_json).map_err(|e| format!("invalid files JSON: {}", e))?;
    let events = mount.sync_disk_to_mcard(&files)?;
    serde_json::to_string(&events).map_err(|e| e.to_string())
}

/// Bidirectional sync. Returns JSON SyncReport.
#[wasm_bindgen]
pub fn okf_sync_bidirectional(mount_json: &str, files_json: &str) -> Result<String, String> {
    let mut mount: crate::okf_adapter::OkfMount =
        serde_json::from_str(mount_json).map_err(|e| format!("invalid mount JSON: {}", e))?;
    let files: std::collections::HashMap<String, String> =
        serde_json::from_str(files_json).map_err(|e| format!("invalid files JSON: {}", e))?;
    let report = mount.sync_bidirectional(&files)?;
    serde_json::to_string(&report).map_err(|e| e.to_string())
}