1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//! 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());
}
}