clm-kernel 0.0.10

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Universal Scoped Execution Configuration (`CLMContext` — `INV-490`).
//!
//! Cordis Naming Boundary:
//! `CLMContext` is the immutable-after-construction execution-configuration snapshot
//! (environment snapshot, paths, agent DID, locale, flags); it is NOT a service locator
//! and must not be conflated with the Cordis service/fiber `Context` (`provide`/`get`/`isolate`).
//! Compose them as `fiber_ctx.provide("clm.context", clm_config)` and
//! `fiber_ctx.provide("clm.storage", storage)`.

use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

use crate::layer0::runtime_contract::{
    resolve_env_from_map, ClmEnvVar, ENV_PASSTHROUGH_WHITELIST,
};

/// Typed error returned when an evaluation path attempts to spawn an OS subprocess
/// while zero-fork policy or a rejecting process-spawner is active (`INV-491`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SovereignSubprocessForbiddenError {
    pub command: String,
    pub args: Vec<String>,
    pub reason: String,
}

impl SovereignSubprocessForbiddenError {
    pub fn new(command: impl Into<String>, args: Vec<String>, reason: impl Into<String>) -> Self {
        Self {
            command: command.into(),
            args,
            reason: reason.into(),
        }
    }
}

impl fmt::Display for SovereignSubprocessForbiddenError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "SovereignSubprocessForbiddenError: {} (command={}, args={:?})",
            self.reason, self.command, self.args
        )
    }
}

impl std::error::Error for SovereignSubprocessForbiddenError {}

/// Injectable process-spawner boundary for evaluation policy enforcement (`INV-491`).
pub trait ProcessSpawner: fmt::Debug + Send + Sync {
    fn spawn_process(
        &self,
        command: &str,
        args: &[String],
    ) -> Result<i32, SovereignSubprocessForbiddenError>;
}

/// Process-spawner implementation that rejects all subprocess launches and records call count.
#[derive(Debug, Default)]
pub struct RejectingProcessSpawner {
    calls: AtomicUsize,
}

impl RejectingProcessSpawner {
    pub fn new() -> Self {
        Self {
            calls: AtomicUsize::new(0),
        }
    }

    pub fn call_count(&self) -> usize {
        self.calls.load(Ordering::SeqCst)
    }
}

impl ProcessSpawner for RejectingProcessSpawner {
    fn spawn_process(
        &self,
        command: &str,
        args: &[String],
    ) -> Result<i32, SovereignSubprocessForbiddenError> {
        self.calls.fetch_add(1, Ordering::SeqCst);
        Err(SovereignSubprocessForbiddenError::new(
            command,
            args.to_vec(),
            "Subprocess spawning is forbidden by active CLMContext process policy",
        ))
    }
}

thread_local! {
    static THREAD_CONTEXT_STACK: RefCell<Vec<CLMContext>> = const { RefCell::new(Vec::new()) };
}

pub struct CLMContextScopeGuard;

impl Drop for CLMContextScopeGuard {
    fn drop(&mut self) {
        THREAD_CONTEXT_STACK.with(|stack| {
            stack.borrow_mut().pop();
        });
    }
}

#[derive(Debug, Clone, Default)]
pub struct CLMContextOverrides {
    pub project_root: Option<PathBuf>,
    pub db_dir: Option<PathBuf>,
    pub runtime: Option<String>,
    pub agent_did: Option<String>,
    pub sponsor_did: Option<String>,
    pub execution_locale_hash: Option<String>,
    pub hash_algo: Option<String>,
    pub zero_fs: Option<bool>,
    pub forbid_subprocess: Option<bool>,
    pub target_file: Option<PathBuf>,
    pub run_id: Option<String>,
    pub nested_exec: Option<bool>,
    pub scoped_vars: HashMap<String, String>,
    pub masked_vars: HashSet<String>,
    pub process_spawner: Option<Arc<dyn ProcessSpawner>>,
}

#[derive(Debug, Clone)]
struct CLMContextInner {
    project_root: Option<PathBuf>,
    db_dir: PathBuf,
    runtime: String,
    agent_did: String,
    sponsor_did: Option<String>,
    execution_locale_hash: String,
    hash_algo: String,
    zero_fs: bool,
    forbid_subprocess: bool,
    target_file: Option<PathBuf>,
    run_id: Option<String>,
    nested_exec: bool,
    scoped_vars: HashMap<String, String>,
    masked_vars: HashSet<String>,
    process_spawner: Option<Arc<dyn ProcessSpawner>>,
}

/// Thread-safe, copy-on-write execution configuration snapshot (`INV-490`).
#[derive(Debug, Clone)]
pub struct CLMContext {
    inner: Arc<CLMContextInner>,
}

/// Deprecated compatibility alias for `CLMContext` (`DoD-490-06`).
pub type EvaluationContext = CLMContext;

fn parse_bool(val: &str) -> bool {
    matches!(
        val.trim().to_ascii_lowercase().as_str(),
        "1" | "true" | "yes" | "on"
    )
}

impl Default for CLMContext {
    fn default() -> Self {
        Self::for_test_sandbox()
    }
}

impl CLMContext {
    pub fn new() -> Self {
        Self::for_test_sandbox()
    }

    /// Construct a deterministic test-sandbox context with zero host-environment reads.
    pub fn for_test_sandbox() -> Self {
        let empty: HashMap<String, String> = HashMap::new();
        Self::from_process_environment(&empty)
    }

    /// Capture and normalize an explicit environment snapshot at the CLI/process boundary.
    pub fn from_process_environment(snapshot: &HashMap<String, String>) -> Self {
        let project_root = resolve_env_from_map(ClmEnvVar::Root, snapshot)
            .filter(|s| !s.is_empty())
            .map(PathBuf::from);
        let db_dir_str = resolve_env_from_map(ClmEnvVar::DbDir, snapshot)
            .unwrap_or_else(|| ClmEnvVar::DbDir.default_value().to_string());
        let db_dir = match &project_root {
            Some(root) if !Path::new(&db_dir_str).is_absolute() => root.join(&db_dir_str),
            _ => PathBuf::from(&db_dir_str),
        };
        let runtime = resolve_env_from_map(ClmEnvVar::Runtime, snapshot)
            .unwrap_or_else(|| ClmEnvVar::Runtime.default_value().to_string());
        let agent_did = resolve_env_from_map(ClmEnvVar::AgentDid, snapshot)
            .unwrap_or_else(|| ClmEnvVar::AgentDid.default_value().to_string());
        let sponsor_did =
            resolve_env_from_map(ClmEnvVar::SponsorDid, snapshot).filter(|s| !s.is_empty());
        let execution_locale_hash =
            resolve_env_from_map(ClmEnvVar::ExecutionLocaleHash, snapshot)
                .unwrap_or_else(|| ClmEnvVar::ExecutionLocaleHash.default_value().to_string());
        let hash_algo = resolve_env_from_map(ClmEnvVar::HashAlgo, snapshot)
            .unwrap_or_else(|| ClmEnvVar::HashAlgo.default_value().to_string());
        let zero_fs = resolve_env_from_map(ClmEnvVar::ZeroFs, snapshot)
            .map(|v| parse_bool(&v))
            .unwrap_or(false);
        let forbid_subprocess = resolve_env_from_map(ClmEnvVar::ForbidSubprocess, snapshot)
            .map(|v| parse_bool(&v))
            .unwrap_or(false);
        let target_file = resolve_env_from_map(ClmEnvVar::TargetFile, snapshot)
            .filter(|s| !s.is_empty())
            .map(PathBuf::from);
        let run_id = resolve_env_from_map(ClmEnvVar::RunId, snapshot).filter(|s| !s.is_empty());
        let nested_exec = snapshot
            .get("CLM_NESTED_EXEC")
            .map(|v| parse_bool(v))
            .unwrap_or(false);

        let mut scoped_vars = HashMap::new();
        for key in ENV_PASSTHROUGH_WHITELIST {
            if let Some(val) = snapshot.get(*key) {
                if !val.is_empty() {
                    scoped_vars.insert((*key).to_string(), val.clone());
                }
            }
        }
        for (k, v) in snapshot {
            if k.starts_with("CLM_MOCK_") {
                scoped_vars.insert(k.clone(), v.clone());
            }
        }

        Self {
            inner: Arc::new(CLMContextInner {
                project_root,
                db_dir,
                runtime,
                agent_did,
                sponsor_did,
                execution_locale_hash,
                hash_algo,
                zero_fs,
                forbid_subprocess,
                target_file,
                run_id,
                nested_exec,
                scoped_vars,
                masked_vars: HashSet::new(),
                process_spawner: None,
            }),
        }
    }

    /// Return the active thread-local `CLMContext` or construct one from allowlisted process env keys.
    pub fn current() -> Self {
        if let Some(ctx) = THREAD_CONTEXT_STACK.with(|stack| stack.borrow().last().cloned()) {
            return ctx;
        }
        let mut snap = HashMap::new();
        for key in ENV_PASSTHROUGH_WHITELIST {
            if let Ok(val) = std::env::var(key) {
                snap.insert((*key).to_string(), val);
            }
        }
        Self::from_process_environment(&snap)
    }

    /// Push `self` onto the thread-local context stack until the returned guard is dropped.
    pub fn enter_scope(&self) -> CLMContextScopeGuard {
        THREAD_CONTEXT_STACK.with(|stack| {
            stack.borrow_mut().push(self.clone());
        });
        CLMContextScopeGuard
    }

    /// Read `key` from the active thread-local `CLMContext` first, falling back to `std::env::var`.
    pub fn get_scoped_or_env(key: &str) -> Option<String> {
        let from_stack = THREAD_CONTEXT_STACK.with(|stack| {
            let borrowed = stack.borrow();
            if let Some(top) = borrowed.last() {
                if top.inner.masked_vars.contains(key) {
                    return Some(None);
                }
                if let Some(val) = top.inner.scoped_vars.get(key) {
                    return Some(Some(val.clone()));
                }
            }
            None
        });
        match from_stack {
            Some(res) => res,
            None => std::env::var(key).ok(),
        }
    }

    /// Apply any active thread-local `CLMContext` scoped overrides/masks to a child `Command`.
    pub fn apply_current_to_command(cmd: &mut std::process::Command) {
        THREAD_CONTEXT_STACK.with(|stack| {
            if let Some(top) = stack.borrow().last() {
                for masked in &top.inner.masked_vars {
                    cmd.env_remove(masked);
                }
                for (k, v) in &top.inner.scoped_vars {
                    cmd.env(k, v);
                }
            }
        });
    }

    /// Create an isolated child context with copy-on-write overrides; parent remains immutable.
    pub fn with_child_scope(&self, overrides: CLMContextOverrides) -> Self {
        let mut next = (*self.inner).clone();
        if let Some(root) = overrides.project_root {
            next.project_root = Some(root);
        }
        if let Some(db_dir) = overrides.db_dir {
            next.db_dir = db_dir;
        }
        if let Some(rt) = overrides.runtime {
            next.runtime = rt.clone();
            next.scoped_vars.insert("CLM_RUNTIME".to_string(), rt);
        }
        if let Some(did) = overrides.agent_did {
            next.agent_did = did.clone();
            next.scoped_vars.insert("CLM_AGENT_DID".to_string(), did);
        }
        if let Some(sponsor) = overrides.sponsor_did {
            next.sponsor_did = Some(sponsor.clone());
            next.scoped_vars
                .insert("CLM_SPONSOR_DID".to_string(), sponsor);
        }
        if let Some(locale) = overrides.execution_locale_hash {
            next.execution_locale_hash = locale.clone();
            next.scoped_vars
                .insert("CLM_EXECUTION_LOCALE_HASH".to_string(), locale);
        }
        if let Some(algo) = overrides.hash_algo {
            next.hash_algo = algo.clone();
            next.scoped_vars.insert("CLM_HASH_ALGO".to_string(), algo);
        }
        if let Some(zfs) = overrides.zero_fs {
            next.zero_fs = zfs;
            next.scoped_vars.insert(
                "CLM_ZERO_FS".to_string(),
                if zfs { "true" } else { "false" }.to_string(),
            );
        }
        if let Some(forbid) = overrides.forbid_subprocess {
            next.forbid_subprocess = forbid;
            next.scoped_vars.insert(
                "CLM_FORBID_SUBPROCESS".to_string(),
                if forbid { "true" } else { "false" }.to_string(),
            );
        }
        if let Some(tf) = overrides.target_file {
            next.scoped_vars.insert(
                "CLM_TARGET_FILE".to_string(),
                tf.to_string_lossy().to_string(),
            );
            next.target_file = Some(tf);
        }
        if let Some(rid) = overrides.run_id {
            next.run_id = Some(rid.clone());
            next.scoped_vars.insert("CLM_RUN_ID".to_string(), rid);
        }
        if let Some(nested) = overrides.nested_exec {
            next.nested_exec = nested;
            if nested {
                next.masked_vars.remove("CLM_NESTED_EXEC");
                next.scoped_vars
                    .insert("CLM_NESTED_EXEC".to_string(), "1".to_string());
            } else {
                next.scoped_vars.remove("CLM_NESTED_EXEC");
                next.masked_vars.insert("CLM_NESTED_EXEC".to_string());
            }
        }
        if let Some(spawner) = overrides.process_spawner {
            next.process_spawner = Some(spawner);
        }
        for m in overrides.masked_vars {
            next.scoped_vars.remove(&m);
            next.masked_vars.insert(m);
        }
        for (k, v) in overrides.scoped_vars {
            next.masked_vars.remove(&k);
            next.scoped_vars.insert(k, v);
        }
        Self {
            inner: Arc::new(next),
        }
    }

}

#[path = "context_accessors.rs"]
mod context_accessors;
#[allow(unused_imports)]
pub use context_accessors::*;

#[cfg(test)]
#[path = "context_tests.rs"]
mod tests;