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%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
98use std::collections::HashMap;
99use std::path::{Path, PathBuf};
100
101/// Thread-Isolated Evaluation Context.
102///
103/// Encapsulates execution variables, working directories, and mock flags without
104/// mutating process-global state (`std::env::set_var`), adhering to Cordis Fiber
105/// context scoping and Kenotic core stateless principles.
106#[derive(Debug, Clone, Default)]
107pub struct EvaluationContext {
108    clm_root: Option<PathBuf>,
109    nested_exec: bool,
110    zero_fs: bool,
111    env_vars: HashMap<String, String>,
112}
113
114impl EvaluationContext {
115    pub fn new() -> Self {
116        Self::default()
117    }
118
119    pub fn with_root(mut self, root: impl Into<PathBuf>) -> Self {
120        self.clm_root = Some(root.into());
121        self
122    }
123
124    pub fn with_nested_exec(mut self, nested: bool) -> Self {
125        self.nested_exec = nested;
126        self
127    }
128
129    pub fn with_zero_fs(mut self, zero_fs: bool) -> Self {
130        self.zero_fs = zero_fs;
131        self
132    }
133
134    pub fn root(&self) -> Option<&Path> {
135        self.clm_root.as_deref()
136    }
137
138    pub fn is_nested(&self) -> bool {
139        self.nested_exec
140    }
141
142    pub fn is_zero_fs(&self) -> bool {
143        self.zero_fs || is_zero_fs()
144    }
145
146    pub fn set_var(&mut self, key: impl Into<String>, value: impl Into<String>) {
147        self.env_vars.insert(key.into(), value.into());
148    }
149
150    pub fn get_var(&self, key: &str) -> Option<String> {
151        if let Some(val) = self.env_vars.get(key) {
152            return Some(val.clone());
153        }
154        env::var(key).ok()
155    }
156
157    pub fn remove_var(&mut self, key: &str) {
158        self.env_vars.remove(key);
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn test_evaluation_context_isolation() {
168        let mut ctx1 = EvaluationContext::new().with_nested_exec(true);
169        ctx1.set_var("LOCAL_FLAG", "value1");
170
171        let mut ctx2 = EvaluationContext::new().with_nested_exec(false);
172        ctx2.set_var("LOCAL_FLAG", "value2");
173
174        assert_eq!(ctx1.get_var("LOCAL_FLAG"), Some("value1".to_string()));
175        assert_eq!(ctx2.get_var("LOCAL_FLAG"), Some("value2".to_string()));
176        assert!(ctx1.is_nested());
177        assert!(!ctx2.is_nested());
178    }
179}
180