clm-kernel 0.0.5

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation

/// Runs a shell-based integration test by sourcing bootstrap and executing a test function.
///
/// # Arguments
/// * `script_path` - Relative path from CLM_ROOT to the test .sh file
/// * `test_fn_name` - Name of the bash function to invoke after sourcing
/// * `extra_setup` - Optional extra bash code injected before the source+call line
pub fn run_shell_test(
    script_path: &str,
    test_fn_name: &str,
    extra_setup: Option<&str>,
) -> Result<String, String> {
    let clm_root = super::resolve_clm_root();
    let clm_root_str = super::path_to_slash_str(&clm_root);
    #[cfg(windows)]
    let clm_root_unix = if clm_root_str.len() >= 2 && clm_root_str.as_bytes()[1] == b':' {
        let drive = (clm_root_str.as_bytes()[0] as char).to_ascii_lowercase();
        format!("/{}{}", drive, &clm_root_str[2..])
    } else {
        clm_root_str.clone()
    };
    #[cfg(not(windows))]
    let clm_root_unix = clm_root_str.clone();

    let full_script = clm_root.join(script_path);
    let full_script_str = super::path_to_slash_str(&full_script);
    #[cfg(windows)]
    let full_script_unix = if full_script_str.len() >= 2 && full_script_str.as_bytes()[1] == b':' {
        let drive = (full_script_str.as_bytes()[0] as char).to_ascii_lowercase();
        format!("/{}{}", drive, &full_script_str[2..])
    } else {
        full_script_str.clone()
    };
    #[cfg(not(windows))]
    let full_script_unix = full_script_str.clone();

    let extra = extra_setup.unwrap_or("");

    #[cfg(windows)]
    let bin_dir_unix = format!("{}/kernel/bin/windows-amd64", clm_root_unix);
    #[cfg(target_os = "macos")]
    let bin_dir_unix = format!("{}/kernel/bin/darwin-arm64", clm_root_unix);
    #[cfg(not(any(windows, target_os = "macos")))]
    let bin_dir_unix = format!("{}/kernel/bin/linux-amd64", clm_root_unix);

    let script_content = format!(
        r#"
export CLM_ROOT="{}"
export ORIGINAL_CLM_ROOT="$CLM_ROOT"
export CLM_RUNNER="rust"
export PATH="{}:{}:{}/kernel/scripts:{}/.venv/Scripts:{}/.venv/bin:$PATH"
clm_root() {{ echo "$CLM_ROOT"; }}
export -f clm_root

# Intercept exit to prevent bootstrap scripts from terminating the shell
exit() {{ return "${{1:-0}}"; }}

while IFS= read -r f; do
    if [[ "$f" != *"clmEval.sh"* && "$f" != *"main.sh"* && "$f" != *"evaluator.sh"* && "$f" != *"eoa_sponsor.sh"* ]]; then
        source "$f" 2>/dev/null || true
    fi
done < <(find "{}/computable_knowledge/Concrete/layer5_system/bootstrap" -name "node_modules" -prune -o -name "*.sh" -print)

unset -f exit

{}

source "{}" && {}
"#,
        clm_root_str,
        bin_dir_unix,
        clm_root_unix,
        clm_root_unix,
        clm_root_unix,
        clm_root_unix,
        clm_root_unix,
        extra,
        full_script_unix,
        test_fn_name
    );

    let output = {
        let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
        let _ = std::fs::create_dir_all(&temp_dir);
        let temp_file = temp_dir.join(format!("clm_shell_test_{}_{}.sh", std::process::id(), std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)));
        std::fs::write(&temp_file, &script_content)
            .map_err(|e| format!("Failed to write temp script: {}", e))?;

        #[cfg(windows)]
        {
            // On Windows, convert the path to Unix-style for Git Bash
            let temp_path_str = temp_file.to_string_lossy().replace('\\', "/");
            // Convert drive letter: C:/... -> /c/...
            let temp_path_unix = if temp_path_str.len() >= 2 && temp_path_str.as_bytes()[1] == b':' {
                let drive = (temp_path_str.as_bytes()[0] as char).to_ascii_lowercase();
                format!("/{}{}", drive, &temp_path_str[2..])
            } else {
                temp_path_str
            };
            let result = std::process::Command::new(crate::fs_utils::get_bash_command())
                .arg(&temp_path_unix)
                .output()
                .map_err(|e| format!("Failed to run bash script: {}", e));
            let _ = std::fs::remove_file(&temp_file);
            result?
        }
        #[cfg(not(windows))]
        {
            let result = std::process::Command::new(crate::fs_utils::get_bash_command())
                .arg(&temp_file)
                .output()
                .map_err(|e| format!("Failed to run bash script: {}", e));
            let _ = std::fs::remove_file(&temp_file);
            result?
        }
    };

    if output.status.success() {
        Ok("PASS".to_string())
    } else {
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        Err(format!(
            "Test failed with exit code: {}\n--- STDOUT ---\n{}\n--- STDERR ---\n{}",
            output.status, stdout, stderr
        ))
    }
}

/// Macro to define a shell-wrapper integration test function.
///
/// Each invocation generates a `pub fn` that delegates to `run_shell_test`
/// with the specified script path and test function name.
///
/// # Variants
/// - Basic: `define_shell_test!(fn_name, "script/path.sh", "test_fn");`
/// - With extra setup: `define_shell_test!(fn_name, "script/path.sh", "test_fn", extra = "bash code");`
macro_rules! define_shell_test {
    ($fn_name:ident, $script:expr, $test_fn:expr) => {
        pub fn $fn_name() -> Result<String, String> {
            super::shell_runner::run_shell_test($script, $test_fn, None)
        }
        inventory::submit! {
            $crate::evaluator::dispatch::DispatchEntry {
                module_path: concat!("clm_rust_core::integration::", $test_fn),
                func: |_clm_root, _clm_file| {
                    $fn_name().map(|out| (0, out))
                },
            }
        }
    };
    ($fn_name:ident, $script:expr, $test_fn:expr, extra = $extra:expr) => {
        pub fn $fn_name() -> Result<String, String> {
            super::shell_runner::run_shell_test($script, $test_fn, Some($extra))
        }
        inventory::submit! {
            $crate::evaluator::dispatch::DispatchEntry {
                module_path: concat!("clm_rust_core::integration::", $test_fn),
                func: |_clm_root, _clm_file| {
                    $fn_name().map(|out| (0, out))
                },
            }
        }
    };
}
pub(crate) use define_shell_test;