clm_rust_core/layer0/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 crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_ZERO_FS).unwrap_or_default() == "true"
32}
33
34/// Asserts a test's wall-clock bound `measured < bound` (INV-589), mirroring `tests/timing.py`.
35///
36/// `make test` runs many jobs at once and exports `CLM_SKIP_TIMING_ASSERTIONS=1`, so the bound
37/// is then printed, not asserted. `make test-budget` and a direct `cargo test` assert it.
38pub fn assert_within(measured: std::time::Duration, bound: std::time::Duration, what: &str) {
39 if measured < bound {
40 return;
41 }
42 let message = format!("{what}: {measured:?}, bound < {bound:?}");
43 if crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_SKIP_TIMING_ASSERTIONS).as_deref() == Ok("1") {
44 println!("[timing not asserted under CLM_SKIP_TIMING_ASSERTIONS=1] {message}");
45 } else {
46 panic!("{message}");
47 }
48}
49
50/// Indents each non-empty line of a string by the specified number of spaces.
51///
52/// Empty lines (whitespace-only) are preserved as bare newlines.
53/// Used by YAML/MCard serialization in `baldwin.rs`, `compile.rs`, and `mcard_encoder.rs`.
54pub fn indent_lines(s: &str, spaces: usize) -> String {
55 let indent = " ".repeat(spaces);
56 let mut result = String::new();
57 for line in s.lines() {
58 if line.trim().is_empty() {
59 result.push('\n');
60 } else {
61 result.push_str(&indent);
62 result.push_str(line);
63 result.push('\n');
64 }
65 }
66 result
67}
68
69/// Collects all `CLM_MOCK_*` environment variables, filtering them from the
70/// current process environment.
71///
72/// Returns a vector of `(key, value)` pairs. Used by the CPN VM, evaluator dispatcher,
73/// and polyglot execution engine to isolate mock behaviors during test execution.
74pub fn collect_clm_mock_vars() -> Vec<(String, String)> {
75 crate::layer0::environment::vars()
76 .filter(|(k, _)| k.starts_with(crate::layer0::vocabulary_env::ENV_CLM_MOCK))
77 .collect()
78}
79
80/// Captures stdout and stderr from a `std::process::Output` as owned Strings.
81///
82/// Uses lossy UTF-8 conversion for robustness against non-UTF-8 output bytes.
83pub fn capture_process_output(output: &std::process::Output) -> (String, String) {
84 (
85 String::from_utf8_lossy(&output.stdout).into_owned(),
86 String::from_utf8_lossy(&output.stderr).into_owned(),
87 )
88}
89
90/// Sets an environment variable.
91///
92/// # Safety
93/// Modifying the environment is inherently thread-unsafe if other threads are concurrently
94/// accessing it. In Rust 2024, `std::env::set_var` is marked as `unsafe`. This wrapper
95/// encapsulates the unsafe block, but the caller must ensure that environment mutations
96/// do not race with concurrent reads or other writes. Prefer `EvaluationContext` instead.
97pub fn set_env_var(key: &str, value: &str) {
98 unsafe {
99 env::set_var(key, value);
100 }
101}
102
103/// Removes an environment variable.
104///
105/// # Safety
106/// Like `set_env_var`, removing an environment variable is thread-unsafe and encapsulates
107/// the unsafe `std::env::remove_var` call. Prefer `EvaluationContext` instead.
108pub fn remove_env_var(key: &str) {
109 unsafe {
110 env::remove_var(key);
111 }
112}
113
114/// Compatibility alias for `crate::cross_cutting::context::CLMContext` (`INV-490`, `DoD-490-06`).
115pub type EvaluationContext = crate::cross_cutting::context::CLMContext;
116pub use crate::cross_cutting::context::CLMContext;
117
118#[cfg(test)]
119mod tests {
120 use super::*;
121
122 #[test]
123 fn test_evaluation_context_isolation() {
124 let mut ctx1 = EvaluationContext::new().with_nested_exec(true);
125 ctx1.set_var("LOCAL_FLAG", "value1");
126
127 let mut ctx2 = EvaluationContext::new().with_nested_exec(false);
128 ctx2.set_var("LOCAL_FLAG", "value2");
129
130 assert_eq!(ctx1.get_var("LOCAL_FLAG"), Some("value1".to_string()));
131 assert_eq!(ctx2.get_var("LOCAL_FLAG"), Some("value2".to_string()));
132 assert!(ctx1.is_nested());
133 assert!(!ctx2.is_nested());
134 }
135}
136
137