clm-kernel 0.0.2

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

use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Thread-Isolated Evaluation Context.
///
/// Encapsulates execution variables, working directories, and mock flags without
/// mutating process-global state (`std::env::set_var`), adhering to Cordis Fiber
/// context scoping and Kenotic core stateless principles.
#[derive(Debug, Clone, Default)]
pub struct EvaluationContext {
    clm_root: Option<PathBuf>,
    nested_exec: bool,
    zero_fs: bool,
    env_vars: HashMap<String, String>,
}

impl EvaluationContext {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_root(mut self, root: impl Into<PathBuf>) -> Self {
        self.clm_root = Some(root.into());
        self
    }

    pub fn with_nested_exec(mut self, nested: bool) -> Self {
        self.nested_exec = nested;
        self
    }

    pub fn with_zero_fs(mut self, zero_fs: bool) -> Self {
        self.zero_fs = zero_fs;
        self
    }

    pub fn root(&self) -> Option<&Path> {
        self.clm_root.as_deref()
    }

    pub fn is_nested(&self) -> bool {
        self.nested_exec
    }

    pub fn is_zero_fs(&self) -> bool {
        self.zero_fs || is_zero_fs()
    }

    pub fn set_var(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.env_vars.insert(key.into(), value.into());
    }

    pub fn get_var(&self, key: &str) -> Option<String> {
        if let Some(val) = self.env_vars.get(key) {
            return Some(val.clone());
        }
        env::var(key).ok()
    }

    pub fn remove_var(&mut self, key: &str) {
        self.env_vars.remove(key);
    }
}

#[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());
    }
}