clm-kernel 0.0.23

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Cordis Context and Fiber State Machine.
//!
//! Enforces:
//! 1. The Empty Root Context (⊥)
//! 2. 5-State Fiber Lifecycle (PENDING ➔ LOADING ➔ ACTIVE ➔ UNLOADING ➔ DISPOSED)
//! 3. Demand-Driven Coeffects (@Inject)
//! 4. Scoped Monadic Contexts & Algebraic Sub-Graph Isolation (ctx.user, ctx.channel, ctx.isolate)

use super::disposable::DisposableList;
use dashmap::DashMap;
use std::any::Any;
use std::collections::HashSet;
use std::sync::{Arc, Mutex};

/// Lifecycle states of a Cordis Fiber: the five canonical states
/// (Pending, Loading, Active, Unloading, Disposed) plus Rust extensions
/// (Paused, Suspended, Failed) — see cordis-spatiotemporal doc §2.3.1.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FiberState {
    /// Waiting for declared coeffect dependencies to be satisfied.
    Pending,
    /// Dependencies satisfied; mounting plugins and initializing effects.
    Loading,
    /// Active, fully verified, and ready to serve tasks/transitions.
    Active,
    /// Temporarily paused for Hot Module Replacement (HMR) or inspection.
    Paused,
    /// Suspended awaiting a delimited continuation or external input.
    Suspended,
    /// In the process of executing DisposableList in LIFO order.
    Unloading,
    /// Cleanly terminated with zero residual state and zero leaked resources.
    Disposed,
    /// Transition or invariant evaluation failed; quarantined.
    Failed(String),
}

/// A Cordis execution Fiber representing an isolated plugin, agent task, or service.
pub struct Fiber {
    pub id: String,
    pub state: Mutex<FiberState>,
    pub required_coeffects: HashSet<String>,
    pub satisfied_coeffects: Mutex<HashSet<String>>,
    pub disposables: Mutex<DisposableList>,
    pub clm_ast: Mutex<Option<serde_json::Value>>,
}

impl Fiber {
    pub fn new(id: impl Into<String>, required_coeffects: Vec<String>) -> Self {
        let coeffects_set: HashSet<String> = required_coeffects.into_iter().collect();
        let initial_state = if coeffects_set.is_empty() {
            FiberState::Active
        } else {
            FiberState::Pending
        };

        Self {
            id: id.into(),
            state: Mutex::new(initial_state),
            required_coeffects: coeffects_set,
            satisfied_coeffects: Mutex::new(HashSet::new()),
            disposables: Mutex::new(DisposableList::new()),
            clm_ast: Mutex::new(None),
        }
    }

    /// Checks if all declared coeffects are satisfied and transitions to ACTIVE.
    pub fn try_activate(&self) -> bool {
        let mut state = self.state.lock().unwrap();
        if *state != FiberState::Pending && *state != FiberState::Loading {
            return *state == FiberState::Active;
        }

        let satisfied = self.satisfied_coeffects.lock().unwrap();
        if self.required_coeffects.is_subset(&satisfied) {
            *state = FiberState::Active;
            true
        } else {
            false
        }
    }

    /// Satisfies a specific coeffect requirement.
    pub fn satisfy_coeffect(&self, coeffect: &str) -> bool {
        {
            let mut satisfied = self.satisfied_coeffects.lock().unwrap();
            satisfied.insert(coeffect.to_string());
        }
        self.try_activate()
    }

    /// Registers a reversible cleanup effect with this fiber.
    pub fn register_disposable<F>(&self, cleanup: F)
    where
        F: FnOnce() -> Result<(), String> + Send + 'static,
    {
        let mut disp = self.disposables.lock().unwrap();
        disp.push(cleanup);
    }

    /// Explicitly transitions the Fiber to a new state.
    pub fn transition_to(&self, new_state: FiberState) -> Result<(), String> {
        let mut state = self.state.lock().unwrap();
        *state = new_state;
        Ok(())
    }

    /// Returns the current lifecycle state of the Fiber.
    pub fn get_state(&self) -> FiberState {
        self.state.lock().unwrap().clone()
    }

    /// Pauses the fiber execution, preparing for HMR or state snapshot.
    pub fn pause(&self) -> Result<(), String> {
        let mut state = self.state.lock().unwrap();
        *state = FiberState::Paused;
        Ok(())
    }

    /// Activates or resumes the fiber.
    pub fn activate(&self) -> Result<(), String> {
        let mut state = self.state.lock().unwrap();
        *state = FiberState::Active;
        Ok(())
    }

    /// Suspends the fiber execution awaiting a delimited continuation.
    pub fn suspend(&self) -> Result<(), String> {
        let mut state = self.state.lock().unwrap();
        *state = FiberState::Suspended;
        Ok(())
    }

    /// Resumes the fiber execution from suspended state back to Active.
    pub fn resume(&self) -> Result<(), String> {
        let mut state = self.state.lock().unwrap();
        *state = FiberState::Active;
        Ok(())
    }

    /// Unwinds disposables in LIFO order without setting Disposed state.
    pub fn unwind_disposables(&self) -> Result<(), Vec<String>> {
        let disposers = {
            let mut disp = self.disposables.lock().unwrap();
            std::mem::take(&mut *disp)
        };
        disposers.dispose()
    }

    /// Stores the CLM AST in this fiber.
    pub fn set_ast(&self, ast: serde_json::Value) {
        let mut clm = self.clm_ast.lock().unwrap();
        *clm = Some(ast);
    }

    /// Retrieves the stored CLM AST if present.
    pub fn get_ast(&self) -> Option<serde_json::Value> {
        self.clm_ast.lock().unwrap().clone()
    }

    /// Transitions the Fiber to DISPOSED, executing all disposables in strict LIFO order.
    pub fn dispose(&self) -> Result<(), Vec<String>> {
        {
            let mut state = self.state.lock().unwrap();
            *state = FiberState::Unloading;
        }

        let disposers = {
            let mut disp = self.disposables.lock().unwrap();
            std::mem::take(&mut *disp)
        };

        let result = disposers.dispose();

        {
            let mut state = self.state.lock().unwrap();
            if result.is_ok() {
                *state = FiberState::Disposed;
            } else {
                *state = FiberState::Failed("Disposal errors encountered".to_string());
            }
        }

        result
    }
}

/// A Scoped Monadic Context for Cordis plugin execution.
#[derive(Clone)]
pub struct Context {
    pub scope_id: String,
    pub services: Arc<DashMap<String, Arc<dyn Any + Send + Sync>>>,
    pub fibers: Arc<DashMap<String, Arc<Fiber>>>,
}

impl Context {
    /// Creates the sovereign Empty Root Context (⊥) with zero privileged state.
    pub fn root() -> Self {
        Self {
            scope_id: "root".to_string(),
            services: Arc::new(DashMap::new()),
            fibers: Arc::new(DashMap::new()),
        }
    }

    /// Creates a scoped child context partitioned by user identity (Tenant Isolation).
    pub fn user(&self, did: &str) -> Self {
        Self {
            scope_id: format!("{}/user:{}", self.scope_id, did),
            services: self.services.clone(),
            fibers: self.fibers.clone(),
        }
    }

    /// Creates a scoped child context partitioned by communication channel or session.
    pub fn channel(&self, channel_id: &str) -> Self {
        Self {
            scope_id: format!("{}/channel:{}", self.scope_id, channel_id),
            services: self.services.clone(),
            fibers: self.fibers.clone(),
        }
    }

    /// Creates an isolated child sandbox with only the declared coeffects exposed.
    pub fn isolate(&self, allowed_coeffects: &[&str]) -> Self {
        let isolated_services = Arc::new(DashMap::new());
        let allowed_set: HashSet<&str> = allowed_coeffects.iter().copied().collect();

        for entry in self.services.iter() {
            if allowed_set.contains(entry.key().as_str()) {
                isolated_services.insert(entry.key().clone(), entry.value().clone());
            }
        }

        Self {
            scope_id: format!("{}/isolate:{}", self.scope_id, uuid_or_random()),
            services: isolated_services,
            fibers: Arc::new(DashMap::new()),
        }
    }

    /// Creates a masked child context with specific capabilities stripped.
    pub fn mask(&self, denied_coeffects: &[&str]) -> Self {
        let masked_services = Arc::new(DashMap::new());
        let denied_set: HashSet<&str> = denied_coeffects.iter().copied().collect();

        for entry in self.services.iter() {
            if !denied_set.contains(entry.key().as_str()) {
                masked_services.insert(entry.key().clone(), entry.value().clone());
            }
        }

        Self {
            scope_id: format!("{}/mask:{}", self.scope_id, uuid_or_random()),
            services: masked_services,
            fibers: Arc::new(DashMap::new()),
        }
    }

    /// Checks whether a specific coeffect capability is present in this context scope.
    pub fn require(&self, coeffect: &str) -> bool {
        self.services.contains_key(coeffect)
    }

    /// Provides a service capability into the context registry (alias for register_service).
    pub fn provide<T: Send + Sync + 'static>(&self, name: &str, service: T) {
        self.register_service(name, service);
    }

    /// Registers a service capability into the context registry.
    pub fn register_service<T: Send + Sync + 'static>(&self, name: &str, service: T) {
        self.services.insert(name.to_string(), Arc::new(service));

        // Notify any pending fibers that this coeffect is now available
        for fiber in self.fibers.iter() {
            if fiber.required_coeffects.contains(name) {
                fiber.satisfy_coeffect(name);
            }
        }
    }

    /// Retrieves a typed service capability from the registry.
    pub fn get_service<T: Send + Sync + 'static>(&self, name: &str) -> Option<Arc<T>> {
        self.services
            .get(name)
            .and_then(|any_arc| any_arc.clone().downcast::<T>().ok())
    }

    /// Mounts an MCard virtual filesystem into this context scope as a reactive coeffect (Sprint 191).
    #[cfg(any(feature = "native", feature = "db"))]
    pub fn mount_mcard_fs(&self, fs: crate::mcard_fs::MCardFileSystem) {
        self.provide("mcard_fs", fs);
    }

    /// Retrieves the mounted MCard virtual filesystem if available.
    #[cfg(any(feature = "native", feature = "db"))]
    pub fn mcard_fs(&self) -> Option<Arc<crate::mcard_fs::MCardFileSystem>> {
        self.get_service::<crate::mcard_fs::MCardFileSystem>("mcard_fs")
    }

    /// Ephemerally mounts an MCard virtual filesystem scoped to `prefix` on a Fiber,
    /// registering LIFO cleanup on the fiber's DisposableList.
    #[cfg(any(feature = "native", feature = "db"))]
    pub fn mount_ephemeral_mcard_fs(
        &self,
        fiber_id: &str,
        prefix: &str,
    ) -> Result<crate::mcard_fs::MCardFileSystem, String> {
        let fs = self.mcard_fs().ok_or_else(|| "mcard_fs service not mounted in context".to_string())?;
        let fiber = self.get_fiber(fiber_id).ok_or_else(|| format!("fiber '{}' not found", fiber_id))?;
        fs.ephemeral_mount(&fiber, prefix)
            .map_err(|e| e.to_string())
    }

    /// Instantiates and registers a new Fiber within this context.
    pub fn spawn_fiber(&self, id: &str, required_coeffects: Vec<String>) -> Arc<Fiber> {
        let fiber = Arc::new(Fiber::new(id, required_coeffects));

        // Immediately satisfy any coeffects that already exist in this context
        for coeffect in &fiber.required_coeffects {
            if self.services.contains_key(coeffect) {
                fiber.satisfy_coeffect(coeffect);
            }
        }

        self.fibers.insert(id.to_string(), fiber.clone());
        fiber
    }

    /// Looks up an active fiber by id.
    pub fn get_fiber(&self, id: &str) -> Option<Arc<Fiber>> {
        self.fibers.get(id).map(|f| f.clone())
    }

    /// Lists all active fibers in this context.
    pub fn list_fibers(&self) -> Vec<Arc<Fiber>> {
        self.fibers.iter().map(|entry| entry.value().clone()).collect()
    }

    /// Creates and registers a new Fiber within this context.
    pub fn create_fiber(&self, id: &str, required_coeffects: Vec<String>) -> Result<Arc<Fiber>, String> {
        Ok(self.spawn_fiber(id, required_coeffects))
    }

    /// Removes an active fiber from the registry.
    pub fn remove_fiber(&self, id: &str) -> Option<Arc<Fiber>> {
        self.fibers.remove(id).map(|(_, f)| f)
    }

    /// Disposes all fibers associated with this context scope.
    pub fn dispose(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();
        for fiber in self.fibers.iter() {
            if let Err(mut e) = fiber.dispose() {
                errors.append(&mut e);
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

fn uuid_or_random() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    format!("{:x}", nanos)
}

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