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/// The five canonical lifecycle states of a Cordis Fiber.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum FiberState {
18    /// Waiting for declared coeffect dependencies to be satisfied.
19    Pending,
20    /// Dependencies satisfied; mounting plugins and initializing effects.
21    Loading,
22    /// Active, fully verified, and ready to serve tasks/transitions.
23    Active,
24    /// Temporarily paused for Hot Module Replacement (HMR) or inspection.
25    Paused,
26    /// Suspended awaiting a delimited continuation or external input.
27    Suspended,
28    /// In the process of executing DisposableList in LIFO order.
29    Unloading,
30    /// Cleanly terminated with zero residual state and zero leaked resources.
31    Disposed,
32    /// Transition or invariant evaluation failed; quarantined.
33    Failed(String),
34}
35
36/// A Cordis execution Fiber representing an isolated plugin, agent task, or service.
37pub struct Fiber {
38    pub id: String,
39    pub state: Mutex<FiberState>,
40    pub required_coeffects: HashSet<String>,
41    pub satisfied_coeffects: Mutex<HashSet<String>>,
42    pub disposables: Mutex<DisposableList>,
43    pub clm_ast: Mutex<Option<serde_json::Value>>,
44}
45
46impl Fiber {
47    pub fn new(id: impl Into<String>, required_coeffects: Vec<String>) -> Self {
48        let coeffects_set: HashSet<String> = required_coeffects.into_iter().collect();
49        let initial_state = if coeffects_set.is_empty() {
50            FiberState::Active
51        } else {
52            FiberState::Pending
53        };
54
55        Self {
56            id: id.into(),
57            state: Mutex::new(initial_state),
58            required_coeffects: coeffects_set,
59            satisfied_coeffects: Mutex::new(HashSet::new()),
60            disposables: Mutex::new(DisposableList::new()),
61            clm_ast: Mutex::new(None),
62        }
63    }
64
65    /// Checks if all declared coeffects are satisfied and transitions to ACTIVE.
66    pub fn try_activate(&self) -> bool {
67        let mut state = self.state.lock().unwrap();
68        if *state != FiberState::Pending && *state != FiberState::Loading {
69            return *state == FiberState::Active;
70        }
71
72        let satisfied = self.satisfied_coeffects.lock().unwrap();
73        if self.required_coeffects.is_subset(&satisfied) {
74            *state = FiberState::Active;
75            true
76        } else {
77            false
78        }
79    }
80
81    /// Satisfies a specific coeffect requirement.
82    pub fn satisfy_coeffect(&self, coeffect: &str) -> bool {
83        {
84            let mut satisfied = self.satisfied_coeffects.lock().unwrap();
85            satisfied.insert(coeffect.to_string());
86        }
87        self.try_activate()
88    }
89
90    /// Registers a reversible cleanup effect with this fiber.
91    pub fn register_disposable<F>(&self, cleanup: F)
92    where
93        F: FnOnce() -> Result<(), String> + Send + 'static,
94    {
95        let mut disp = self.disposables.lock().unwrap();
96        disp.push(cleanup);
97    }
98
99    /// Explicitly transitions the Fiber to a new state.
100    pub fn transition_to(&self, new_state: FiberState) -> Result<(), String> {
101        let mut state = self.state.lock().unwrap();
102        *state = new_state;
103        Ok(())
104    }
105
106    /// Returns the current lifecycle state of the Fiber.
107    pub fn get_state(&self) -> FiberState {
108        self.state.lock().unwrap().clone()
109    }
110
111    /// Pauses the fiber execution, preparing for HMR or state snapshot.
112    pub fn pause(&self) -> Result<(), String> {
113        let mut state = self.state.lock().unwrap();
114        *state = FiberState::Paused;
115        Ok(())
116    }
117
118    /// Activates or resumes the fiber.
119    pub fn activate(&self) -> Result<(), String> {
120        let mut state = self.state.lock().unwrap();
121        *state = FiberState::Active;
122        Ok(())
123    }
124
125    /// Suspends the fiber execution awaiting a delimited continuation.
126    pub fn suspend(&self) -> Result<(), String> {
127        let mut state = self.state.lock().unwrap();
128        *state = FiberState::Suspended;
129        Ok(())
130    }
131
132    /// Resumes the fiber execution from suspended state back to Active.
133    pub fn resume(&self) -> Result<(), String> {
134        let mut state = self.state.lock().unwrap();
135        *state = FiberState::Active;
136        Ok(())
137    }
138
139    /// Unwinds disposables in LIFO order without setting Disposed state.
140    pub fn unwind_disposables(&self) -> Result<(), Vec<String>> {
141        let disposers = {
142            let mut disp = self.disposables.lock().unwrap();
143            std::mem::take(&mut *disp)
144        };
145        disposers.dispose()
146    }
147
148    /// Stores the CLM AST in this fiber.
149    pub fn set_ast(&self, ast: serde_json::Value) {
150        let mut clm = self.clm_ast.lock().unwrap();
151        *clm = Some(ast);
152    }
153
154    /// Retrieves the stored CLM AST if present.
155    pub fn get_ast(&self) -> Option<serde_json::Value> {
156        self.clm_ast.lock().unwrap().clone()
157    }
158
159    /// Transitions the Fiber to DISPOSED, executing all disposables in strict LIFO order.
160    pub fn dispose(&self) -> Result<(), Vec<String>> {
161        {
162            let mut state = self.state.lock().unwrap();
163            *state = FiberState::Unloading;
164        }
165
166        let disposers = {
167            let mut disp = self.disposables.lock().unwrap();
168            std::mem::take(&mut *disp)
169        };
170
171        let result = disposers.dispose();
172
173        {
174            let mut state = self.state.lock().unwrap();
175            if result.is_ok() {
176                *state = FiberState::Disposed;
177            } else {
178                *state = FiberState::Failed("Disposal errors encountered".to_string());
179            }
180        }
181
182        result
183    }
184}
185
186/// A Scoped Monadic Context for Cordis plugin execution.
187#[derive(Clone)]
188pub struct Context {
189    pub scope_id: String,
190    pub services: Arc<DashMap<String, Arc<dyn Any + Send + Sync>>>,
191    pub fibers: Arc<DashMap<String, Arc<Fiber>>>,
192}
193
194impl Context {
195    /// Creates the sovereign Empty Root Context (⊥) with zero privileged state.
196    pub fn root() -> Self {
197        Self {
198            scope_id: "root".to_string(),
199            services: Arc::new(DashMap::new()),
200            fibers: Arc::new(DashMap::new()),
201        }
202    }
203
204    /// Creates a scoped child context partitioned by user identity (Tenant Isolation).
205    pub fn user(&self, did: &str) -> Self {
206        Self {
207            scope_id: format!("{}/user:{}", self.scope_id, did),
208            services: self.services.clone(),
209            fibers: self.fibers.clone(),
210        }
211    }
212
213    /// Creates a scoped child context partitioned by communication channel or session.
214    pub fn channel(&self, channel_id: &str) -> Self {
215        Self {
216            scope_id: format!("{}/channel:{}", self.scope_id, channel_id),
217            services: self.services.clone(),
218            fibers: self.fibers.clone(),
219        }
220    }
221
222    /// Creates an isolated child sandbox with only the declared coeffects exposed.
223    pub fn isolate(&self, allowed_coeffects: &[&str]) -> Self {
224        let isolated_services = Arc::new(DashMap::new());
225        let allowed_set: HashSet<&str> = allowed_coeffects.iter().copied().collect();
226
227        for entry in self.services.iter() {
228            if allowed_set.contains(entry.key().as_str()) {
229                isolated_services.insert(entry.key().clone(), entry.value().clone());
230            }
231        }
232
233        Self {
234            scope_id: format!("{}/isolate:{}", self.scope_id, uuid_or_random()),
235            services: isolated_services,
236            fibers: Arc::new(DashMap::new()),
237        }
238    }
239
240    /// Creates a masked child context with specific capabilities stripped.
241    pub fn mask(&self, denied_coeffects: &[&str]) -> Self {
242        let masked_services = Arc::new(DashMap::new());
243        let denied_set: HashSet<&str> = denied_coeffects.iter().copied().collect();
244
245        for entry in self.services.iter() {
246            if !denied_set.contains(entry.key().as_str()) {
247                masked_services.insert(entry.key().clone(), entry.value().clone());
248            }
249        }
250
251        Self {
252            scope_id: format!("{}/mask:{}", self.scope_id, uuid_or_random()),
253            services: masked_services,
254            fibers: Arc::new(DashMap::new()),
255        }
256    }
257
258    /// Checks whether a specific coeffect capability is present in this context scope.
259    pub fn require(&self, coeffect: &str) -> bool {
260        self.services.contains_key(coeffect)
261    }
262
263    /// Provides a service capability into the context registry (alias for register_service).
264    pub fn provide<T: Send + Sync + 'static>(&self, name: &str, service: T) {
265        self.register_service(name, service);
266    }
267
268    /// Registers a service capability into the context registry.
269    pub fn register_service<T: Send + Sync + 'static>(&self, name: &str, service: T) {
270        self.services.insert(name.to_string(), Arc::new(service));
271
272        // Notify any pending fibers that this coeffect is now available
273        for fiber in self.fibers.iter() {
274            if fiber.required_coeffects.contains(name) {
275                fiber.satisfy_coeffect(name);
276            }
277        }
278    }
279
280    /// Retrieves a typed service capability from the registry.
281    pub fn get_service<T: Send + Sync + 'static>(&self, name: &str) -> Option<Arc<T>> {
282        self.services
283            .get(name)
284            .and_then(|any_arc| any_arc.clone().downcast::<T>().ok())
285    }
286
287    /// Mounts an MCard virtual filesystem into this context scope as a reactive coeffect (Sprint 191).
288    #[cfg(any(feature = "native", feature = "db"))]
289    pub fn mount_mcard_fs(&self, fs: crate::mcard_fs::MCardFileSystem) {
290        self.provide("mcard_fs", fs);
291    }
292
293    /// Retrieves the mounted MCard virtual filesystem if available.
294    #[cfg(any(feature = "native", feature = "db"))]
295    pub fn mcard_fs(&self) -> Option<Arc<crate::mcard_fs::MCardFileSystem>> {
296        self.get_service::<crate::mcard_fs::MCardFileSystem>("mcard_fs")
297    }
298
299    /// Ephemerally mounts an MCard virtual filesystem scoped to `prefix` on a Fiber,
300    /// registering LIFO cleanup on the fiber's DisposableList.
301    #[cfg(any(feature = "native", feature = "db"))]
302    pub fn mount_ephemeral_mcard_fs(
303        &self,
304        fiber_id: &str,
305        prefix: &str,
306    ) -> Result<crate::mcard_fs::MCardFileSystem, String> {
307        let fs = self.mcard_fs().ok_or_else(|| "mcard_fs service not mounted in context".to_string())?;
308        let fiber = self.get_fiber(fiber_id).ok_or_else(|| format!("fiber '{}' not found", fiber_id))?;
309        fs.ephemeral_mount(&fiber, prefix)
310            .map_err(|e| e.to_string())
311    }
312
313    /// Instantiates and registers a new Fiber within this context.
314    pub fn spawn_fiber(&self, id: &str, required_coeffects: Vec<String>) -> Arc<Fiber> {
315        let fiber = Arc::new(Fiber::new(id, required_coeffects));
316
317        // Immediately satisfy any coeffects that already exist in this context
318        for coeffect in &fiber.required_coeffects {
319            if self.services.contains_key(coeffect) {
320                fiber.satisfy_coeffect(coeffect);
321            }
322        }
323
324        self.fibers.insert(id.to_string(), fiber.clone());
325        fiber
326    }
327
328    /// Looks up an active fiber by id.
329    pub fn get_fiber(&self, id: &str) -> Option<Arc<Fiber>> {
330        self.fibers.get(id).map(|f| f.clone())
331    }
332
333    /// Lists all active fibers in this context.
334    pub fn list_fibers(&self) -> Vec<Arc<Fiber>> {
335        self.fibers.iter().map(|entry| entry.value().clone()).collect()
336    }
337
338    /// Creates and registers a new Fiber within this context.
339    pub fn create_fiber(&self, id: &str, required_coeffects: Vec<String>) -> Result<Arc<Fiber>, String> {
340        Ok(self.spawn_fiber(id, required_coeffects))
341    }
342
343    /// Removes an active fiber from the registry.
344    pub fn remove_fiber(&self, id: &str) -> Option<Arc<Fiber>> {
345        self.fibers.remove(id).map(|(_, f)| f)
346    }
347
348    /// Disposes all fibers associated with this context scope.
349    pub fn dispose(&self) -> Result<(), Vec<String>> {
350        let mut errors = Vec::new();
351        for fiber in self.fibers.iter() {
352            if let Err(mut e) = fiber.dispose() {
353                errors.append(&mut e);
354            }
355        }
356        if errors.is_empty() {
357            Ok(())
358        } else {
359            Err(errors)
360        }
361    }
362}
363
364fn uuid_or_random() -> String {
365    use std::time::{SystemTime, UNIX_EPOCH};
366    let nanos = SystemTime::now()
367        .duration_since(UNIX_EPOCH)
368        .map(|d| d.as_nanos())
369        .unwrap_or(0);
370    format!("{:x}", nanos)
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn test_empty_root_context() {
379        let ctx = Context::root();
380        assert_eq!(ctx.scope_id, "root");
381        assert!(ctx.services.is_empty());
382        assert!(ctx.fibers.is_empty());
383    }
384
385    #[test]
386    fn test_fiber_coeffect_satisfaction_lifecycle() {
387        let ctx = Context::root();
388
389        // Spawn a fiber that requires 'mcardfs' and 'signer'
390        let fiber = ctx.spawn_fiber("worker_1", vec!["mcardfs".to_string(), "signer".to_string()]);
391        assert_eq!(*fiber.state.lock().unwrap(), FiberState::Pending);
392
393        // Register mcardfs -> still Pending
394        ctx.register_service("mcardfs", "StorageEngineMock".to_string());
395        assert_eq!(*fiber.state.lock().unwrap(), FiberState::Pending);
396
397        // Register signer -> both coeffects satisfied -> transitions to ACTIVE
398        ctx.register_service("signer", "Ed25519SignerMock".to_string());
399        assert_eq!(*fiber.state.lock().unwrap(), FiberState::Active);
400
401        // Register a disposable effect
402        let cleaned = Arc::new(Mutex::new(false));
403        let cleaned_clone = Arc::clone(&cleaned);
404        fiber.register_disposable(move || {
405            *cleaned_clone.lock().unwrap() = true;
406            Ok(())
407        });
408
409        // Dispose fiber
410        assert!(fiber.dispose().is_ok());
411        assert_eq!(*fiber.state.lock().unwrap(), FiberState::Disposed);
412        assert!(*cleaned.lock().unwrap());
413    }
414
415    #[test]
416    fn test_algebraic_isolation() {
417        let ctx = Context::root();
418        ctx.register_service("public_db", 100u32);
419        ctx.register_service("private_keys", 999u32);
420
421        let isolated = ctx.isolate(&["public_db"]);
422        assert!(isolated.get_service::<u32>("public_db").is_some());
423        assert!(isolated.get_service::<u32>("private_keys").is_none());
424    }
425
426    #[test]
427    fn test_mask_capability_filtering() {
428        let ctx = Context::root();
429        ctx.provide("clm.io.read", 100u32);
430        ctx.provide("clm.io.write", 200u32);
431
432        let masked = ctx.mask(&["clm.io.write"]);
433        assert!(masked.require("clm.io.read"));
434        assert!(!masked.require("clm.io.write"));
435    }
436
437    #[test]
438    fn test_fiber_vcard_sandwich_state_transitions() {
439        let ctx = Context::root();
440        let fiber = ctx.spawn_fiber("sandwich_test", vec![]);
441        assert_eq!(fiber.get_state(), FiberState::Active);
442
443        fiber.transition_to(FiberState::Loading).unwrap();
444        assert_eq!(fiber.get_state(), FiberState::Loading);
445
446        fiber.transition_to(FiberState::Active).unwrap();
447        assert_eq!(fiber.get_state(), FiberState::Active);
448
449        assert!(fiber.dispose().is_ok());
450        assert_eq!(fiber.get_state(), FiberState::Disposed);
451    }
452
453    #[test]
454    fn test_fiber_hmr_lifecycle_and_registry() {
455        let ctx = Context::root();
456        let fiber = ctx.create_fiber("hmr_worker", vec![]).unwrap();
457        assert_eq!(fiber.get_state(), FiberState::Active);
458
459        // Registry queries
460        assert!(ctx.get_fiber("hmr_worker").is_some());
461        assert_eq!(ctx.list_fibers().len(), 1);
462
463        // AST storage
464        let dummy_ast = serde_json::json!({
465            "invariants": {
466                "preconditions": ["inv_1"],
467                "postconditions": ["inv_2"]
468            }
469        });
470        fiber.set_ast(dummy_ast.clone());
471        assert_eq!(fiber.get_ast(), Some(dummy_ast));
472
473        // Register disposable
474        let unwound = Arc::new(Mutex::new(false));
475        let unwound_clone = Arc::clone(&unwound);
476        fiber.register_disposable(move || {
477            *unwound_clone.lock().unwrap() = true;
478            Ok(())
479        });
480
481        // Pause fiber for HMR
482        assert!(fiber.pause().is_ok());
483        assert_eq!(fiber.get_state(), FiberState::Paused);
484
485        // Unwind disposables without disposing fiber
486        assert!(fiber.unwind_disposables().is_ok());
487        assert!(*unwound.lock().unwrap());
488        assert_eq!(fiber.get_state(), FiberState::Paused);
489
490        // Resume/Activate
491        assert!(fiber.activate().is_ok());
492        assert_eq!(fiber.get_state(), FiberState::Active);
493
494        // Remove from registry
495        assert!(ctx.remove_fiber("hmr_worker").is_some());
496        assert!(ctx.get_fiber("hmr_worker").is_none());
497        assert_eq!(ctx.list_fibers().len(), 0);
498    }
499}