clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use crate::layer0::vocabulary_identities::{DID_PKC_CA};
use std::fs;
use std::path::Path;
use crate::fs_utils::compute_sha256_hex;

pub fn verify_integrity(clm_root: &Path) -> Result<(), String> {
    let self_clm = clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/clmEval.yaml");
    if !self_clm.exists() {
        return Err(format!("clmEval.yaml not found at {:?}", self_clm));
    }
    
    let content = fs::read(&self_clm)
        .map_err(|e| format!("Failed to read clmEval.yaml: {}", e))?;
    
    // tr -d '\r' behavior
    let normalized: Vec<u8> = content.into_iter().filter(|&b| b != b'\r').collect();
    let actual_sha256 = compute_sha256_hex(&normalized);
    let actual_blake3 = crate::hash::raw_hash_bytes(&normalized);
    let expected_sha256 = "db32718264f3689faef4b0844e9744d8cf66001850ace5df756449ee786ed728";
    let expected_blake3 = "aa400b8497ddef57051e1a8dee8fddb07d48e5af0575dfaa0bd19ec11247be26";
    
    let actual_hash = actual_sha256.clone();
    let expected_hash = expected_sha256;
    
    if actual_sha256 != expected_sha256 && actual_blake3 != expected_blake3 {
        let clm_root_str = clm_root.to_str().unwrap_or("");
        let conn = crate::db::get_connection(crate::layer0::vocabulary_env::PILLAR_AGENT_IDENTITIES, clm_root_str).map_err(|e| e.to_string())?;
        let upgrade_matched = crate::layer2::record_store::read_handle_record(&conn, "upgrade:evaluator")
            .map_err(|e| e.to_string())?.is_some_and(|record| record.content == normalized);

        if !upgrade_matched {
            let err_msg = format!(
                "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n\
                 ┃  INTEGRITY FAILURE: clmEval.yaml content has changed    ┃\n\
                 ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n\
                  Expected: {}\n\
                  Actual:   {}\n\
                  File:     {:?}\n",
                expected_hash, actual_hash, self_clm
            );
            return Err(err_msg);
        }
    }
    Ok(())
}

pub fn bootstrap_and_authorize_agent(clm_root: &str, quiet: bool) -> Result<(), String> {
    if crate::db::is_membroker_backend() {
        return Err("agent bootstrap requires verified remote record import support".into());
    }
    let conn = crate::db::get_connection(crate::layer0::vocabulary_env::PILLAR_AGENT_IDENTITIES, clm_root).map_err(|e| e.to_string())?;
    let host_os = match std::env::consts::OS {
        "linux" => "linux",
        "macos" => "darwin",
        "windows" => "windows",
        _ => "unknown",
    };

    let root_did = format!("{DID_PKC_CA}{}:root-agent", host_os);

    let now = crate::utils::now_iso8601();
    let agents = [root_did.as_str(),
        crate::layer0::vocabulary_identities::DID_CLM_EVALUATOR,
        crate::layer0::vocabulary_identities::DID_CLM_CACHE_MANAGER,
        crate::layer0::vocabulary_identities::DID_CLM_IAM_AGENT,
        crate::layer0::vocabulary_identities::DID_CLM_CI_PIPELINE];
    for did in agents {
        if crate::layer2::record_store::read_handle_record(&conn, did).map_err(|e| e.to_string())?.is_none() {
            let content = format!("agent:\n  did: \"{}\"\n  type: CA\n  capabilities: [admin, exec]\n", did);
            let record = crate::layer0::mcard_record::MCardRecord::create(content.as_bytes(), None)?;
            crate::layer2::record_store::insert_record(&conn, &record).map_err(|e| e.to_string())?;
            crate::tape::register_handle(&conn, did, &record.hash, &now)?;
            if did == root_did { crate::tape::register_handle(&conn, "agent:root", &record.hash, &now)?; }
        }
    }

    // Generate ephemeral CA keypair for this session.
    // The key lives only in volatile memory and is zeroized on drop.
    let mut ephemeral_ca = crate::tss::EphemeralCA::new(vec!["admin".to_string(), "exec".to_string()]);
    let delegation_vcard = ephemeral_ca.issue_delegation()
        .map_err(|e| format!("[VERIFY] Failed to issue delegation: {}", e))?;

    if !quiet {
        eprintln!("[VERIFY] Ephemeral CA generated: {}", ephemeral_ca.did);
    }

    let delegation = crate::layer0::mcard_record::MCardRecord::create(delegation_vcard.as_bytes(), None)?;
    crate::layer2::record_store::insert_record(&conn, &delegation).map_err(|e| e.to_string())?;

    // Resolve active agent DID
    let active_did = crate::cross_cutting::context::CLMContext::get_scoped_or_env("ACTIVE_AGENT_DID")
        .unwrap_or_else(|| root_did.clone());

    if !quiet {
        eprintln!("[VERIFY] Active Agent DID: {}", active_did);
    }

    let agent_card_str = crate::layer2::record_store::read_handle_text(&conn, &active_did)
        .map_err(|e| e.to_string())?.ok_or_else(|| format!("Unauthorized agent: {active_did} is not registered"))?;

    // Parse yaml to check capabilities
    let agent_val: serde_yaml::Value = serde_yaml::from_str(&agent_card_str)
        .map_err(|e| format!("Failed to parse agent card YAML: {}", e))?;

    let capabilities = agent_val
        .get("agent")
        .and_then(|a| a.get("capabilities"))
        .and_then(|c| c.as_sequence());

    let mut has_exec = false;
    if let Some(caps) = capabilities {
        for cap in caps {
            if let Some(s) = cap.as_str()
                && (s == "exec" || s == "admin") {
                    has_exec = true;
                    break;
                }
        }
    }

    if !has_exec {
        return Err(format!("[VERIFY] ❌ Agent {} lacks required 'exec' or 'admin' capability.", active_did));
    }

    if !quiet {
        eprintln!("[VERIFY] ✅ Agent authorized successfully (ephemeral CA: {})", ephemeral_ca.did);
    }

    // EphemeralCA is dropped here — signing key is zeroized
    drop(ephemeral_ca);

    Ok(())
}

pub fn verify_precondition_internal(clm_root: &Path, _clm_file: &str, quiet: bool) -> Result<(), String> {
    // 1. Integrity Check
    let self_clm = clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/clmEval.yaml");
    let stub = clm_root.join("kernel/launchers/clmEval");
    
    let yaml_hash = if self_clm.exists() {
        let content = fs::read(&self_clm)
            .map_err(|e| format!("Failed to read clmEval.yaml: {}", e))?;
        let normalized: Vec<u8> = content.into_iter().filter(|&b| b != b'\r').collect();
        compute_sha256_hex(&normalized)
    } else {
        "unknown".to_string()
    };
    
    let stub_hash = if stub.exists() {
        let content = fs::read(&stub)
            .map_err(|e| format!("Failed to read stub: {}", e))?;
        compute_sha256_hex(&content)
    } else {
        "unknown".to_string()
    };

    if !quiet {
        eprintln!("[VERIFY] ✅ Bidirectional integrity verified");
        eprintln!("[VERIFY]   YAML hash: {}", yaml_hash);
        eprintln!("[VERIFY]   Stub hash: {}", stub_hash);
    }

    // 2. Bootstrap & Authorize Agent
    let clm_root_str = clm_root.to_str().unwrap_or("");
    bootstrap_and_authorize_agent(clm_root_str, quiet)?;

    Ok(())
}

#[allow(dead_code)]
pub fn verify_tool_signature(tool_path: &Path, expected_hash: &str) -> Result<(), String> {
    if !tool_path.exists() {
        return Err(format!("Tool implementation not found: {:?}", tool_path));
    }
    
    let content = fs::read(tool_path)
        .map_err(|e| format!("Failed to read tool file: {}", e))?;
    
    let normalized: Vec<u8> = content.into_iter().filter(|&b| b != b'\r').collect();
    let actual_hash = compute_sha256_hex(&normalized);
    
    if actual_hash != expected_hash {
        let err_msg = format!(
            "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n\
             ┃  SECURITY FAILURE: Tool implementation has changed      ┃\n\
             ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n\
              Expected: {}\n\
              Actual:   {}\n\
              File:     {:?}\n",
            expected_hash, actual_hash, tool_path
        );
        return Err(err_msg);
    }
    
    Ok(())
}