Skip to main content

maple_runtime/runtime_core/
runtime.rs

1//! Main MAPLE Resonance Runtime implementation
2
3use crate::allocator::AttentionAllocator;
4use crate::config::RuntimeConfig;
5use crate::fabrics::{CouplingFabric, PresenceFabric};
6use crate::invariants::InvariantGuard;
7use crate::runtime_core::{ContinuityProof, ProfileManager, ResonatorHandle, ResonatorRegistry};
8use crate::scheduler::ResonanceScheduler;
9use crate::telemetry::RuntimeTelemetry;
10use crate::temporal::TemporalCoordinator;
11use crate::types::*;
12use std::sync::Arc;
13use tokio::sync::RwLock;
14
15/// The MAPLE Resonance Runtime - heart of the entire MAPLE ecosystem
16///
17/// This runtime powers:
18/// - **Mapleverse**: Coordination of millions of pure AI agents
19/// - **Finalverse**: Meaningful human-AI coexistence in experiential worlds
20/// - **iBank**: Accountable autonomous financial operations
21#[derive(Clone)]
22pub struct MapleRuntime {
23    inner: Arc<RuntimeInner>,
24}
25
26struct RuntimeInner {
27    // ═══════════════════════════════════════════════════════════════════
28    // RESONATOR MANAGEMENT
29    // ═══════════════════════════════════════════════════════════════════
30    resonator_registry: Arc<ResonatorRegistry>,
31    profile_manager: Arc<ProfileManager>,
32
33    // ═══════════════════════════════════════════════════════════════════
34    // RESONANCE INFRASTRUCTURE
35    // ═══════════════════════════════════════════════════════════════════
36    presence_fabric: Arc<PresenceFabric>,
37    coupling_fabric: Arc<CouplingFabric>,
38    attention_allocator: Arc<AttentionAllocator>,
39
40    // ═══════════════════════════════════════════════════════════════════
41    // COGNITIVE PIPELINE (placeholders for now)
42    // ═══════════════════════════════════════════════════════════════════
43    // meaning_engine: Arc<MeaningFormationEngine>,
44    // intent_engine: Arc<IntentStabilizationEngine>,
45    // commitment_manager: Arc<CommitmentManager>,
46    // consequence_tracker: Arc<ConsequenceTracker>,
47
48    // ═══════════════════════════════════════════════════════════════════
49    // SAFETY AND GOVERNANCE
50    // ═══════════════════════════════════════════════════════════════════
51    #[allow(dead_code)]
52    invariant_guard: Arc<InvariantGuard>,
53    // agency_protector: Arc<HumanAgencyProtector>,
54    // safety_enforcer: Arc<SafetyBoundaryEnforcer>,
55
56    // ═══════════════════════════════════════════════════════════════════
57    // TEMPORAL AND SCHEDULING
58    // ═══════════════════════════════════════════════════════════════════
59    temporal_coordinator: Arc<TemporalCoordinator>,
60    scheduler: Arc<ResonanceScheduler>,
61
62    // ═══════════════════════════════════════════════════════════════════
63    // OBSERVABILITY
64    // ═══════════════════════════════════════════════════════════════════
65    telemetry: Arc<RuntimeTelemetry>,
66
67    // ═══════════════════════════════════════════════════════════════════
68    // STATE
69    // ═══════════════════════════════════════════════════════════════════
70    shutdown: Arc<RwLock<bool>>,
71}
72
73impl MapleRuntime {
74    /// Bootstrap the MAPLE Resonance Runtime
75    ///
76    /// This initializes all subsystems in the correct order to ensure
77    /// architectural invariants are satisfied from the start.
78    ///
79    /// # Arguments
80    ///
81    /// * `config` - Runtime configuration
82    ///
83    /// # Returns
84    ///
85    /// * `Ok(MapleRuntime)` - Successfully bootstrapped runtime
86    /// * `Err(BootstrapError)` - Bootstrap failed
87    ///
88    /// # Example
89    ///
90    /// ```no_run
91    /// use maple_runtime::{MapleRuntime, config::RuntimeConfig};
92    ///
93    /// #[tokio::main]
94    /// async fn main() {
95    ///     let config = RuntimeConfig::default();
96    ///     let runtime = MapleRuntime::bootstrap(config).await.unwrap();
97    /// }
98    /// ```
99    pub async fn bootstrap(config: RuntimeConfig) -> Result<Self, BootstrapError> {
100        tracing::info!("Bootstrapping MAPLE Resonance Runtime");
101
102        // Phase 1: Initialize safety infrastructure FIRST
103        tracing::debug!("Phase 1: Initializing safety infrastructure");
104        let invariant_guard = Arc::new(InvariantGuard::new(&config.invariants));
105
106        // Phase 2: Initialize temporal coordination
107        tracing::debug!("Phase 2: Initializing temporal coordination");
108        let temporal_coordinator = Arc::new(TemporalCoordinator::new(&config.temporal));
109
110        // Phase 3: Initialize resonance infrastructure
111        tracing::debug!("Phase 3: Initializing resonance infrastructure");
112        let attention_allocator = Arc::new(AttentionAllocator::new(&config.attention));
113        let presence_fabric = Arc::new(PresenceFabric::new(&config.presence));
114        let coupling_fabric = Arc::new(CouplingFabric::new(
115            &config.coupling,
116            Arc::clone(&attention_allocator),
117        ));
118
119        // Phase 4: Initialize cognitive pipeline (placeholder)
120        tracing::debug!("Phase 4: Cognitive pipeline (placeholder)");
121
122        // Phase 5: Initialize Resonator management
123        tracing::debug!("Phase 5: Initializing Resonator management");
124        let profile_manager = Arc::new(ProfileManager::new(&config.profiles));
125        let resonator_registry = Arc::new(ResonatorRegistry::new(&config.registry));
126
127        // Phase 6: Initialize scheduler and telemetry
128        tracing::debug!("Phase 6: Initializing scheduler and telemetry");
129        let scheduler = Arc::new(ResonanceScheduler::new(&config.scheduling));
130        let telemetry = Arc::new(RuntimeTelemetry::new(&config.telemetry));
131
132        let inner = RuntimeInner {
133            resonator_registry,
134            profile_manager,
135            presence_fabric,
136            coupling_fabric,
137            attention_allocator,
138            invariant_guard,
139            temporal_coordinator,
140            scheduler,
141            telemetry,
142            shutdown: Arc::new(RwLock::new(false)),
143        };
144
145        tracing::info!("MAPLE Resonance Runtime bootstrapped successfully");
146
147        Ok(Self {
148            inner: Arc::new(inner),
149        })
150    }
151
152    /// Shutdown gracefully, preserving all commitments
153    ///
154    /// This ensures that:
155    /// 1. No new commitments are accepted
156    /// 2. Active commitments are completed or recorded
157    /// 3. All Resonator continuity is persisted
158    /// 4. Coupling topology is saved
159    pub async fn shutdown(&self) -> Result<(), ShutdownError> {
160        tracing::info!("Shutting down MAPLE Resonance Runtime");
161
162        let mut shutdown = self.inner.shutdown.write().await;
163        if *shutdown {
164            tracing::warn!("Runtime already shut down");
165            return Ok(());
166        }
167        *shutdown = true;
168        drop(shutdown);
169
170        // Step 1: Stop accepting new commitments (placeholder)
171        tracing::debug!("Step 1: Stopping new commitments");
172
173        // Step 2: Wait for active commitments (placeholder)
174        tracing::debug!("Step 2: Waiting for active commitments");
175
176        // Step 3: Persist all Resonator continuity records
177        tracing::debug!("Step 3: Persisting Resonator continuity");
178        self.inner
179            .resonator_registry
180            .persist_all_continuity()
181            .await
182            .map_err(|e| ShutdownError::PersistenceError(e.to_string()))?;
183
184        // Step 4: Persist coupling topology
185        tracing::debug!("Step 4: Persisting coupling topology");
186        self.inner
187            .coupling_fabric
188            .persist_topology()
189            .await
190            .map_err(|e| ShutdownError::PersistenceError(e.to_string()))?;
191
192        // Step 5: Final telemetry flush
193        tracing::debug!("Step 5: Flushing telemetry");
194        self.inner.telemetry.flush().await;
195
196        tracing::info!("MAPLE Resonance Runtime shutdown complete");
197        Ok(())
198    }
199
200    /// Check if runtime is shutting down
201    pub async fn is_shutting_down(&self) -> bool {
202        *self.inner.shutdown.read().await
203    }
204
205    /// Register a new Resonator
206    ///
207    /// This creates a persistent identity that survives restarts,
208    /// migrations, and network partitions.
209    ///
210    /// # Arguments
211    ///
212    /// * `spec` - Resonator specification
213    ///
214    /// # Returns
215    ///
216    /// * `Ok(ResonatorHandle)` - Handle to the registered Resonator
217    /// * `Err(RegistrationError)` - Registration failed
218    pub async fn register_resonator(
219        &self,
220        spec: ResonatorSpec,
221    ) -> Result<ResonatorHandle, RegistrationError> {
222        if self.is_shutting_down().await {
223            return Err(RegistrationError::InvalidSpec(
224                "Runtime is shutting down".to_string(),
225            ));
226        }
227
228        // Validate against profile constraints
229        self.inner
230            .profile_manager
231            .validate_spec(&spec)
232            .map_err(|e| RegistrationError::ProfileValidation(e))?;
233
234        // Check invariants
235        // (placeholder for now)
236
237        // Create persistent identity
238        let identity = self
239            .inner
240            .resonator_registry
241            .create_identity(&spec.identity)
242            .await?;
243
244        // Initialize presence
245        self.inner
246            .presence_fabric
247            .initialize_presence(&identity, &spec.presence)
248            .await
249            .map_err(|e| RegistrationError::InvalidSpec(e.to_string()))?;
250
251        // Allocate attention budget
252        self.inner
253            .attention_allocator
254            .allocate_budget(&identity, &spec.attention)
255            .await
256            .map_err(|e| RegistrationError::InvalidSpec(e.to_string()))?;
257
258        // Register in coupling topology
259        self.inner
260            .coupling_fabric
261            .register(&identity)
262            .await
263            .map_err(|e| RegistrationError::InvalidSpec(e.to_string()))?;
264
265        // Create Resonator handle
266        let handle = ResonatorHandle::new(identity, self.clone());
267
268        // Emit telemetry
269        self.inner.telemetry.resonator_registered(&handle);
270
271        tracing::info!("Registered Resonator: {}", identity);
272
273        Ok(handle)
274    }
275
276    /// Resume a Resonator from continuity record
277    ///
278    /// This restores a Resonator's identity, memory, and pending commitments
279    /// after a restart or migration.
280    pub async fn resume_resonator(
281        &self,
282        continuity_proof: ContinuityProof,
283    ) -> Result<ResonatorHandle, ResumeError> {
284        if self.is_shutting_down().await {
285            return Err(ResumeError::StateRestorationFailed(
286                "Runtime is shutting down".to_string(),
287            ));
288        }
289
290        // Verify continuity proof
291        let record = self
292            .inner
293            .resonator_registry
294            .verify_continuity(&continuity_proof)
295            .await?;
296
297        // Restore identity
298        let identity = record.identity;
299
300        // Restore presence state
301        self.inner
302            .presence_fabric
303            .restore_presence(&identity, &record.presence_state)
304            .await
305            .map_err(|e| ResumeError::StateRestorationFailed(e.to_string()))?;
306
307        // Restore attention budget
308        self.inner
309            .attention_allocator
310            .restore_budget(&identity, &record.attention_state)
311            .await
312            .map_err(|e| ResumeError::StateRestorationFailed(e.to_string()))?;
313
314        // Restore coupling topology
315        self.inner
316            .coupling_fabric
317            .restore_couplings(&identity, &record.couplings)
318            .await
319            .map_err(|e| ResumeError::StateRestorationFailed(e.to_string()))?;
320
321        // Reconcile pending commitments (placeholder)
322
323        let handle = ResonatorHandle::new(identity, self.clone());
324
325        self.inner.telemetry.resonator_resumed(&handle);
326
327        tracing::info!("Resumed Resonator: {}", identity);
328
329        Ok(handle)
330    }
331
332    // ═══════════════════════════════════════════════════════════════════
333    // ACCESSORS FOR SUBSYSTEMS
334    // ═══════════════════════════════════════════════════════════════════
335
336    pub fn presence_fabric(&self) -> &Arc<PresenceFabric> {
337        &self.inner.presence_fabric
338    }
339
340    pub fn coupling_fabric(&self) -> &Arc<CouplingFabric> {
341        &self.inner.coupling_fabric
342    }
343
344    pub fn attention_allocator(&self) -> &Arc<AttentionAllocator> {
345        &self.inner.attention_allocator
346    }
347
348    pub fn temporal_coordinator(&self) -> &Arc<TemporalCoordinator> {
349        &self.inner.temporal_coordinator
350    }
351
352    pub fn scheduler(&self) -> &Arc<ResonanceScheduler> {
353        &self.inner.scheduler
354    }
355
356    pub fn telemetry(&self) -> &Arc<RuntimeTelemetry> {
357        &self.inner.telemetry
358    }
359}
360
361/// Specification for creating a new Resonator
362#[derive(Debug, Clone)]
363pub struct ResonatorSpec {
364    /// Identity specification
365    pub identity: ResonatorIdentitySpec,
366
367    /// Profile determines constraints and behaviors
368    pub profile: ResonatorProfile,
369
370    /// Initial capabilities (placeholder)
371    pub capabilities: Vec<CapabilitySpec>,
372
373    /// Presence configuration
374    pub presence: PresenceConfig,
375
376    /// Attention budget
377    pub attention: AttentionBudgetSpec,
378
379    /// Initial memory (for continuity across restarts)
380    pub initial_memory: Option<MemorySnapshot>,
381
382    /// Coupling affinity (preferred coupling patterns)
383    pub coupling_affinity: CouplingAffinitySpec,
384}
385
386impl Default for ResonatorSpec {
387    fn default() -> Self {
388        Self {
389            identity: ResonatorIdentitySpec::default(),
390            profile: ResonatorProfile::default(),
391            capabilities: Vec::new(),
392            presence: PresenceConfig::default(),
393            attention: AttentionBudgetSpec::default(),
394            initial_memory: None,
395            coupling_affinity: CouplingAffinitySpec::default(),
396        }
397    }
398}
399
400/// Identity specification for a Resonator
401#[derive(Debug, Clone)]
402pub struct ResonatorIdentitySpec {
403    /// Display name (optional)
404    pub name: Option<String>,
405
406    /// Additional metadata
407    pub metadata: std::collections::HashMap<String, String>,
408}
409
410impl Default for ResonatorIdentitySpec {
411    fn default() -> Self {
412        Self {
413            name: None,
414            metadata: std::collections::HashMap::new(),
415        }
416    }
417}
418
419/// Capability specification (placeholder)
420#[derive(Debug, Clone)]
421pub struct CapabilitySpec {
422    pub name: String,
423    pub version: String,
424}
425
426/// Memory snapshot (placeholder)
427#[derive(Debug, Clone)]
428pub struct MemorySnapshot {
429    pub data: Vec<u8>,
430}