use crate::allocator::AttentionAllocator;
use crate::config::RuntimeConfig;
use crate::fabrics::{CouplingFabric, PresenceFabric};
use crate::invariants::InvariantGuard;
use crate::runtime_core::{ContinuityProof, ProfileManager, ResonatorHandle, ResonatorRegistry};
use crate::scheduler::ResonanceScheduler;
use crate::telemetry::RuntimeTelemetry;
use crate::temporal::TemporalCoordinator;
use crate::types::*;
use std::sync::Arc;
use tokio::sync::RwLock;
#[derive(Clone)]
pub struct MapleRuntime {
inner: Arc<RuntimeInner>,
}
struct RuntimeInner {
resonator_registry: Arc<ResonatorRegistry>,
profile_manager: Arc<ProfileManager>,
presence_fabric: Arc<PresenceFabric>,
coupling_fabric: Arc<CouplingFabric>,
attention_allocator: Arc<AttentionAllocator>,
#[allow(dead_code)]
invariant_guard: Arc<InvariantGuard>,
temporal_coordinator: Arc<TemporalCoordinator>,
scheduler: Arc<ResonanceScheduler>,
telemetry: Arc<RuntimeTelemetry>,
shutdown: Arc<RwLock<bool>>,
}
impl MapleRuntime {
pub async fn bootstrap(config: RuntimeConfig) -> Result<Self, BootstrapError> {
tracing::info!("Bootstrapping MAPLE Resonance Runtime");
tracing::debug!("Phase 1: Initializing safety infrastructure");
let invariant_guard = Arc::new(InvariantGuard::new(&config.invariants));
tracing::debug!("Phase 2: Initializing temporal coordination");
let temporal_coordinator = Arc::new(TemporalCoordinator::new(&config.temporal));
tracing::debug!("Phase 3: Initializing resonance infrastructure");
let attention_allocator = Arc::new(AttentionAllocator::new(&config.attention));
let presence_fabric = Arc::new(PresenceFabric::new(&config.presence));
let coupling_fabric = Arc::new(CouplingFabric::new(
&config.coupling,
Arc::clone(&attention_allocator),
));
tracing::debug!("Phase 4: Cognitive pipeline (placeholder)");
tracing::debug!("Phase 5: Initializing Resonator management");
let profile_manager = Arc::new(ProfileManager::new(&config.profiles));
let resonator_registry = Arc::new(ResonatorRegistry::new(&config.registry));
tracing::debug!("Phase 6: Initializing scheduler and telemetry");
let scheduler = Arc::new(ResonanceScheduler::new(&config.scheduling));
let telemetry = Arc::new(RuntimeTelemetry::new(&config.telemetry));
let inner = RuntimeInner {
resonator_registry,
profile_manager,
presence_fabric,
coupling_fabric,
attention_allocator,
invariant_guard,
temporal_coordinator,
scheduler,
telemetry,
shutdown: Arc::new(RwLock::new(false)),
};
tracing::info!("MAPLE Resonance Runtime bootstrapped successfully");
Ok(Self {
inner: Arc::new(inner),
})
}
pub async fn shutdown(&self) -> Result<(), ShutdownError> {
tracing::info!("Shutting down MAPLE Resonance Runtime");
let mut shutdown = self.inner.shutdown.write().await;
if *shutdown {
tracing::warn!("Runtime already shut down");
return Ok(());
}
*shutdown = true;
drop(shutdown);
tracing::debug!("Step 1: Stopping new commitments");
tracing::debug!("Step 2: Waiting for active commitments");
tracing::debug!("Step 3: Persisting Resonator continuity");
self.inner
.resonator_registry
.persist_all_continuity()
.await
.map_err(|e| ShutdownError::PersistenceError(e.to_string()))?;
tracing::debug!("Step 4: Persisting coupling topology");
self.inner
.coupling_fabric
.persist_topology()
.await
.map_err(|e| ShutdownError::PersistenceError(e.to_string()))?;
tracing::debug!("Step 5: Flushing telemetry");
self.inner.telemetry.flush().await;
tracing::info!("MAPLE Resonance Runtime shutdown complete");
Ok(())
}
pub async fn is_shutting_down(&self) -> bool {
*self.inner.shutdown.read().await
}
pub async fn register_resonator(
&self,
spec: ResonatorSpec,
) -> Result<ResonatorHandle, RegistrationError> {
if self.is_shutting_down().await {
return Err(RegistrationError::InvalidSpec(
"Runtime is shutting down".to_string(),
));
}
self.inner
.profile_manager
.validate_spec(&spec)
.map_err(|e| RegistrationError::ProfileValidation(e))?;
let identity = self
.inner
.resonator_registry
.create_identity(&spec.identity)
.await?;
self.inner
.presence_fabric
.initialize_presence(&identity, &spec.presence)
.await
.map_err(|e| RegistrationError::InvalidSpec(e.to_string()))?;
self.inner
.attention_allocator
.allocate_budget(&identity, &spec.attention)
.await
.map_err(|e| RegistrationError::InvalidSpec(e.to_string()))?;
self.inner
.coupling_fabric
.register(&identity)
.await
.map_err(|e| RegistrationError::InvalidSpec(e.to_string()))?;
let handle = ResonatorHandle::new(identity, self.clone());
self.inner.telemetry.resonator_registered(&handle);
tracing::info!("Registered Resonator: {}", identity);
Ok(handle)
}
pub async fn resume_resonator(
&self,
continuity_proof: ContinuityProof,
) -> Result<ResonatorHandle, ResumeError> {
if self.is_shutting_down().await {
return Err(ResumeError::StateRestorationFailed(
"Runtime is shutting down".to_string(),
));
}
let record = self
.inner
.resonator_registry
.verify_continuity(&continuity_proof)
.await?;
let identity = record.identity;
self.inner
.presence_fabric
.restore_presence(&identity, &record.presence_state)
.await
.map_err(|e| ResumeError::StateRestorationFailed(e.to_string()))?;
self.inner
.attention_allocator
.restore_budget(&identity, &record.attention_state)
.await
.map_err(|e| ResumeError::StateRestorationFailed(e.to_string()))?;
self.inner
.coupling_fabric
.restore_couplings(&identity, &record.couplings)
.await
.map_err(|e| ResumeError::StateRestorationFailed(e.to_string()))?;
let handle = ResonatorHandle::new(identity, self.clone());
self.inner.telemetry.resonator_resumed(&handle);
tracing::info!("Resumed Resonator: {}", identity);
Ok(handle)
}
pub fn presence_fabric(&self) -> &Arc<PresenceFabric> {
&self.inner.presence_fabric
}
pub fn coupling_fabric(&self) -> &Arc<CouplingFabric> {
&self.inner.coupling_fabric
}
pub fn attention_allocator(&self) -> &Arc<AttentionAllocator> {
&self.inner.attention_allocator
}
pub fn temporal_coordinator(&self) -> &Arc<TemporalCoordinator> {
&self.inner.temporal_coordinator
}
pub fn scheduler(&self) -> &Arc<ResonanceScheduler> {
&self.inner.scheduler
}
pub fn telemetry(&self) -> &Arc<RuntimeTelemetry> {
&self.inner.telemetry
}
}
#[derive(Debug, Clone)]
pub struct ResonatorSpec {
pub identity: ResonatorIdentitySpec,
pub profile: ResonatorProfile,
pub capabilities: Vec<CapabilitySpec>,
pub presence: PresenceConfig,
pub attention: AttentionBudgetSpec,
pub initial_memory: Option<MemorySnapshot>,
pub coupling_affinity: CouplingAffinitySpec,
}
impl Default for ResonatorSpec {
fn default() -> Self {
Self {
identity: ResonatorIdentitySpec::default(),
profile: ResonatorProfile::default(),
capabilities: Vec::new(),
presence: PresenceConfig::default(),
attention: AttentionBudgetSpec::default(),
initial_memory: None,
coupling_affinity: CouplingAffinitySpec::default(),
}
}
}
#[derive(Debug, Clone)]
pub struct ResonatorIdentitySpec {
pub name: Option<String>,
pub metadata: std::collections::HashMap<String, String>,
}
impl Default for ResonatorIdentitySpec {
fn default() -> Self {
Self {
name: None,
metadata: std::collections::HashMap::new(),
}
}
}
#[derive(Debug, Clone)]
pub struct CapabilitySpec {
pub name: String,
pub version: String,
}
#[derive(Debug, Clone)]
pub struct MemorySnapshot {
pub data: Vec<u8>,
}