clm-kernel 0.0.19

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Shared utility functions for the CLM Rust Core.
//!
//! This module consolidates commonly used helper functions that were previously
//! duplicated across multiple source files. Centralizing them here follows the
//! DRY (Don't Repeat Yourself) principle and ensures consistent behavior.

use std::env;

/// Returns the current local timestamp in ISO 8601 format: `%Y-%m-%dT%H:%M:%S%z`.
///
/// This is used for database `created_at`/`updated_at` fields, handle registration
/// timestamps, and execution log entries throughout the codebase.
///
/// # Examples
/// ```ignore
/// let now = crate::utils::now_iso8601();
/// // "2026-06-19T14:15:00+0800"
/// ```
pub fn now_iso8601() -> String {
    chrono::Local::now()
        .format("%Y-%m-%dT%H:%M:%S%.6f%z")
        .to_string()
}

/// Returns `true` if the CLM runtime is operating in Zero-File-System mode.
///
/// When `CLM_ZERO_FS=true` is set, the runtime bypasses all direct filesystem write
/// operations, achieving parity with browser storage paradigms (IndexedDB, DuckDB WASM).
/// In-memory place markings and SQLite handle persistence replace disk I/O.
pub fn is_zero_fs() -> bool {
    env::var("CLM_ZERO_FS").unwrap_or_default() == "true"
}

/// Indents each non-empty line of a string by the specified number of spaces.
///
/// Empty lines (whitespace-only) are preserved as bare newlines.
/// Used by YAML/MCard serialization in `baldwin.rs`, `compile.rs`, and `mcard_encoder.rs`.
pub fn indent_lines(s: &str, spaces: usize) -> String {
    let indent = " ".repeat(spaces);
    let mut result = String::new();
    for line in s.lines() {
        if line.trim().is_empty() {
            result.push('\n');
        } else {
            result.push_str(&indent);
            result.push_str(line);
            result.push('\n');
        }
    }
    result
}

/// Collects all `CLM_MOCK_*` environment variables, filtering them from the
/// current process environment.
///
/// Returns a vector of `(key, value)` pairs. Used by the CPN VM, evaluator dispatcher,
/// and polyglot execution engine to isolate mock behaviors during test execution.
pub fn collect_clm_mock_vars() -> Vec<(String, String)> {
    env::vars()
        .filter(|(k, _)| k.starts_with("CLM_MOCK_"))
        .collect()
}

/// Captures stdout and stderr from a `std::process::Output` as owned Strings.
///
/// Uses lossy UTF-8 conversion for robustness against non-UTF-8 output bytes.
pub fn capture_process_output(output: &std::process::Output) -> (String, String) {
    (
        String::from_utf8_lossy(&output.stdout).into_owned(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    )
}

/// Sets an environment variable.
///
/// # Safety
/// Modifying the environment is inherently thread-unsafe if other threads are concurrently
/// accessing it. In Rust 2024, `std::env::set_var` is marked as `unsafe`. This wrapper
/// encapsulates the unsafe block, but the caller must ensure that environment mutations
/// do not race with concurrent reads or other writes. Prefer `EvaluationContext` instead.
pub fn set_env_var(key: &str, value: &str) {
    unsafe {
        env::set_var(key, value);
    }
}

/// Removes an environment variable.
///
/// # Safety
/// Like `set_env_var`, removing an environment variable is thread-unsafe and encapsulates
/// the unsafe `std::env::remove_var` call. Prefer `EvaluationContext` instead.
pub fn remove_env_var(key: &str) {
    unsafe {
        env::remove_var(key);
    }
}

/// Compatibility alias for `crate::cross_cutting::context::CLMContext` (`INV-490`, `DoD-490-06`).
pub type EvaluationContext = crate::cross_cutting::context::CLMContext;
pub use crate::cross_cutting::context::CLMContext;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_evaluation_context_isolation() {
        let mut ctx1 = EvaluationContext::new().with_nested_exec(true);
        ctx1.set_var("LOCAL_FLAG", "value1");

        let mut ctx2 = EvaluationContext::new().with_nested_exec(false);
        ctx2.set_var("LOCAL_FLAG", "value2");

        assert_eq!(ctx1.get_var("LOCAL_FLAG"), Some("value1".to_string()));
        assert_eq!(ctx2.get_var("LOCAL_FLAG"), Some("value2".to_string()));
        assert!(ctx1.is_nested());
        assert!(!ctx2.is_nested());
    }
}