clm-kernel 0.0.22

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Integration test module for the CLM Rust core.
//!
//! Organized by test layer:
//! - **Layer 0 (Microkernel)**: Core kernel operations, MCard, symbol extraction, etc.
//! - **Layer 1 (CPN VM)**: Coloured Petri Net VM, compose nets, polyglot execution
//! - **Layer 2 (Storage)**: Storage equivalence, directory ingestion, Merkle, finetuning
//! - **Layer 3 (Network)**: Namespace sync, chat interface, peer discovery
//!
//! Most tests delegate to shell scripts via the shared `shell_runner` infrastructure.
//! Complex tests with Rust-native logic live in dedicated modules (`zerofs`, `polyglot_sla`).

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

pub mod shell_runner;
mod layer0_microkernel;
mod layer1_cpn_vm;
mod layer2_storage;
mod layer3_network;
mod zerofs;
mod polyglot_sla;

// Re-export all public test functions so that existing references to
// `crate::integration::run_integration_*` continue to resolve.
pub use layer0_microkernel::*;
pub use layer1_cpn_vm::*;
pub use layer2_storage::*;
pub use layer3_network::*;
pub use zerofs::*;
pub use polyglot_sla::*;


// ─── Shared Utilities ──────────────────────────────────────────────────────

fn path_to_slash_str<P: AsRef<Path>>(p: P) -> String {
    p.as_ref().to_string_lossy().replace('\\', "/")
}

/// Resolve the CLM workspace root directory.
///
/// Strategy:
/// 1. If `CLM_ROOT` env var is set, use it.
/// 2. Walk upward from the current directory looking for the canonical CLM
///    workspace marker (`computable_knowledge/Concrete/layer5_system/bootstrap/evaluator`).
/// 3. Fallback to the current directory.
pub fn resolve_clm_root() -> PathBuf {
    if let Ok(val) = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_ROOT) {
        return PathBuf::from(val);
    }

    if let Ok(curr) = env::current_dir() {
        let mut dir = curr;
        loop {
            if dir.join("computable_knowledge/Concrete/layer5_system/bootstrap/evaluator").is_dir()
                || dir.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator").is_dir()
            {
                return dir;
            }
            if dir.join("clm/computable_knowledge/Concrete/layer5_system/bootstrap/evaluator").is_dir()
                || dir.join("clm/computable_knowledge/Abstract/layer5_system/bootstrap/evaluator").is_dir()
            {
                return dir.join("clm");
            }
            if let Some(parent) = dir.parent() {
                dir = parent.to_path_buf();
            } else {
                break;
            }
        }
    }

    // Fallback to current directory
    env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
}

#[cfg(unix)]
fn create_dir_symlink<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> std::io::Result<()> {
    std::os::unix::fs::symlink(original, link)
}

#[cfg(windows)]
fn create_dir_symlink<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> std::io::Result<()> {
    if let Ok(()) = std::os::windows::fs::symlink_dir(&original, &link) {
        return Ok(());
    }
    let status = std::process::Command::new("cmd")
        .args([
            "/c",
            "mklink",
            "/j",
            link.as_ref().to_str().unwrap(),
            original.as_ref().to_str().unwrap(),
        ])
        .status()?;
    if status.success() {
        Ok(())
    } else {
        Err(std::io::Error::other("Failed to create directory junction"))
    }
}

/// Set up an isolated test environment with symlinks to the real CLM workspace.
fn setup_isolated_env(suffix: &str) -> (PathBuf, PathBuf) {
    let original_clm_root = resolve_clm_root();

    let test_dir = original_clm_root.join(format!("data/execution_logs/.tmp/{}", suffix));
    let _ = fs::remove_dir_all(&test_dir);
    fs::create_dir_all(&test_dir).unwrap();

    // Symlinks to mimic CLM_ROOT
    for dir in &["tools", "types", "computable_knowledge", "tests", "kernel"] {
        let _ = create_dir_symlink(original_clm_root.join(dir), test_dir.join(dir));
    }
    fs::create_dir_all(test_dir.join("db")).unwrap();
    fs::create_dir_all(test_dir.join("data/content_memory")).unwrap();
    fs::create_dir_all(test_dir.join("data/execution_logs")).unwrap();

    let db_dir = test_dir.join("db");
    crate::utils::set_env_var(crate::layer0::vocabulary_env::ENV_CLM_ROOT, test_dir.to_str().unwrap());
    crate::utils::set_env_var(crate::layer0::vocabulary_env::ENV_CLM_MEMBROKER_SNAP_DIR, db_dir.to_str().unwrap());
    (original_clm_root, test_dir)
}

/// Restore environment variables and clean up the test directory.
fn restore_env(original_clm_root: &Path, test_dir: &Path) {
    crate::utils::set_env_var(crate::layer0::vocabulary_env::ENV_CLM_ROOT, original_clm_root.to_str().unwrap());
    let _ = fs::remove_dir_all(test_dir);
}

/// Generate an honest stub result for unimplemented Rust-native test suites.
///
/// By default, prints a visible STUB warning but returns Ok so CI is not broken.
/// Set CLM_STRICT_INTEGRATION=true to make stubs return Err instead (surfaces false-green).
#[allow(dead_code)]
fn print_stub_pass(suite_name: &str) -> Result<String, String> {
    let strict = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_STRICT_INTEGRATION)
        .map(|v| v.to_lowercase() == "true")
        .unwrap_or(false);
    if strict {
        return Err(format!(
            "STUB FAILURE: '{}' is not implemented (CLM_STRICT_INTEGRATION=true)",
            suite_name
        ));
    }
    println!("======================================================");
    println!("  Test Suite: {} (Rust Native — STUB)", suite_name);
    println!("======================================================\n");
    println!("  STUB: '{}' is not implemented — no tests were run", suite_name);
    println!("\n======================================================");
    print!("  Results: 0 run, 0 passed (STUB)");
    Ok("".to_string())
}