clm-kernel 0.0.16

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
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 = "60cb03ed477d1f315ce3237ea4c55efad9c3c590c79839f00471c3534c639ec3";
    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 mut upgrade_matched = false;
        if let Ok(conn) = crate::db::get_connection("agent_identities", clm_root_str) {
            let upgrade_hash: Option<String> = conn.query_row(
                "SELECT current_hash FROM handle_registry WHERE handle = 'upgrade:evaluator';",
                [],
                |row| row.get(0),
            ).ok();
            if let Some(target_hash) = upgrade_hash {
                let clean_target = crate::hash::strip_prefix(&target_hash);
                if actual_hash == clean_target {
                    upgrade_matched = true;
                }
            }
        }

        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> {
    let conn = crate::db::get_connection("agent_identities", clm_root)
        .map_err(|e| format!("Failed to get agent_identities DB connection: {}", e))?;

    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);

    // Bootstrap root DID if missing
    let root_exists: i64 = conn.query_row(
        "SELECT count(*) FROM card WHERE hash = ?",
        [&root_did],
        |row| row.get(0),
    ).unwrap_or(0);

    let now = crate::utils::now_iso8601();

    let yaml_content = format!(
        "agent:\n  did: \"{}\"\n  type: \"CA\"\n  metadata:\n    os: \"{}\"\n    name: \"Root CA Agent\"\n  capabilities:\n    - \"admin\"\n    - \"exec\"",
        root_did, host_os
    );

    if root_exists == 0 {
        if !quiet {
            eprintln!("[VERIFY] Bootstrapping root CA agent: {}", root_did);
        }
        conn.execute(
            "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
            rusqlite::params![root_did, yaml_content, now],
        ).map_err(|e| e.to_string())?;

        conn.execute(
            "INSERT OR IGNORE INTO handle_registry (handle, current_hash, updated_at) VALUES (?, ?, ?)",
            rusqlite::params!["agent:root", root_did, now],
        ).map_err(|e| e.to_string())?;
    }

    // Sync root CA agent to membroker (idempotent, only active in Zero-FS mode)
    let esc_yaml = yaml_content.replace('\'', "''");
    let esc_now = now.replace('\'', "''");
    crate::db::membroker_sync("agent_identities", &format!(
        "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES ('{}', '{}', '{}')",
        root_did, esc_yaml, esc_now
    ));
    crate::db::membroker_sync("agent_identities", &format!(
        "INSERT OR IGNORE INTO handle_registry (handle, current_hash, updated_at) VALUES ('{}', '{}', '{}')",
        "agent:root", root_did, esc_now
    ));

    // Bootstrap virtual DIDs if missing
    let virtual_dids = [
        "did:clm:evaluator",
        "did:clm:cache_manager",
        "did:clm:iam_agent",
        "did:clm:ci_pipeline",
    ];

    for v_did in &virtual_dids {
        let v_exists: i64 = conn.query_row(
            "SELECT count(*) FROM card WHERE hash = ?",
            [v_did],
            |row| row.get(0),
        ).unwrap_or(0);

        let v_yaml = format!(
            "agent:\n  did: \"{}\"\n  type: \"CA\"\n  metadata:\n    name: \"Virtual {} Agent\"\n  capabilities:\n    - \"admin\"\n    - \"exec\"",
            v_did, v_did
        );
        if v_exists == 0 {
            conn.execute(
                "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
                rusqlite::params![v_did, v_yaml, now],
            ).map_err(|e| e.to_string())?;
        }
        // Sync virtual DID to membroker
        let esc_v_yaml = v_yaml.replace('\'', "''");
        crate::db::membroker_sync("agent_identities", &format!(
            "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES ('{}', '{}', '{}')",
            v_did, esc_v_yaml, esc_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);
    }

    // Store the delegation VCard (public proof, no private key material)
    let (delegation_hash, delegation_gtime) = (crate::fs_utils::compute_content_hash(&delegation_vcard), crate::fs_utils::compute_g_time());
    conn.execute(
        "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
        rusqlite::params![delegation_hash, delegation_vcard, delegation_gtime],
    ).map_err(|e| e.to_string())?;

    // Sync delegation VCard to membroker
    let esc_dvc = delegation_vcard.replace('\'', "''");
    crate::db::membroker_sync("agent_identities", &format!(
        "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES ('{}', '{}', '{}')",
        delegation_hash, esc_dvc, delegation_gtime.replace('\'', "''")
    ));

    // 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);
    }

    // Query active agent card content
    let agent_card: Option<String> = conn.query_row(
        "SELECT content FROM card WHERE hash = ?",
        [&active_did],
        |row| row.get(0),
    ).ok();

    let agent_card_str = match agent_card {
        Some(c) => c,
        None => {
            // Fallback: check membroker for agent card (e.g. EOA agents registered by shell)
            if crate::db::is_membroker_backend() {
                if let Ok(mb_resp) = crate::db::membroker_send(
                    "agent_identities",
                    &format!("SELECT content FROM card WHERE hash = '{}';", active_did),
                ) {
                    if !mb_resp.is_empty() {
                        // Import into Rust DB for subsequent checks
                        let _ = conn.execute(
                            "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
                            rusqlite::params![&active_did, &mb_resp, &now],
                        );
                        mb_resp
                    } else {
                        return Err(format!("[VERIFY] ❌ Unauthorized agent: {} is not registered.", active_did));
                    }
                } else {
                    return Err(format!("[VERIFY] ❌ Unauthorized agent: {} is not registered.", active_did));
                }
            } else {
                return Err(format!("[VERIFY] ❌ Unauthorized agent: {} is not registered.", active_did));
            }
        }
    };

    // 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/scripts/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(())
}