Skip to main content

maple_runtime/runtime_core/
runtime.rs

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