Skip to main content

clm_rust_core/
utils.rs

1//! Shared utility functions for the CLM Rust Core.
2//!
3//! This module consolidates commonly used helper functions that were previously
4//! duplicated across multiple source files. Centralizing them here follows the
5//! DRY (Don't Repeat Yourself) principle and ensures consistent behavior.
6
7use std::env;
8
9/// Returns the current local timestamp in ISO 8601 format: `%Y-%m-%dT%H:%M:%S%z`.
10///
11/// This is used for database `created_at`/`updated_at` fields, handle registration
12/// timestamps, and execution log entries throughout the codebase.
13///
14/// # Examples
15/// ```ignore
16/// let now = crate::utils::now_iso8601();
17/// // "2026-06-19T14:15:00+0800"
18/// ```
19pub fn now_iso8601() -> String {
20    chrono::Local::now()
21        .format("%Y-%m-%dT%H:%M:%S%.6f%z")
22        .to_string()
23}
24
25/// Returns `true` if the CLM runtime is operating in Zero-File-System mode.
26///
27/// When `CLM_ZERO_FS=true` is set, the runtime bypasses all direct filesystem write
28/// operations, achieving parity with browser storage paradigms (IndexedDB, DuckDB WASM).
29/// In-memory place markings and SQLite handle persistence replace disk I/O.
30pub fn is_zero_fs() -> bool {
31    env::var("CLM_ZERO_FS").unwrap_or_default() == "true"
32}
33
34/// Indents each non-empty line of a string by the specified number of spaces.
35///
36/// Empty lines (whitespace-only) are preserved as bare newlines.
37/// Used by YAML/MCard serialization in `baldwin.rs`, `compile.rs`, and `mcard_encoder.rs`.
38pub fn indent_lines(s: &str, spaces: usize) -> String {
39    let indent = " ".repeat(spaces);
40    let mut result = String::new();
41    for line in s.lines() {
42        if line.trim().is_empty() {
43            result.push('\n');
44        } else {
45            result.push_str(&indent);
46            result.push_str(line);
47            result.push('\n');
48        }
49    }
50    result
51}
52
53/// Collects all `CLM_MOCK_*` environment variables, filtering them from the
54/// current process environment.
55///
56/// Returns a vector of `(key, value)` pairs. Used by the CPN VM, evaluator dispatcher,
57/// and polyglot execution engine to isolate mock behaviors during test execution.
58pub fn collect_clm_mock_vars() -> Vec<(String, String)> {
59    env::vars()
60        .filter(|(k, _)| k.starts_with("CLM_MOCK_"))
61        .collect()
62}
63
64/// Captures stdout and stderr from a `std::process::Output` as owned Strings.
65///
66/// Uses lossy UTF-8 conversion for robustness against non-UTF-8 output bytes.
67pub fn capture_process_output(output: &std::process::Output) -> (String, String) {
68    (
69        String::from_utf8_lossy(&output.stdout).into_owned(),
70        String::from_utf8_lossy(&output.stderr).into_owned(),
71    )
72}
73
74/// Sets an environment variable.
75///
76/// # Safety
77/// Modifying the environment is inherently thread-unsafe if other threads are concurrently
78/// accessing it. In Rust 2024, `std::env::set_var` is marked as `unsafe`. This wrapper
79/// encapsulates the unsafe block, but the caller must ensure that environment mutations
80/// do not race with concurrent reads or other writes. Prefer `EvaluationContext` instead.
81pub fn set_env_var(key: &str, value: &str) {
82    unsafe {
83        env::set_var(key, value);
84    }
85}
86
87/// Removes an environment variable.
88///
89/// # Safety
90/// Like `set_env_var`, removing an environment variable is thread-unsafe and encapsulates
91/// the unsafe `std::env::remove_var` call. Prefer `EvaluationContext` instead.
92pub fn remove_env_var(key: &str) {
93    unsafe {
94        env::remove_var(key);
95    }
96}
97
98/// Compatibility alias for `crate::cross_cutting::context::CLMContext` (`INV-490`, `DoD-490-06`).
99pub type EvaluationContext = crate::cross_cutting::context::CLMContext;
100pub use crate::cross_cutting::context::CLMContext;
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    #[test]
107    fn test_evaluation_context_isolation() {
108        let mut ctx1 = EvaluationContext::new().with_nested_exec(true);
109        ctx1.set_var("LOCAL_FLAG", "value1");
110
111        let mut ctx2 = EvaluationContext::new().with_nested_exec(false);
112        ctx2.set_var("LOCAL_FLAG", "value2");
113
114        assert_eq!(ctx1.get_var("LOCAL_FLAG"), Some("value1".to_string()));
115        assert_eq!(ctx2.get_var("LOCAL_FLAG"), Some("value2".to_string()));
116        assert!(ctx1.is_nested());
117        assert!(!ctx2.is_nested());
118    }
119}
120
121