Skip to main content

clm_rust_core/cross_cutting/
context.rs

1//! Universal Scoped Execution Configuration (`CLMContext` — `INV-490`).
2//!
3//! Cordis Naming Boundary:
4//! `CLMContext` is the immutable-after-construction execution-configuration snapshot
5//! (environment snapshot, paths, agent DID, locale, flags); it is NOT a service locator
6//! and must not be conflated with the Cordis service/fiber `Context` (`provide`/`get`/`isolate`).
7//! Compose them as `fiber_ctx.provide("clm.context", clm_config)` and
8//! `fiber_ctx.provide("clm.storage", storage)`.
9
10use std::cell::RefCell;
11use std::collections::{HashMap, HashSet};
12use std::fmt;
13use std::path::{Path, PathBuf};
14use std::sync::atomic::{AtomicUsize, Ordering};
15use std::sync::Arc;
16
17use crate::layer0::runtime_contract::{
18    resolve_env_from_map, ClmEnvVar, ENV_PASSTHROUGH_WHITELIST,
19};
20
21/// Typed error returned when an evaluation path attempts to spawn an OS subprocess
22/// while zero-fork policy or a rejecting process-spawner is active (`INV-491`).
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct SovereignSubprocessForbiddenError {
25    pub command: String,
26    pub args: Vec<String>,
27    pub reason: String,
28}
29
30impl SovereignSubprocessForbiddenError {
31    pub fn new(command: impl Into<String>, args: Vec<String>, reason: impl Into<String>) -> Self {
32        Self {
33            command: command.into(),
34            args,
35            reason: reason.into(),
36        }
37    }
38}
39
40impl fmt::Display for SovereignSubprocessForbiddenError {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        write!(
43            f,
44            "SovereignSubprocessForbiddenError: {} (command={}, args={:?})",
45            self.reason, self.command, self.args
46        )
47    }
48}
49
50impl std::error::Error for SovereignSubprocessForbiddenError {}
51
52/// Injectable process-spawner boundary for evaluation policy enforcement (`INV-491`).
53pub trait ProcessSpawner: fmt::Debug + Send + Sync {
54    fn spawn_process(
55        &self,
56        command: &str,
57        args: &[String],
58    ) -> Result<i32, SovereignSubprocessForbiddenError>;
59}
60
61/// Process-spawner implementation that rejects all subprocess launches and records call count.
62#[derive(Debug, Default)]
63pub struct RejectingProcessSpawner {
64    calls: AtomicUsize,
65}
66
67impl RejectingProcessSpawner {
68    pub fn new() -> Self {
69        Self {
70            calls: AtomicUsize::new(0),
71        }
72    }
73
74    pub fn call_count(&self) -> usize {
75        self.calls.load(Ordering::SeqCst)
76    }
77}
78
79impl ProcessSpawner for RejectingProcessSpawner {
80    fn spawn_process(
81        &self,
82        command: &str,
83        args: &[String],
84    ) -> Result<i32, SovereignSubprocessForbiddenError> {
85        self.calls.fetch_add(1, Ordering::SeqCst);
86        Err(SovereignSubprocessForbiddenError::new(
87            command,
88            args.to_vec(),
89            "Subprocess spawning is forbidden by active CLMContext process policy",
90        ))
91    }
92}
93
94thread_local! {
95    static THREAD_CONTEXT_STACK: RefCell<Vec<CLMContext>> = const { RefCell::new(Vec::new()) };
96}
97
98pub struct CLMContextScopeGuard;
99
100impl Drop for CLMContextScopeGuard {
101    fn drop(&mut self) {
102        THREAD_CONTEXT_STACK.with(|stack| {
103            stack.borrow_mut().pop();
104        });
105    }
106}
107
108#[derive(Debug, Clone, Default)]
109pub struct CLMContextOverrides {
110    pub project_root: Option<PathBuf>,
111    pub db_dir: Option<PathBuf>,
112    pub runtime: Option<String>,
113    pub agent_did: Option<String>,
114    pub sponsor_did: Option<String>,
115    pub execution_locale_hash: Option<String>,
116    pub hash_algo: Option<String>,
117    pub zero_fs: Option<bool>,
118    pub forbid_subprocess: Option<bool>,
119    pub target_file: Option<PathBuf>,
120    pub run_id: Option<String>,
121    pub nested_exec: Option<bool>,
122    pub scoped_vars: HashMap<String, String>,
123    pub masked_vars: HashSet<String>,
124    pub process_spawner: Option<Arc<dyn ProcessSpawner>>,
125}
126
127#[derive(Debug, Clone)]
128struct CLMContextInner {
129    project_root: Option<PathBuf>,
130    db_dir: PathBuf,
131    runtime: String,
132    agent_did: String,
133    sponsor_did: Option<String>,
134    execution_locale_hash: String,
135    hash_algo: String,
136    zero_fs: bool,
137    forbid_subprocess: bool,
138    target_file: Option<PathBuf>,
139    run_id: Option<String>,
140    nested_exec: bool,
141    scoped_vars: HashMap<String, String>,
142    masked_vars: HashSet<String>,
143    process_spawner: Option<Arc<dyn ProcessSpawner>>,
144}
145
146/// Thread-safe, copy-on-write execution configuration snapshot (`INV-490`).
147#[derive(Debug, Clone)]
148pub struct CLMContext {
149    inner: Arc<CLMContextInner>,
150}
151
152/// Deprecated compatibility alias for `CLMContext` (`DoD-490-06`).
153pub type EvaluationContext = CLMContext;
154
155fn parse_bool(val: &str) -> bool {
156    matches!(
157        val.trim().to_ascii_lowercase().as_str(),
158        "1" | "true" | "yes" | "on"
159    )
160}
161
162impl Default for CLMContext {
163    fn default() -> Self {
164        Self::for_test_sandbox()
165    }
166}
167
168impl CLMContext {
169    pub fn new() -> Self {
170        Self::for_test_sandbox()
171    }
172
173    /// Construct a deterministic test-sandbox context with zero host-environment reads.
174    pub fn for_test_sandbox() -> Self {
175        let empty: HashMap<String, String> = HashMap::new();
176        Self::from_process_environment(&empty)
177    }
178
179    /// Capture and normalize an explicit environment snapshot at the CLI/process boundary.
180    pub fn from_process_environment(snapshot: &HashMap<String, String>) -> Self {
181        let project_root = resolve_env_from_map(ClmEnvVar::Root, snapshot)
182            .filter(|s| !s.is_empty())
183            .map(PathBuf::from);
184        let db_dir_str = resolve_env_from_map(ClmEnvVar::DbDir, snapshot)
185            .unwrap_or_else(|| ClmEnvVar::DbDir.default_value().to_string());
186        let db_dir = match &project_root {
187            Some(root) if !Path::new(&db_dir_str).is_absolute() => root.join(&db_dir_str),
188            _ => PathBuf::from(&db_dir_str),
189        };
190        let runtime = resolve_env_from_map(ClmEnvVar::Runtime, snapshot)
191            .unwrap_or_else(|| ClmEnvVar::Runtime.default_value().to_string());
192        let agent_did = resolve_env_from_map(ClmEnvVar::AgentDid, snapshot)
193            .unwrap_or_else(|| ClmEnvVar::AgentDid.default_value().to_string());
194        let sponsor_did =
195            resolve_env_from_map(ClmEnvVar::SponsorDid, snapshot).filter(|s| !s.is_empty());
196        let execution_locale_hash =
197            resolve_env_from_map(ClmEnvVar::ExecutionLocaleHash, snapshot)
198                .unwrap_or_else(|| ClmEnvVar::ExecutionLocaleHash.default_value().to_string());
199        let hash_algo = resolve_env_from_map(ClmEnvVar::HashAlgo, snapshot)
200            .unwrap_or_else(|| ClmEnvVar::HashAlgo.default_value().to_string());
201        let zero_fs = resolve_env_from_map(ClmEnvVar::ZeroFs, snapshot)
202            .map(|v| parse_bool(&v))
203            .unwrap_or(false);
204        let forbid_subprocess = resolve_env_from_map(ClmEnvVar::ForbidSubprocess, snapshot)
205            .map(|v| parse_bool(&v))
206            .unwrap_or(false);
207        let target_file = resolve_env_from_map(ClmEnvVar::TargetFile, snapshot)
208            .filter(|s| !s.is_empty())
209            .map(PathBuf::from);
210        let run_id = resolve_env_from_map(ClmEnvVar::RunId, snapshot).filter(|s| !s.is_empty());
211        let nested_exec = snapshot
212            .get("CLM_NESTED_EXEC")
213            .map(|v| parse_bool(v))
214            .unwrap_or(false);
215
216        let mut scoped_vars = HashMap::new();
217        for key in ENV_PASSTHROUGH_WHITELIST {
218            if let Some(val) = snapshot.get(*key) {
219                if !val.is_empty() {
220                    scoped_vars.insert((*key).to_string(), val.clone());
221                }
222            }
223        }
224        for (k, v) in snapshot {
225            if k.starts_with("CLM_MOCK_") {
226                scoped_vars.insert(k.clone(), v.clone());
227            }
228        }
229
230        Self {
231            inner: Arc::new(CLMContextInner {
232                project_root,
233                db_dir,
234                runtime,
235                agent_did,
236                sponsor_did,
237                execution_locale_hash,
238                hash_algo,
239                zero_fs,
240                forbid_subprocess,
241                target_file,
242                run_id,
243                nested_exec,
244                scoped_vars,
245                masked_vars: HashSet::new(),
246                process_spawner: None,
247            }),
248        }
249    }
250
251    /// Return the active thread-local `CLMContext` or construct one from allowlisted process env keys.
252    pub fn current() -> Self {
253        if let Some(ctx) = THREAD_CONTEXT_STACK.with(|stack| stack.borrow().last().cloned()) {
254            return ctx;
255        }
256        let mut snap = HashMap::new();
257        for key in ENV_PASSTHROUGH_WHITELIST {
258            if let Ok(val) = std::env::var(key) {
259                snap.insert((*key).to_string(), val);
260            }
261        }
262        Self::from_process_environment(&snap)
263    }
264
265    /// Push `self` onto the thread-local context stack until the returned guard is dropped.
266    pub fn enter_scope(&self) -> CLMContextScopeGuard {
267        THREAD_CONTEXT_STACK.with(|stack| {
268            stack.borrow_mut().push(self.clone());
269        });
270        CLMContextScopeGuard
271    }
272
273    /// Read `key` from the active thread-local `CLMContext` first, falling back to `std::env::var`.
274    pub fn get_scoped_or_env(key: &str) -> Option<String> {
275        let from_stack = THREAD_CONTEXT_STACK.with(|stack| {
276            let borrowed = stack.borrow();
277            if let Some(top) = borrowed.last() {
278                if top.inner.masked_vars.contains(key) {
279                    return Some(None);
280                }
281                if let Some(val) = top.inner.scoped_vars.get(key) {
282                    return Some(Some(val.clone()));
283                }
284            }
285            None
286        });
287        match from_stack {
288            Some(res) => res,
289            None => std::env::var(key).ok(),
290        }
291    }
292
293    /// Apply any active thread-local `CLMContext` scoped overrides/masks to a child `Command`.
294    pub fn apply_current_to_command(cmd: &mut std::process::Command) {
295        THREAD_CONTEXT_STACK.with(|stack| {
296            if let Some(top) = stack.borrow().last() {
297                for masked in &top.inner.masked_vars {
298                    cmd.env_remove(masked);
299                }
300                for (k, v) in &top.inner.scoped_vars {
301                    cmd.env(k, v);
302                }
303            }
304        });
305    }
306
307    /// Create an isolated child context with copy-on-write overrides; parent remains immutable.
308    pub fn with_child_scope(&self, overrides: CLMContextOverrides) -> Self {
309        let mut next = (*self.inner).clone();
310        if let Some(root) = overrides.project_root {
311            next.project_root = Some(root);
312        }
313        if let Some(db_dir) = overrides.db_dir {
314            next.db_dir = db_dir;
315        }
316        if let Some(rt) = overrides.runtime {
317            next.runtime = rt.clone();
318            next.scoped_vars.insert("CLM_RUNTIME".to_string(), rt);
319        }
320        if let Some(did) = overrides.agent_did {
321            next.agent_did = did.clone();
322            next.scoped_vars.insert("CLM_AGENT_DID".to_string(), did);
323        }
324        if let Some(sponsor) = overrides.sponsor_did {
325            next.sponsor_did = Some(sponsor.clone());
326            next.scoped_vars
327                .insert("CLM_SPONSOR_DID".to_string(), sponsor);
328        }
329        if let Some(locale) = overrides.execution_locale_hash {
330            next.execution_locale_hash = locale.clone();
331            next.scoped_vars
332                .insert("CLM_EXECUTION_LOCALE_HASH".to_string(), locale);
333        }
334        if let Some(algo) = overrides.hash_algo {
335            next.hash_algo = algo.clone();
336            next.scoped_vars.insert("CLM_HASH_ALGO".to_string(), algo);
337        }
338        if let Some(zfs) = overrides.zero_fs {
339            next.zero_fs = zfs;
340            next.scoped_vars.insert(
341                "CLM_ZERO_FS".to_string(),
342                if zfs { "true" } else { "false" }.to_string(),
343            );
344        }
345        if let Some(forbid) = overrides.forbid_subprocess {
346            next.forbid_subprocess = forbid;
347            next.scoped_vars.insert(
348                "CLM_FORBID_SUBPROCESS".to_string(),
349                if forbid { "true" } else { "false" }.to_string(),
350            );
351        }
352        if let Some(tf) = overrides.target_file {
353            next.scoped_vars.insert(
354                "CLM_TARGET_FILE".to_string(),
355                tf.to_string_lossy().to_string(),
356            );
357            next.target_file = Some(tf);
358        }
359        if let Some(rid) = overrides.run_id {
360            next.run_id = Some(rid.clone());
361            next.scoped_vars.insert("CLM_RUN_ID".to_string(), rid);
362        }
363        if let Some(nested) = overrides.nested_exec {
364            next.nested_exec = nested;
365            if nested {
366                next.masked_vars.remove("CLM_NESTED_EXEC");
367                next.scoped_vars
368                    .insert("CLM_NESTED_EXEC".to_string(), "1".to_string());
369            } else {
370                next.scoped_vars.remove("CLM_NESTED_EXEC");
371                next.masked_vars.insert("CLM_NESTED_EXEC".to_string());
372            }
373        }
374        if let Some(spawner) = overrides.process_spawner {
375            next.process_spawner = Some(spawner);
376        }
377        for m in overrides.masked_vars {
378            next.scoped_vars.remove(&m);
379            next.masked_vars.insert(m);
380        }
381        for (k, v) in overrides.scoped_vars {
382            next.masked_vars.remove(&k);
383            next.scoped_vars.insert(k, v);
384        }
385        Self {
386            inner: Arc::new(next),
387        }
388    }
389
390}
391
392#[path = "context_accessors.rs"]
393mod context_accessors;
394#[allow(unused_imports)]
395pub use context_accessors::*;
396
397#[cfg(test)]
398#[path = "context_tests.rs"]
399mod tests;
400