Skip to main content

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