Skip to main content

clm_rust_core/fiber/
context.rs

1//! Cordis Context and Fiber State Machine.
2//!
3//! Enforces:
4//! 1. The Empty Root Context (⊥)
5//! 2. 5-State Fiber Lifecycle (PENDING ➔ LOADING ➔ ACTIVE ➔ UNLOADING ➔ DISPOSED)
6//! 3. Demand-Driven Coeffects (@Inject)
7//! 4. Scoped Monadic Contexts & Algebraic Sub-Graph Isolation (ctx.user, ctx.channel, ctx.isolate)
8
9use super::disposable::DisposableList;
10use dashmap::DashMap;
11use std::any::Any;
12use std::collections::HashSet;
13use std::sync::{Arc, Mutex};
14
15/// Lifecycle states of a Cordis Fiber: the five canonical states
16/// (Pending, Loading, Active, Unloading, Disposed) plus Rust extensions
17/// (Paused, Suspended, Failed) — see cordis-spatiotemporal doc §2.3.1.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum FiberState {
20    /// Waiting for declared coeffect dependencies to be satisfied.
21    Pending,
22    /// Dependencies satisfied; mounting plugins and initializing effects.
23    Loading,
24    /// Active, fully verified, and ready to serve tasks/transitions.
25    Active,
26    /// Temporarily paused for Hot Module Replacement (HMR) or inspection.
27    Paused,
28    /// Suspended awaiting a delimited continuation or external input.
29    Suspended,
30    /// In the process of executing DisposableList in LIFO order.
31    Unloading,
32    /// Cleanly terminated with zero residual state and zero leaked resources.
33    Disposed,
34    /// Transition or invariant evaluation failed; quarantined.
35    Failed(String),
36}
37
38/// A Cordis execution Fiber representing an isolated plugin, agent task, or service.
39pub struct Fiber {
40    pub id: String,
41    pub state: Mutex<FiberState>,
42    pub required_coeffects: HashSet<String>,
43    pub satisfied_coeffects: Mutex<HashSet<String>>,
44    pub disposables: Mutex<DisposableList>,
45    pub clm_ast: Mutex<Option<serde_json::Value>>,
46}
47
48impl Fiber {
49    pub fn new(id: impl Into<String>, required_coeffects: Vec<String>) -> Self {
50        let coeffects_set: HashSet<String> = required_coeffects.into_iter().collect();
51        let initial_state = if coeffects_set.is_empty() {
52            FiberState::Active
53        } else {
54            FiberState::Pending
55        };
56
57        Self {
58            id: id.into(),
59            state: Mutex::new(initial_state),
60            required_coeffects: coeffects_set,
61            satisfied_coeffects: Mutex::new(HashSet::new()),
62            disposables: Mutex::new(DisposableList::new()),
63            clm_ast: Mutex::new(None),
64        }
65    }
66
67    /// Checks if all declared coeffects are satisfied and transitions to ACTIVE.
68    pub fn try_activate(&self) -> bool {
69        let mut state = self.state.lock().unwrap();
70        if *state != FiberState::Pending && *state != FiberState::Loading {
71            return *state == FiberState::Active;
72        }
73
74        let satisfied = self.satisfied_coeffects.lock().unwrap();
75        if self.required_coeffects.is_subset(&satisfied) {
76            *state = FiberState::Active;
77            true
78        } else {
79            false
80        }
81    }
82
83    /// Satisfies a specific coeffect requirement.
84    pub fn satisfy_coeffect(&self, coeffect: &str) -> bool {
85        {
86            let mut satisfied = self.satisfied_coeffects.lock().unwrap();
87            satisfied.insert(coeffect.to_string());
88        }
89        self.try_activate()
90    }
91
92    /// Registers a reversible cleanup effect with this fiber.
93    pub fn register_disposable<F>(&self, cleanup: F)
94    where
95        F: FnOnce() -> Result<(), String> + Send + 'static,
96    {
97        let mut disp = self.disposables.lock().unwrap();
98        disp.push(cleanup);
99    }
100
101    /// Explicitly transitions the Fiber to a new state.
102    pub fn transition_to(&self, new_state: FiberState) -> Result<(), String> {
103        let mut state = self.state.lock().unwrap();
104        *state = new_state;
105        Ok(())
106    }
107
108    /// Returns the current lifecycle state of the Fiber.
109    pub fn get_state(&self) -> FiberState {
110        self.state.lock().unwrap().clone()
111    }
112
113    /// Pauses the fiber execution, preparing for HMR or state snapshot.
114    pub fn pause(&self) -> Result<(), String> {
115        let mut state = self.state.lock().unwrap();
116        *state = FiberState::Paused;
117        Ok(())
118    }
119
120    /// Activates or resumes the fiber.
121    pub fn activate(&self) -> Result<(), String> {
122        let mut state = self.state.lock().unwrap();
123        *state = FiberState::Active;
124        Ok(())
125    }
126
127    /// Suspends the fiber execution awaiting a delimited continuation.
128    pub fn suspend(&self) -> Result<(), String> {
129        let mut state = self.state.lock().unwrap();
130        *state = FiberState::Suspended;
131        Ok(())
132    }
133
134    /// Resumes the fiber execution from suspended state back to Active.
135    pub fn resume(&self) -> Result<(), String> {
136        let mut state = self.state.lock().unwrap();
137        *state = FiberState::Active;
138        Ok(())
139    }
140
141    /// Unwinds disposables in LIFO order without setting Disposed state.
142    pub fn unwind_disposables(&self) -> Result<(), Vec<String>> {
143        let disposers = {
144            let mut disp = self.disposables.lock().unwrap();
145            std::mem::take(&mut *disp)
146        };
147        disposers.dispose()
148    }
149
150    /// Stores the CLM AST in this fiber.
151    pub fn set_ast(&self, ast: serde_json::Value) {
152        let mut clm = self.clm_ast.lock().unwrap();
153        *clm = Some(ast);
154    }
155
156    /// Retrieves the stored CLM AST if present.
157    pub fn get_ast(&self) -> Option<serde_json::Value> {
158        self.clm_ast.lock().unwrap().clone()
159    }
160
161    /// Transitions the Fiber to DISPOSED, executing all disposables in strict LIFO order.
162    pub fn dispose(&self) -> Result<(), Vec<String>> {
163        {
164            let mut state = self.state.lock().unwrap();
165            *state = FiberState::Unloading;
166        }
167
168        let disposers = {
169            let mut disp = self.disposables.lock().unwrap();
170            std::mem::take(&mut *disp)
171        };
172
173        let result = disposers.dispose();
174
175        {
176            let mut state = self.state.lock().unwrap();
177            if result.is_ok() {
178                *state = FiberState::Disposed;
179            } else {
180                *state = FiberState::Failed("Disposal errors encountered".to_string());
181            }
182        }
183
184        result
185    }
186}
187
188/// A Scoped Monadic Context for Cordis plugin execution.
189#[derive(Clone)]
190pub struct Context {
191    pub scope_id: String,
192    pub services: Arc<DashMap<String, Arc<dyn Any + Send + Sync>>>,
193    pub fibers: Arc<DashMap<String, Arc<Fiber>>>,
194}
195
196impl Context {
197    /// Creates the sovereign Empty Root Context (⊥) with zero privileged state.
198    pub fn root() -> Self {
199        Self {
200            scope_id: "root".to_string(),
201            services: Arc::new(DashMap::new()),
202            fibers: Arc::new(DashMap::new()),
203        }
204    }
205
206    /// Creates a scoped child context partitioned by user identity (Tenant Isolation).
207    pub fn user(&self, did: &str) -> Self {
208        Self {
209            scope_id: format!("{}/user:{}", self.scope_id, did),
210            services: self.services.clone(),
211            fibers: self.fibers.clone(),
212        }
213    }
214
215    /// Creates a scoped child context partitioned by communication channel or session.
216    pub fn channel(&self, channel_id: &str) -> Self {
217        Self {
218            scope_id: format!("{}/channel:{}", self.scope_id, channel_id),
219            services: self.services.clone(),
220            fibers: self.fibers.clone(),
221        }
222    }
223
224    /// Creates an isolated child sandbox with only the declared coeffects exposed.
225    pub fn isolate(&self, allowed_coeffects: &[&str]) -> Self {
226        let isolated_services = Arc::new(DashMap::new());
227        let allowed_set: HashSet<&str> = allowed_coeffects.iter().copied().collect();
228
229        for entry in self.services.iter() {
230            if allowed_set.contains(entry.key().as_str()) {
231                isolated_services.insert(entry.key().clone(), entry.value().clone());
232            }
233        }
234
235        Self {
236            scope_id: format!("{}/isolate:{}", self.scope_id, uuid_or_random()),
237            services: isolated_services,
238            fibers: Arc::new(DashMap::new()),
239        }
240    }
241
242    /// Creates a masked child context with specific capabilities stripped.
243    pub fn mask(&self, denied_coeffects: &[&str]) -> Self {
244        let masked_services = Arc::new(DashMap::new());
245        let denied_set: HashSet<&str> = denied_coeffects.iter().copied().collect();
246
247        for entry in self.services.iter() {
248            if !denied_set.contains(entry.key().as_str()) {
249                masked_services.insert(entry.key().clone(), entry.value().clone());
250            }
251        }
252
253        Self {
254            scope_id: format!("{}/mask:{}", self.scope_id, uuid_or_random()),
255            services: masked_services,
256            fibers: Arc::new(DashMap::new()),
257        }
258    }
259
260    /// Checks whether a specific coeffect capability is present in this context scope.
261    pub fn require(&self, coeffect: &str) -> bool {
262        self.services.contains_key(coeffect)
263    }
264
265    /// Provides a service capability into the context registry (alias for register_service).
266    pub fn provide<T: Send + Sync + 'static>(&self, name: &str, service: T) {
267        self.register_service(name, service);
268    }
269
270    /// Registers a service capability into the context registry.
271    pub fn register_service<T: Send + Sync + 'static>(&self, name: &str, service: T) {
272        self.services.insert(name.to_string(), Arc::new(service));
273
274        // Notify any pending fibers that this coeffect is now available
275        for fiber in self.fibers.iter() {
276            if fiber.required_coeffects.contains(name) {
277                fiber.satisfy_coeffect(name);
278            }
279        }
280    }
281
282    /// Retrieves a typed service capability from the registry.
283    pub fn get_service<T: Send + Sync + 'static>(&self, name: &str) -> Option<Arc<T>> {
284        self.services
285            .get(name)
286            .and_then(|any_arc| any_arc.clone().downcast::<T>().ok())
287    }
288
289    /// Mounts an MCard virtual filesystem into this context scope as a reactive coeffect (Sprint 191).
290    #[cfg(any(feature = "native", feature = "db"))]
291    pub fn mount_mcard_fs(&self, fs: crate::mcard_fs::MCardFileSystem) {
292        self.provide("mcard_fs", fs);
293    }
294
295    /// Retrieves the mounted MCard virtual filesystem if available.
296    #[cfg(any(feature = "native", feature = "db"))]
297    pub fn mcard_fs(&self) -> Option<Arc<crate::mcard_fs::MCardFileSystem>> {
298        self.get_service::<crate::mcard_fs::MCardFileSystem>("mcard_fs")
299    }
300
301    /// Ephemerally mounts an MCard virtual filesystem scoped to `prefix` on a Fiber,
302    /// registering LIFO cleanup on the fiber's DisposableList.
303    #[cfg(any(feature = "native", feature = "db"))]
304    pub fn mount_ephemeral_mcard_fs(
305        &self,
306        fiber_id: &str,
307        prefix: &str,
308    ) -> Result<crate::mcard_fs::MCardFileSystem, String> {
309        let fs = self.mcard_fs().ok_or_else(|| "mcard_fs service not mounted in context".to_string())?;
310        let fiber = self.get_fiber(fiber_id).ok_or_else(|| format!("fiber '{}' not found", fiber_id))?;
311        fs.ephemeral_mount(&fiber, prefix)
312            .map_err(|e| e.to_string())
313    }
314
315    /// Instantiates and registers a new Fiber within this context.
316    pub fn spawn_fiber(&self, id: &str, required_coeffects: Vec<String>) -> Arc<Fiber> {
317        let fiber = Arc::new(Fiber::new(id, required_coeffects));
318
319        // Immediately satisfy any coeffects that already exist in this context
320        for coeffect in &fiber.required_coeffects {
321            if self.services.contains_key(coeffect) {
322                fiber.satisfy_coeffect(coeffect);
323            }
324        }
325
326        self.fibers.insert(id.to_string(), fiber.clone());
327        fiber
328    }
329
330    /// Looks up an active fiber by id.
331    pub fn get_fiber(&self, id: &str) -> Option<Arc<Fiber>> {
332        self.fibers.get(id).map(|f| f.clone())
333    }
334
335    /// Lists all active fibers in this context.
336    pub fn list_fibers(&self) -> Vec<Arc<Fiber>> {
337        self.fibers.iter().map(|entry| entry.value().clone()).collect()
338    }
339
340    /// Creates and registers a new Fiber within this context.
341    pub fn create_fiber(&self, id: &str, required_coeffects: Vec<String>) -> Result<Arc<Fiber>, String> {
342        Ok(self.spawn_fiber(id, required_coeffects))
343    }
344
345    /// Removes an active fiber from the registry.
346    pub fn remove_fiber(&self, id: &str) -> Option<Arc<Fiber>> {
347        self.fibers.remove(id).map(|(_, f)| f)
348    }
349
350    /// Disposes all fibers associated with this context scope.
351    pub fn dispose(&self) -> Result<(), Vec<String>> {
352        let mut errors = Vec::new();
353        for fiber in self.fibers.iter() {
354            if let Err(mut e) = fiber.dispose() {
355                errors.append(&mut e);
356            }
357        }
358        if errors.is_empty() {
359            Ok(())
360        } else {
361            Err(errors)
362        }
363    }
364}
365
366fn uuid_or_random() -> String {
367    use std::time::{SystemTime, UNIX_EPOCH};
368    let nanos = SystemTime::now()
369        .duration_since(UNIX_EPOCH)
370        .map(|d| d.as_nanos())
371        .unwrap_or(0);
372    format!("{:x}", nanos)
373}
374
375#[cfg(test)]
376#[path = "context_tests.rs"]
377mod tests;