clm-kernel 0.0.24

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
//! 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 crate::layer0::fiber_transitions::{self as lifecycle, FiberBypass};
pub use crate::layer0::fiber_transitions::FiberState;
use dashmap::DashMap;
use std::any::Any;
use std::collections::HashSet;
use std::sync::{Arc, Mutex};

/// The table `step` reads: one profile's ordinary edges and its bypasses.
pub struct FiberTable {
    pub profile: &'static str,
    pub valid: fn(&FiberState, &FiberState) -> bool,
    /// The targets an ordinary transition may take from each state, in published names.
    pub allowed: &'static [(&'static str, &'static [&'static str])],
    pub bypasses: &'static [FiberBypass],
}

/// The generated table of this runtime's profile.
pub const TABLE: FiberTable = FiberTable {
    profile: lifecycle::PROFILE,
    valid: lifecycle::valid_transition,
    allowed: lifecycle::PUBLISHED_TRANSITIONS,
    bypasses: lifecycle::BYPASSES,
};

/// What a caller asks of a fiber: move to `to` along an ordinary edge, or through a named bypass.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FiberEvent {
    pub to: FiberState,
    pub bypass: Option<&'static FiberBypass>,
}

impl FiberEvent {
    pub fn to(to: FiberState) -> Self {
        Self { to, bypass: None }
    }

    pub fn bypass(bypass: &'static FiberBypass, to: FiberState) -> Self {
        Self { to, bypass: Some(bypass) }
    }
}

/// Work the caller owes once a move is stored.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FiberEffect {
    UnwindDisposables,
}

const NO_EFFECTS: &[FiberEffect] = &[];
const UNWIND: &[FiberEffect] = &[FiberEffect::UnwindDisposables];

/// A legal move: the state to store and the effects to apply.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Moved {
    pub state: FiberState,
    pub effects: &'static [FiberEffect],
}

/// A move the table does not carry; the state is unchanged.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Illegal {
    pub profile: &'static str,
    pub from: FiberState,
    pub to: FiberState,
    pub allowed: &'static [&'static str],
}

impl std::fmt::Display for Illegal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "illegal fiber transition {} -> {} under the {} profile; allowed targets: {:?}",
            self.from.published_name(),
            self.to.published_name(),
            self.profile,
            self.allowed
        )
    }
}

/// Decides one lifecycle move. Reads only its arguments: no clock, no lock, no fiber.
#[inline]
pub fn step(table: &FiberTable, state: &FiberState, event: FiberEvent) -> Result<Moved, Illegal> {
    let FiberEvent { to, bypass } = event;
    let effects = if let Some(bypass) = bypass {
        let fires = table.bypasses.contains(bypass)
            && bypass.sources.contains(&state.name())
            && bypass.targets.contains(&to.name());
        fires.then_some(if bypass.drains { UNWIND } else { NO_EFFECTS })
    } else {
        (table.valid)(state, &to).then_some(NO_EFFECTS)
    };
    let Some(effects) = effects else {
        let allowed = table
            .allowed
            .iter()
            .find(|(from, _)| *from == state.published_name())
            .map_or(NO_TARGETS, |(_, targets)| *targets);
        return Err(Illegal { profile: table.profile, from: state.clone(), to, allowed });
    };
    Ok(Moved { state: to, effects })
}

/// Decides `event` with `step` and stores the state it returns. The only writer of a fiber's state.
fn store(state: &mut FiberState, event: FiberEvent) -> Result<&'static [FiberEffect], Illegal> {
    let moved = step(&TABLE, state, event)?;
    *state = moved.state;
    Ok(moved.effects)
}

const NO_TARGETS: &[&str] = &[];
const DISPOSAL_ERRORS: &str = "Disposal errors encountered";

/// A Cordis execution Fiber representing an isolated plugin, agent task, or service.
pub struct Fiber {
    pub id: String,
    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();
        Self {
            id: id.into(),
            state: Mutex::new(lifecycle::initial_state(coeffects_set.is_empty())),
            required_coeffects: coeffects_set,
            satisfied_coeffects: Mutex::new(HashSet::new()),
            disposables: Mutex::new(DisposableList::new()),
            clm_ast: Mutex::new(None),
        }
    }

    /// The profile whose table this fiber's moves are decided by.
    pub fn profile(&self) -> &'static str {
        TABLE.profile
    }

    fn fire(&self, event: FiberEvent) -> Result<&'static [FiberEffect], Illegal> {
        store(&mut self.state.lock().unwrap(), event)
    }

    /// 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();
        self.required_coeffects.is_subset(&satisfied)
            && store(&mut state, FiberEvent::to(FiberState::Active)).is_ok()
    }

    /// Satisfies a specific coeffect requirement.
    pub fn satisfy_coeffect(&self, coeffect: &str) -> bool {
        self.satisfied_coeffects.lock().unwrap().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,
    {
        self.disposables.lock().unwrap().push(cleanup);
    }

    /// Transitions the Fiber to a new state along an ordinary edge of its profile.
    pub fn transition_to(&self, new_state: FiberState) -> Result<(), String> {
        self.fire(FiberEvent::to(new_state)).map(drop).map_err(|refused| refused.to_string())
    }

    /// 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> {
        self.transition_to(FiberState::Paused)
    }

    /// Activates or resumes the fiber.
    pub fn activate(&self) -> Result<(), String> {
        self.transition_to(FiberState::Active)
    }

    /// Suspends the fiber execution awaiting a delimited continuation.
    pub fn suspend(&self) -> Result<(), String> {
        self.transition_to(FiberState::Suspended)
    }

    /// Resumes the fiber execution from suspended state back to Active.
    pub fn resume(&self) -> Result<(), String> {
        self.transition_to(FiberState::Active)
    }

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

    /// Stores the CLM AST in this fiber.
    pub fn set_ast(&self, ast: serde_json::Value) {
        *self.clm_ast.lock().unwrap() = 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.
    /// A fiber that is already disposed stays disposed and reports success.
    pub fn dispose(&self) -> Result<(), Vec<String>> {
        let fired = self.fire(FiberEvent::bypass(&lifecycle::RUST_DISPOSE, FiberState::Unloading));
        if let Err(refused) = &fired {
            if refused.from == FiberState::Disposed {
                return Ok(());
            }
        }
        let effects = fired.map_err(|refused| vec![refused.to_string()])?;
        let unwound = if effects.contains(&FiberEffect::UnwindDisposables) {
            self.unwind_disposables()
        } else {
            Ok(())
        };
        let end = if unwound.is_ok() {
            FiberState::Disposed
        } else {
            FiberState::Failed(DISPOSAL_ERRORS.to_string())
        };
        let sealed = self.fire(FiberEvent::to(end)).map(drop).map_err(|refused| vec![refused.to_string()]);
        unwound.and(sealed)
    }
}

/// Where a context draws a fresh identifier. The default reads the clock.
pub type IdSource = Arc<dyn Fn() -> String + Send + Sync>;

/// 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>>>,
    ids: IdSource,
}

impl Context {
    /// Creates the sovereign Empty Root Context (⊥) with zero privileged state.
    pub fn root() -> Self {
        Self::root_with_ids(Arc::new(crate::utils::clock_hex_id))
    }

    /// The root context with a caller-supplied identifier source, so a runner can fix the identifiers.
    pub fn root_with_ids(ids: IdSource) -> Self {
        Self {
            scope_id: "root".to_string(),
            services: Arc::new(DashMap::new()),
            fibers: Arc::new(DashMap::new()),
            ids,
        }
    }

    /// A fresh identifier from this context's source.
    pub fn fresh_id(&self) -> String {
        (self.ids)()
    }

    /// 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(),
            ids: self.ids.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(),
            ids: self.ids.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, self.fresh_id()),
            services: isolated_services,
            fibers: Arc::new(DashMap::new()),
            ids: self.ids.clone(),
        }
    }

    /// 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, self.fresh_id()),
            services: masked_services,
            fibers: Arc::new(DashMap::new()),
            ids: self.ids.clone(),
        }
    }

    /// 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)
        }
    }
}

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