clm-kernel 0.0.5

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! 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)]
mod tests {
    use super::*;

    #[test]
    fn test_empty_root_context() {
        let ctx = Context::root();
        assert_eq!(ctx.scope_id, "root");
        assert!(ctx.services.is_empty());
        assert!(ctx.fibers.is_empty());
    }

    #[test]
    fn test_fiber_coeffect_satisfaction_lifecycle() {
        let ctx = Context::root();

        // Spawn a fiber that requires 'mcardfs' and 'signer'
        let fiber = ctx.spawn_fiber("worker_1", vec!["mcardfs".to_string(), "signer".to_string()]);
        assert_eq!(*fiber.state.lock().unwrap(), FiberState::Pending);

        // Register mcardfs -> still Pending
        ctx.register_service("mcardfs", "StorageEngineMock".to_string());
        assert_eq!(*fiber.state.lock().unwrap(), FiberState::Pending);

        // Register signer -> both coeffects satisfied -> transitions to ACTIVE
        ctx.register_service("signer", "Ed25519SignerMock".to_string());
        assert_eq!(*fiber.state.lock().unwrap(), FiberState::Active);

        // Register a disposable effect
        let cleaned = Arc::new(Mutex::new(false));
        let cleaned_clone = Arc::clone(&cleaned);
        fiber.register_disposable(move || {
            *cleaned_clone.lock().unwrap() = true;
            Ok(())
        });

        // Dispose fiber
        assert!(fiber.dispose().is_ok());
        assert_eq!(*fiber.state.lock().unwrap(), FiberState::Disposed);
        assert!(*cleaned.lock().unwrap());
    }

    #[test]
    fn test_algebraic_isolation() {
        let ctx = Context::root();
        ctx.register_service("public_db", 100u32);
        ctx.register_service("private_keys", 999u32);

        let isolated = ctx.isolate(&["public_db"]);
        assert!(isolated.get_service::<u32>("public_db").is_some());
        assert!(isolated.get_service::<u32>("private_keys").is_none());
    }

    #[test]
    fn test_mask_capability_filtering() {
        let ctx = Context::root();
        ctx.provide("clm.io.read", 100u32);
        ctx.provide("clm.io.write", 200u32);

        let masked = ctx.mask(&["clm.io.write"]);
        assert!(masked.require("clm.io.read"));
        assert!(!masked.require("clm.io.write"));
    }

    #[test]
    fn test_fiber_vcard_sandwich_state_transitions() {
        let ctx = Context::root();
        let fiber = ctx.spawn_fiber("sandwich_test", vec![]);
        assert_eq!(fiber.get_state(), FiberState::Active);

        fiber.transition_to(FiberState::Loading).unwrap();
        assert_eq!(fiber.get_state(), FiberState::Loading);

        fiber.transition_to(FiberState::Active).unwrap();
        assert_eq!(fiber.get_state(), FiberState::Active);

        assert!(fiber.dispose().is_ok());
        assert_eq!(fiber.get_state(), FiberState::Disposed);
    }

    #[test]
    fn test_fiber_hmr_lifecycle_and_registry() {
        let ctx = Context::root();
        let fiber = ctx.create_fiber("hmr_worker", vec![]).unwrap();
        assert_eq!(fiber.get_state(), FiberState::Active);

        // Registry queries
        assert!(ctx.get_fiber("hmr_worker").is_some());
        assert_eq!(ctx.list_fibers().len(), 1);

        // AST storage
        let dummy_ast = serde_json::json!({
            "invariants": {
                "preconditions": ["inv_1"],
                "postconditions": ["inv_2"]
            }
        });
        fiber.set_ast(dummy_ast.clone());
        assert_eq!(fiber.get_ast(), Some(dummy_ast));

        // Register disposable
        let unwound = Arc::new(Mutex::new(false));
        let unwound_clone = Arc::clone(&unwound);
        fiber.register_disposable(move || {
            *unwound_clone.lock().unwrap() = true;
            Ok(())
        });

        // Pause fiber for HMR
        assert!(fiber.pause().is_ok());
        assert_eq!(fiber.get_state(), FiberState::Paused);

        // Unwind disposables without disposing fiber
        assert!(fiber.unwind_disposables().is_ok());
        assert!(*unwound.lock().unwrap());
        assert_eq!(fiber.get_state(), FiberState::Paused);

        // Resume/Activate
        assert!(fiber.activate().is_ok());
        assert_eq!(fiber.get_state(), FiberState::Active);

        // Remove from registry
        assert!(ctx.remove_fiber("hmr_worker").is_some());
        assert!(ctx.get_fiber("hmr_worker").is_none());
        assert_eq!(ctx.list_fibers().len(), 0);
    }
}