clm-kernel 0.0.12

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use std::fs;
use clap::Subcommand;
use std::path::Path;

pub fn compile_evaluator_cache(_clm_root: &Path, _quiet: bool) -> Result<(), String> {
    // Legacy shell evaluator cache compilation is retired in Sprint 483/487 (INV-483 / INV-487).
    // Native Rust, Python, and JS evaluators execute in-process without sourcing evaluator_cache.
    Ok(())
}

pub fn extract_bootstrap_script(clm_root: &Path) -> Result<String, 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_to_string(&self_clm)
        .map_err(|e| format!("Failed to read clmEval.yaml: {}", e))?;
    
    let data: serde_yaml::Value = serde_yaml::from_str(&content)
        .map_err(|e| format!("Failed to parse clmEval.yaml: {}", e))?;
    
    let clm_data = data.get("clm").unwrap_or(&data);
    let concrete_impl = clm_data.get("concrete_impl").ok_or("No concrete_impl in clmEval.yaml")?;
    let process = concrete_impl.get("process").ok_or("No process in clmEval.yaml")?;
    
    let script = match process {
        serde_yaml::Value::Mapping(map) => {
            map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string())
        }
        serde_yaml::Value::Sequence(seq) => {
            let mut s = None;
            for val in seq {
                if let serde_yaml::Value::Mapping(map) = val
                    && map.get("type").and_then(|v| v.as_str()) == Some("shell") {
                        s = map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string());
                        break;
                    }
            }
            s
        }
        _ => None,
    };
    
    script.ok_or_else(|| "Could not extract shell bootstrap script from clmEval.yaml".to_string())
}

#[derive(Subcommand, Debug, Clone)]
pub enum ToolCommands {
    #[command(name = "run")]
    Run {
        tool_handle: String,
        #[arg(long)]
        source_dir: Option<String>,
        #[arg(num_args = 0..)]
        args: Vec<String>,
    },
    #[command(name = "document")]
    Document,
}

#[derive(Subcommand, Debug, Clone)]
pub enum EvolveCommands {
    #[command(name = "status")]
    Status {
        #[arg(long)]
        timeslot: Option<String>,
    },
    #[command(name = "step")]
    Step,
    #[command(name = "report")]
    Report,
}

pub fn run_tool_dispatcher(cmd: ToolCommands, clm_root: &str) -> Result<String, String> {
    match cmd {
        ToolCommands::Run { tool_handle, source_dir, args } => {
            let clm_path = Path::new(clm_root);
            
            // Map tool handle to yaml file, e.g., tool:foo -> tool_foo.yaml
            let yaml_filename = format!("{}.yaml", tool_handle.replace(":", "_"));
            let yaml_path = clm_path.join("types/governance").join(&yaml_filename);
            
            if !yaml_path.exists() {
                return Err(format!("[ERROR] Tool spec not found: {:?}", yaml_path));
            }
            
            let yaml_content = std::fs::read_to_string(&yaml_path).map_err(|e| e.to_string())?;
            let spec: serde_yaml::Value = serde_yaml::from_str(&yaml_content).map_err(|e| e.to_string())?;
            
            let script_val = spec.get("clm")
                .and_then(|v| v.get("concrete_impl"))
                .and_then(|v| v.get("process"))
                .and_then(|v| v.get("script"))
                .and_then(|v| v.as_str());
                
            if let Some(script_rel_path) = script_val {
                let script_path = clm_path.join(script_rel_path);
                if !script_path.exists() {
                    return Err(format!("[ERROR] Script not found: {:?}", script_path));
                }
                
                let mut cmd = std::process::Command::new("python3");
                cmd.arg(&script_path);
                
                if let Some(dir) = source_dir {
                    cmd.arg("--source_dir");
                    cmd.arg(&dir);
                }
                for arg in args {
                    cmd.arg(&arg);
                }
                
                let res = cmd.output().map_err(|e| e.to_string())?;
                let mut out = format!("[TOOL DISPATCHER] Executed tool: {}\n", tool_handle);
                out.push_str(&String::from_utf8_lossy(&res.stdout));
                if !res.stderr.is_empty() {
                    out.push_str("\n[STDERR]\n");
                    out.push_str(&String::from_utf8_lossy(&res.stderr));
                }
                Ok(out)
            } else {
                Err(format!("[ERROR] Invalid tool spec in {:?}: missing clm.concrete_impl.process.script", yaml_path))
            }
        }
        ToolCommands::Document => {
            Ok("# CLM Executable Tools Registry\n\n- `tool:layer_boundary_checker`: Verifies layer boundaries across the Rust workspace.\n- `tool:rust_interpreter_reporter`: Analyzes the Rust CLM Interpreter and generates an architecture report.\n".to_string())
        }
    }
}

pub fn run_evolve_dispatcher(cmd: EvolveCommands, clm_root: &str) -> Result<String, String> {
    match cmd {
        EvolveCommands::Status { timeslot } => {
            let slot = timeslot.unwrap_or_else(|| {
                let now = chrono::Local::now();
                let iso_week = chrono::Datelike::iso_week(&now);
                format!("{:04}_w{:02}", iso_week.year(), iso_week.week())
            });
            let db_name = format!("pkc_evol_{}.db", slot);
            
            let count = if let Ok(conn) = crate::db::get_connection("evolution", clm_root) {
                conn.query_row(
                    "SELECT COUNT(*) FROM handle_registry WHERE handle LIKE 'run:evolution:transition:%'",
                    [],
                    |row| row.get::<_, i64>(0)
                ).unwrap_or(0)
            } else {
                0
            };
            
            Ok(format!(
                "[EVOLVE STATUS] Active Time-Slot: {}\nDatabase: {}\nVerified Transitions: {}\nStatus: Ready for next step.\n",
                slot, db_name, count
            ))
        }
        EvolveCommands::Step => {
            let gov_dir = Path::new(clm_root).join("types/governance");
            if !gov_dir.exists() {
                return Err(format!("Governance directory not found: {:?}", gov_dir));
            }
            
            let mut executed_count = 0;
            let mut failed_count = 0;
            let mut skipped_count = 0;
            
            for entry in fs::read_dir(&gov_dir).map_err(|e| e.to_string())? {
                let entry = entry.map_err(|e| e.to_string())?;
                let path = entry.path();
                let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
                
                if file_name.starts_with("b_mcard_") && file_name.ends_with(".yaml") {
                    let b_mcard_name = file_name.trim_start_matches("b_mcard_").trim_end_matches(".yaml");
                    let handle_name = format!("run:evolution:transition:{}", b_mcard_name);
                    
                    if let Ok(Some(_)) = crate::db::resolve_handle_hash("evolution", clm_root, &handle_name) {
                        skipped_count += 1;
                        continue;
                    }
                    
                    let path_str = path.to_string_lossy().to_string();
                    let val = match crate::parser::parse_manifest(&path_str) {
                        Ok(v) => v,
                        Err(e) => {
                            failed_count += 1;
                            println!("[EVOLVE STEP] Failed to parse B-MCard {:?}: {}", path, e);
                            continue;
                        }
                    };
                    
                    let polyglot_cases = val.pointer("/clm/balanced_exp/polyglot_cases")
                        .and_then(|v| v.as_array());
                        
                    if let Some(cases) = polyglot_cases {
                        let mut b_mcard_ok = true;
                        println!("[EVOLVE STEP] Verifying transition '{}'...", b_mcard_name);
                        
                        for case in cases {
                            let name = case.get("name").and_then(|v| v.as_str()).unwrap_or("unnamed");
                            let assertions = case.get("then").and_then(|v| v.as_array());
                            
                            if let Some(asserts) = assertions {
                                for assertion in asserts {
                                    if let Some(cmd_str) = assertion.get("assert_success").and_then(|v| v.as_str()) {
                                        let mut command = std::process::Command::new("sh");
                                        command.arg("-c").arg(cmd_str);
                                        let output = match command.output() {
                                            Ok(out) => out,
                                            Err(e) => {
                                                b_mcard_ok = false;
                                                println!("  ❌ Case '{}' failed: could not execute: {}", name, e);
                                                break;
                                            }
                                        };
                                        if !output.status.success() {
                                            b_mcard_ok = false;
                                            println!("  ❌ Case '{}' failed (exit code = {}).", name, output.status.code().unwrap_or(1));
                                            let stderr = String::from_utf8_lossy(&output.stderr);
                                            if !stderr.is_empty() {
                                                println!("     Stderr: {}", stderr.trim());
                                            }
                                            break;
                                        } else {
                                            println!("  ✅ Case '{}' assertion passed.", name);
                                        }
                                    }
                                }
                            }
                            if !b_mcard_ok {
                                break;
                            }
                        }
                        
                        if b_mcard_ok {
                            let g_time = crate::fs_utils::compute_g_time();
                            let sponsor_did = std::env::var("ACTIVE_AGENT_DID").unwrap_or_else(|_| "did:pkc:ca:darwin:root-agent".to_string());
                            let pre_hash = val.pointer("/clm/abstract_spec/invariants/preconditions")
                                .and_then(|v| v.as_array())
                                .map(|a| crate::fs_utils::compute_content_hash(&format!("{:?}", a)))
                                .unwrap_or_default();
                            let post_hash = val.pointer("/clm/abstract_spec/invariants/postconditions")
                                .and_then(|v| v.as_array())
                                .map(|a| crate::fs_utils::compute_content_hash(&format!("{:?}", a)))
                                .unwrap_or_default();
                                
                            let vcard_content = format!(
                                "vcard:\n  g_time: \"{}\"\n  transition: \"{}\"\n  status: \"VERIFIED\"\n  pre_hash: \"{}\"\n  post_hash: \"{}\"\n  sponsor_did: \"{}\"\n",
                                g_time, b_mcard_name, pre_hash, post_hash, sponsor_did
                            );
                            let content_hash = crate::fs_utils::compute_content_hash(&vcard_content);
                            
                            if let Err(e) = crate::db::handle_register_batch(
                                "evolution",
                                clm_root,
                                &handle_name,
                                &crate::hash::prefixed(&content_hash),
                                &vcard_content,
                            ) {
                                failed_count += 1;
                                println!("[EVOLVE STEP] Failed to register transition handle: {}", e);
                            } else {
                                executed_count += 1;
                                println!("[EVOLVE STEP] Verified and registered transition '{}'.", b_mcard_name);
                            }
                        } else {
                            failed_count += 1;
                        }
                    }
                }
            }
            
            Ok(format!(
                "[EVOLVE STEP] Completed. Executed: {}, Skipped: {}, Failed: {}\n",
                executed_count, skipped_count, failed_count
            ))
        }
        EvolveCommands::Report => {
            generate_evolution_audit_report(clm_root)
        }
    }
}

pub fn generate_evolution_audit_report(clm_root: &str) -> Result<String, String> {
    let mut table_rows = Vec::new();
    
    if let Ok(conn) = crate::db::get_connection("evolution", clm_root) {
        let mut stmt = match conn.prepare(
            "SELECT hr.handle, hr.current_hash, hr.updated_at, c.content \
             FROM handle_registry hr \
             JOIN card c ON hr.current_hash = c.hash \
             WHERE hr.handle LIKE 'run:evolution:transition:%' \
             ORDER BY hr.updated_at ASC;"
        ) {
            Ok(s) => s,
            Err(e) => return Err(e.to_string()),
        };
        
        let mut rows = match stmt.query([]) {
            Ok(r) => r,
            Err(e) => return Err(e.to_string()),
        };
        
        while let Ok(Some(row)) = rows.next() {
            let handle: String = row.get(0).unwrap_or_default();
            let _current_hash: String = row.get(1).unwrap_or_default();
            let updated_at: String = row.get(2).unwrap_or_default();
            let content: String = row.get(3).unwrap_or_default();
            
            let mut transition = handle.trim_start_matches("run:evolution:transition:").to_string();
            let mut status = "UNKNOWN".to_string();
            let mut sponsor_did = "UNKNOWN".to_string();
            let mut pre_hash = "UNKNOWN".to_string();
            let mut post_hash = "UNKNOWN".to_string();
            
            for line in content.lines() {
                let line_trimmed = line.trim();
                if line_trimmed.starts_with("transition:") {
                    transition = line_trimmed.trim_start_matches("transition:").trim_matches('"').trim().to_string();
                } else if line_trimmed.starts_with("status:") {
                    status = line_trimmed.trim_start_matches("status:").trim_matches('"').trim().to_string();
                } else if line_trimmed.starts_with("sponsor_did:") {
                    sponsor_did = line_trimmed.trim_start_matches("sponsor_did:").trim_matches('"').trim().to_string();
                } else if line_trimmed.starts_with("pre_hash:") {
                    pre_hash = line_trimmed.trim_start_matches("pre_hash:").trim_matches('"').trim().to_string();
                } else if line_trimmed.starts_with("post_hash:") {
                    post_hash = line_trimmed.trim_start_matches("post_hash:").trim_matches('"').trim().to_string();
                }
            }
            
            table_rows.push(format!(
                "| {} | {} | {} | {} | `{}` | `{}` |",
                updated_at, transition, status, sponsor_did, pre_hash, post_hash
            ));
        }
    }
    
    let rows_str = if table_rows.is_empty() {
        "No transitions recorded in the current epoch.\n".to_string()
    } else {
        let mut table = "| Timestamp | Transition | Status | Sponsor DID | Pre Ingress Hash | Post Egress Hash |\n".to_string();
        table.push_str("| --- | --- | --- | --- | --- | --- |\n");
        for r in table_rows {
            table.push_str(&r);
            table.push('\n');
        }
        table
    };
    
    let report_content = format!(
        "# CLM Evolution Audit Report\n\n\
         Generated: {}\n\n\
         ## Verified Transitions\n\n\
         {}\n",
        chrono::Local::now().to_rfc2822(),
        rows_str
    );
    
    let path = Path::new(clm_root).join("docs/spec/consensus_audit_report.md");
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
    }
    std::fs::write(&path, &report_content).map_err(|e| e.to_string())?;
    
    Ok(format!("Evolution audit report generated at: {:?}", path))
}