myc

Self-custodial remote signer for Radroots apps
git clone https://radroots.dev/git/myc.git
Log | Files | Refs | README | LICENSE

runtime_foundation.rs (25911B)


      1 //! Existing-only, join-owned Myc runtime foundation.
      2 
      3 use core::fmt;
      4 use std::{error::Error, sync::mpsc};
      5 
      6 use radroots_service_host::{
      7     HostError, HostErrorKind, ShutdownPhase, TaskClassification, TaskMetadata, TaskName,
      8     TaskSupervisor,
      9 };
     10 use radroots_service_sqlite::{MigrationAppliedAtUnixSeconds, MigrationBuildIdentity};
     11 
     12 use crate::{
     13     MycConfigDocumentV1, MycDecryptedIdentity, MycLocalSignerClient, MycProviderBinding,
     14     MycProviderKind, MycProviderRole, MycRuntimeContext, MycStateHost, MycStateMetadata,
     15     open_myc_encrypted_identity, open_myc_state_read_write, resolve_myc_wrapping_credential,
     16 };
     17 
     18 #[cfg(test)]
     19 const RUNTIME_FOUNDATION_CONTRACT: &str =
     20     include_str!("../contracts/services_hardening/runtime_foundation.v1.json");
     21 
     22 /// Exact version of the Myc runtime-foundation contract.
     23 pub const MYC_RUNTIME_FOUNDATION_CONTRACT_VERSION: u32 = 1;
     24 
     25 /// Closed startup conditions that must all be satisfied before Myc is ready.
     26 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
     27 pub enum MycRuntimePrerequisite {
     28     ExistingState,
     29     TransportProvider,
     30     UserProvider,
     31     DiscoveryProvider,
     32     OutboxRecovery,
     33     RequiredRelayConnectivity,
     34     RequiredRelaySubscription,
     35     AdminListener,
     36     OperationsListener,
     37 }
     38 
     39 impl MycRuntimePrerequisite {
     40     /// Returns the exact machine-contract spelling.
     41     #[must_use]
     42     pub const fn as_str(self) -> &'static str {
     43         match self {
     44             Self::ExistingState => "existing_state",
     45             Self::TransportProvider => "transport_provider",
     46             Self::UserProvider => "user_provider",
     47             Self::DiscoveryProvider => "discovery_provider",
     48             Self::OutboxRecovery => "outbox_recovery",
     49             Self::RequiredRelayConnectivity => "required_relay_connectivity",
     50             Self::RequiredRelaySubscription => "required_relay_subscription",
     51             Self::AdminListener => "admin_listener",
     52             Self::OperationsListener => "operations_listener",
     53         }
     54     }
     55 
     56     const fn reason(self) -> MycRuntimeReadinessReason {
     57         match self {
     58             Self::ExistingState => MycRuntimeReadinessReason::DatabaseSchemaMismatch,
     59             Self::TransportProvider | Self::UserProvider | Self::DiscoveryProvider => {
     60                 MycRuntimeReadinessReason::SignerProviderUnavailable
     61             }
     62             Self::OutboxRecovery => MycRuntimeReadinessReason::OutboxInvariantFailed,
     63             Self::RequiredRelayConnectivity => MycRuntimeReadinessReason::RequiredRelayUnavailable,
     64             Self::RequiredRelaySubscription => MycRuntimeReadinessReason::SubscriberNotActive,
     65             Self::AdminListener => MycRuntimeReadinessReason::AdminListenerFailed,
     66             Self::OperationsListener => MycRuntimeReadinessReason::OperationsListenerFailed,
     67         }
     68     }
     69 }
     70 
     71 /// Closed stable reason vocabulary for an unsatisfied runtime prerequisite.
     72 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
     73 pub enum MycRuntimeReadinessReason {
     74     AdminListenerFailed,
     75     DatabaseSchemaMismatch,
     76     OperationsListenerFailed,
     77     OutboxInvariantFailed,
     78     RequiredRelayUnavailable,
     79     SignerProviderUnavailable,
     80     SubscriberNotActive,
     81 }
     82 
     83 impl MycRuntimeReadinessReason {
     84     /// Returns the exact machine-contract spelling.
     85     #[must_use]
     86     pub const fn as_str(self) -> &'static str {
     87         match self {
     88             Self::AdminListenerFailed => "admin_listener_failed",
     89             Self::DatabaseSchemaMismatch => "database_schema_mismatch",
     90             Self::OperationsListenerFailed => "operations_listener_failed",
     91             Self::OutboxInvariantFailed => "outbox_invariant_failed",
     92             Self::RequiredRelayUnavailable => "required_relay_unavailable",
     93             Self::SignerProviderUnavailable => "signer_provider_unavailable",
     94             Self::SubscriberNotActive => "subscriber_not_active",
     95         }
     96     }
     97 }
     98 
     99 /// Immutable startup-readiness projection derived from admitted configuration.
    100 ///
    101 /// This snapshot is passive evidence. It performs no provider, relay, SQLite,
    102 /// DNS, listener, or filesystem probe when read.
    103 #[derive(Clone, PartialEq, Eq)]
    104 pub struct MycRuntimeReadiness {
    105     required: Box<[MycRuntimePrerequisite]>,
    106     satisfied: Box<[MycRuntimePrerequisite]>,
    107     reasons: Box<[MycRuntimeReadinessReason]>,
    108 }
    109 
    110 impl MycRuntimeReadiness {
    111     /// Returns readiness only when every exact prerequisite is satisfied.
    112     #[must_use]
    113     pub fn is_ready(&self) -> bool {
    114         self.required.len() == self.satisfied.len()
    115             && self
    116                 .required
    117                 .iter()
    118                 .all(|required| self.satisfied.contains(required))
    119     }
    120 
    121     /// Returns the exact ordered prerequisite inventory for this configuration.
    122     #[must_use]
    123     pub fn required(&self) -> &[MycRuntimePrerequisite] {
    124         &self.required
    125     }
    126 
    127     /// Returns the exact ordered prerequisites already proven at construction.
    128     #[must_use]
    129     pub fn satisfied(&self) -> &[MycRuntimePrerequisite] {
    130         &self.satisfied
    131     }
    132 
    133     /// Returns bounded stable reasons for every class of missing prerequisite.
    134     #[must_use]
    135     pub const fn reasons(&self) -> &[MycRuntimeReadinessReason] {
    136         &self.reasons
    137     }
    138 }
    139 
    140 impl fmt::Debug for MycRuntimeReadiness {
    141     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    142         formatter
    143             .debug_struct("MycRuntimeReadiness")
    144             .field("ready", &self.is_ready())
    145             .field("required", &self.required)
    146             .field("satisfied", &self.satisfied)
    147             .field("reasons", &self.reasons)
    148             .finish()
    149     }
    150 }
    151 
    152 /// Stable source-free runtime-foundation failure class.
    153 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    154 pub enum MycRuntimeFoundationErrorKind {
    155     InvalidBinding,
    156     StateOpen,
    157     Provider,
    158     TaskRegistration,
    159     TaskFailure,
    160     Readiness,
    161     Close,
    162 }
    163 
    164 impl MycRuntimeFoundationErrorKind {
    165     /// Returns the stable machine-facing safe code.
    166     #[must_use]
    167     pub const fn code(self) -> &'static str {
    168         match self {
    169             Self::InvalidBinding => "runtime_binding_invalid",
    170             Self::StateOpen => "runtime_state_open_failed",
    171             Self::Provider => "runtime_provider_unavailable",
    172             Self::TaskRegistration => "runtime_task_registration_failed",
    173             Self::TaskFailure => "runtime_task_failed",
    174             Self::Readiness => "runtime_readiness_invalid",
    175             Self::Close => "runtime_close_failed",
    176         }
    177     }
    178 
    179     const fn message(self) -> &'static str {
    180         match self {
    181             Self::InvalidBinding => "Myc runtime binding is invalid",
    182             Self::StateOpen => "Myc existing state could not be opened",
    183             Self::Provider => "Myc provider startup failed",
    184             Self::TaskRegistration => "Myc runtime task registration failed",
    185             Self::TaskFailure => "Myc supervised startup task failed",
    186             Self::Readiness => "Myc readiness prerequisites are invalid",
    187             Self::Close => "Myc runtime foundation could not close",
    188         }
    189     }
    190 }
    191 
    192 /// One redacted source-free runtime-foundation failure.
    193 #[derive(Clone, Copy, PartialEq, Eq)]
    194 pub struct MycRuntimeFoundationError {
    195     kind: MycRuntimeFoundationErrorKind,
    196 }
    197 
    198 impl MycRuntimeFoundationError {
    199     const fn new(kind: MycRuntimeFoundationErrorKind) -> Self {
    200         Self { kind }
    201     }
    202 
    203     /// Returns the stable failure kind.
    204     #[must_use]
    205     pub const fn kind(self) -> MycRuntimeFoundationErrorKind {
    206         self.kind
    207     }
    208 
    209     /// Returns the stable machine-facing safe code.
    210     #[must_use]
    211     pub const fn code(self) -> &'static str {
    212         self.kind.code()
    213     }
    214 }
    215 
    216 impl fmt::Debug for MycRuntimeFoundationError {
    217     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    218         formatter
    219             .debug_struct("MycRuntimeFoundationError")
    220             .field("kind", &self.kind)
    221             .finish()
    222     }
    223 }
    224 
    225 impl fmt::Display for MycRuntimeFoundationError {
    226     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    227         formatter.write_str(self.kind.message())
    228     }
    229 }
    230 
    231 impl Error for MycRuntimeFoundationError {}
    232 
    233 enum MycRuntimeProvider {
    234     EncryptedFile {
    235         role: MycProviderRole,
    236         _identity: MycDecryptedIdentity,
    237     },
    238     LocalSigner {
    239         role: MycProviderRole,
    240         _client: Box<MycLocalSignerClient>,
    241     },
    242 }
    243 
    244 enum ProviderStartupOutcome {
    245     Ready(MycDecryptedIdentity),
    246     ProviderFailure,
    247     TaskFailure,
    248 }
    249 
    250 impl MycRuntimeProvider {
    251     const fn role(&self) -> MycProviderRole {
    252         match self {
    253             Self::EncryptedFile { role, .. } | Self::LocalSigner { role, .. } => *role,
    254         }
    255     }
    256 
    257     const fn kind(&self) -> MycProviderKind {
    258         match self {
    259             Self::EncryptedFile { .. } => MycProviderKind::EncryptedFile,
    260             Self::LocalSigner { .. } => MycProviderKind::LocalSigner,
    261         }
    262     }
    263 }
    264 
    265 /// Existing-only Myc foundation with sealed state, provider, and task ownership.
    266 ///
    267 /// The final relay/admin/process task graph remains owned by later RCLDs. This
    268 /// value cannot be constructed directly or used to extract raw SQLite,
    269 /// provider-secret, task-handle, or cancellation authority.
    270 #[must_use = "the runtime foundation must be shut down so owned tasks and state are joined"]
    271 pub struct MycRuntimeFoundation {
    272     runtime: MycRuntimeContext,
    273     configuration: MycConfigDocumentV1,
    274     metadata: MycStateMetadata,
    275     state: MycStateHost,
    276     providers: Box<[MycRuntimeProvider]>,
    277     readiness: MycRuntimeReadiness,
    278     supervisor: TaskSupervisor,
    279 }
    280 
    281 impl MycRuntimeFoundation {
    282     /// Returns the immutable canonical instance context.
    283     #[must_use]
    284     pub const fn runtime_context(&self) -> &MycRuntimeContext {
    285         &self.runtime
    286     }
    287 
    288     /// Returns the admitted immutable configuration.
    289     #[must_use]
    290     pub const fn configuration(&self) -> &MycConfigDocumentV1 {
    291         &self.configuration
    292     }
    293 
    294     /// Returns metadata proven against the existing state host.
    295     #[must_use]
    296     pub const fn metadata(&self) -> &MycStateMetadata {
    297         &self.metadata
    298     }
    299 
    300     /// Returns the passive startup-readiness snapshot.
    301     #[must_use]
    302     pub const fn readiness(&self) -> &MycRuntimeReadiness {
    303         &self.readiness
    304     }
    305 
    306     /// Returns the configured retained provider kind for one enabled role.
    307     #[must_use]
    308     pub fn provider_kind(&self, role: MycProviderRole) -> Option<MycProviderKind> {
    309         self.providers
    310             .iter()
    311             .find(|provider| provider.role() == role)
    312             .map(MycRuntimeProvider::kind)
    313     }
    314 
    315     /// Requests cancellation, joins every owned task, and explicitly closes state.
    316     pub async fn shutdown(mut self) -> Result<(), MycRuntimeFoundationError> {
    317         self.supervisor.request_cancellation();
    318         let supervised = self.supervisor.supervise().await;
    319         let closed = self.state.close().await;
    320         if supervised.is_err() {
    321             Err(MycRuntimeFoundationError::new(
    322                 MycRuntimeFoundationErrorKind::TaskFailure,
    323             ))
    324         } else if closed.is_err() {
    325             Err(MycRuntimeFoundationError::new(
    326                 MycRuntimeFoundationErrorKind::Close,
    327             ))
    328         } else {
    329             Ok(())
    330         }
    331     }
    332 }
    333 
    334 impl fmt::Debug for MycRuntimeFoundation {
    335     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    336         formatter
    337             .debug_struct("MycRuntimeFoundation")
    338             .field("runtime", &"[redacted]")
    339             .field("configuration", &"[redacted]")
    340             .field("metadata", &"[redacted]")
    341             .field("state", &"[sealed]")
    342             .field("provider_count", &self.providers.len())
    343             .field("readiness", &self.readiness)
    344             .field("task_count", &self.supervisor.task_count())
    345             .finish()
    346     }
    347 }
    348 
    349 /// Opens an existing Myc state host and composes its sealed startup foundation.
    350 ///
    351 /// Missing state is never initialized. Encrypted-file providers are opened on
    352 /// bounded one-shot worker threads that are synchronously joined by
    353 /// `TaskSupervisor`; local-signer clients are constructed without I/O and
    354 /// remain unready until a later governed handshake succeeds. No task handle is
    355 /// detached or returned.
    356 pub async fn open_myc_runtime_foundation(
    357     runtime: MycRuntimeContext,
    358     configuration: MycConfigDocumentV1,
    359     metadata: MycStateMetadata,
    360     applied_at: MigrationAppliedAtUnixSeconds,
    361     build: &MigrationBuildIdentity,
    362 ) -> Result<MycRuntimeFoundation, MycRuntimeFoundationError> {
    363     if !metadata.matches_configuration(&runtime, &configuration) {
    364         return Err(MycRuntimeFoundationError::new(
    365             MycRuntimeFoundationErrorKind::InvalidBinding,
    366         ));
    367     }
    368     let state = open_myc_state_read_write(&runtime, &metadata, applied_at, build)
    369         .await
    370         .map_err(|_| MycRuntimeFoundationError::new(MycRuntimeFoundationErrorKind::StateOpen))?;
    371 
    372     match compose_after_state_open(runtime, configuration, metadata, state).await {
    373         Ok(foundation) => Ok(foundation),
    374         Err(failure) => {
    375             let (error, state) = *failure;
    376             if state.close().await.is_err() {
    377                 Err(MycRuntimeFoundationError::new(
    378                     MycRuntimeFoundationErrorKind::Close,
    379                 ))
    380             } else {
    381                 Err(error)
    382             }
    383         }
    384     }
    385 }
    386 
    387 async fn compose_after_state_open(
    388     runtime: MycRuntimeContext,
    389     configuration: MycConfigDocumentV1,
    390     metadata: MycStateMetadata,
    391     state: MycStateHost,
    392 ) -> Result<MycRuntimeFoundation, Box<(MycRuntimeFoundationError, MycStateHost)>> {
    393     let (providers, readiness, supervisor) =
    394         match compose_runtime_components(&runtime, &configuration).await {
    395             Ok(components) => components,
    396             Err(error) => return Err(Box::new((error, state))),
    397         };
    398     Ok(MycRuntimeFoundation {
    399         runtime,
    400         configuration,
    401         metadata,
    402         state,
    403         providers,
    404         readiness,
    405         supervisor,
    406     })
    407 }
    408 
    409 async fn compose_runtime_components(
    410     runtime: &MycRuntimeContext,
    411     configuration: &MycConfigDocumentV1,
    412 ) -> Result<
    413     (
    414         Box<[MycRuntimeProvider]>,
    415         MycRuntimeReadiness,
    416         TaskSupervisor,
    417     ),
    418     MycRuntimeFoundationError,
    419 > {
    420     let mut supervisor = TaskSupervisor::new();
    421     let mut providers: Vec<Option<MycRuntimeProvider>> = configuration
    422         .provider_contract()
    423         .bindings()
    424         .iter()
    425         .map(|_| None)
    426         .collect();
    427     let mut encrypted = Vec::new();
    428     let mut pending = Vec::new();
    429 
    430     for (index, binding) in configuration
    431         .provider_contract()
    432         .bindings()
    433         .iter()
    434         .cloned()
    435         .enumerate()
    436     {
    437         match binding.kind() {
    438             MycProviderKind::EncryptedFile => {
    439                 let role = binding.role();
    440                 let task = provider_task_metadata(role)?;
    441                 encrypted.push((index, role, binding, task));
    442             }
    443             MycProviderKind::LocalSigner => {
    444                 let role = binding.role();
    445                 let client = MycLocalSignerClient::new(&binding).map_err(|_| {
    446                     MycRuntimeFoundationError::new(MycRuntimeFoundationErrorKind::Provider)
    447                 })?;
    448                 providers[index] = Some(MycRuntimeProvider::LocalSigner {
    449                     role,
    450                     _client: Box::new(client),
    451                 });
    452             }
    453         }
    454     }
    455 
    456     for (index, role, binding, task) in encrypted {
    457         let (sender, receiver) = mpsc::sync_channel(1);
    458         let task_runtime = runtime.clone();
    459         let registered = supervisor.spawn(task, move |_cancellation| async move {
    460             let outcome = match std::thread::Builder::new()
    461                 .name(provider_thread_name(role).to_owned())
    462                 .spawn(move || open_encrypted_provider(&task_runtime, &binding))
    463             {
    464                 Ok(thread) => match thread.join() {
    465                     Ok(Ok(identity)) => ProviderStartupOutcome::Ready(identity),
    466                     Ok(Err(())) => ProviderStartupOutcome::ProviderFailure,
    467                     Err(_) => ProviderStartupOutcome::TaskFailure,
    468                 },
    469                 Err(_) => ProviderStartupOutcome::TaskFailure,
    470             };
    471             let succeeded = matches!(outcome, ProviderStartupOutcome::Ready(_));
    472             let _ = sender.send(outcome);
    473             if succeeded {
    474                 Ok(())
    475             } else {
    476                 Err(HostError::new(HostErrorKind::TaskFailure))
    477             }
    478         });
    479         if registered.is_err() {
    480             supervisor.request_cancellation();
    481             let _ = supervisor.supervise().await;
    482             return Err(MycRuntimeFoundationError::new(
    483                 MycRuntimeFoundationErrorKind::TaskRegistration,
    484             ));
    485         }
    486         pending.push((index, role, receiver));
    487     }
    488 
    489     let supervised = supervisor.supervise().await;
    490     let mut provider_failure = false;
    491     let mut task_failure = false;
    492     for (index, role, receiver) in pending {
    493         match receiver.recv() {
    494             Ok(ProviderStartupOutcome::Ready(identity)) => {
    495                 providers[index] = Some(MycRuntimeProvider::EncryptedFile {
    496                     role,
    497                     _identity: identity,
    498                 });
    499             }
    500             Ok(ProviderStartupOutcome::ProviderFailure) => provider_failure = true,
    501             Ok(ProviderStartupOutcome::TaskFailure) | Err(_) => task_failure = true,
    502         }
    503     }
    504     if task_failure {
    505         return Err(MycRuntimeFoundationError::new(
    506             MycRuntimeFoundationErrorKind::TaskFailure,
    507         ));
    508     }
    509     if provider_failure {
    510         return Err(MycRuntimeFoundationError::new(
    511             MycRuntimeFoundationErrorKind::Provider,
    512         ));
    513     }
    514     if supervised.is_err() {
    515         return Err(MycRuntimeFoundationError::new(
    516             MycRuntimeFoundationErrorKind::TaskFailure,
    517         ));
    518     }
    519     let providers = providers
    520         .into_iter()
    521         .collect::<Option<Vec<_>>>()
    522         .ok_or_else(|| MycRuntimeFoundationError::new(MycRuntimeFoundationErrorKind::Provider))?
    523         .into_boxed_slice();
    524 
    525     let readiness = startup_readiness(configuration, &providers)?;
    526     let lifetime = TaskMetadata::new(
    527         TaskName::new("runtime_lifetime").map_err(|_| {
    528             MycRuntimeFoundationError::new(MycRuntimeFoundationErrorKind::TaskRegistration)
    529         })?,
    530         TaskClassification::Critical,
    531         Some(ShutdownPhase::RejectNewMutations),
    532     )
    533     .map_err(|_| MycRuntimeFoundationError::new(MycRuntimeFoundationErrorKind::TaskRegistration))?;
    534     supervisor
    535         .spawn(lifetime, |cancellation| async move {
    536             cancellation.cancelled().await;
    537             Ok(())
    538         })
    539         .map_err(|_| {
    540             MycRuntimeFoundationError::new(MycRuntimeFoundationErrorKind::TaskRegistration)
    541         })?;
    542 
    543     Ok((providers, readiness, supervisor))
    544 }
    545 
    546 fn open_encrypted_provider(
    547     runtime: &MycRuntimeContext,
    548     binding: &MycProviderBinding,
    549 ) -> Result<MycDecryptedIdentity, ()> {
    550     let credential = resolve_myc_wrapping_credential(runtime, binding).map_err(|_| ())?;
    551     open_myc_encrypted_identity(binding, &credential).map_err(|_| ())
    552 }
    553 
    554 fn provider_task_metadata(
    555     role: MycProviderRole,
    556 ) -> Result<TaskMetadata, MycRuntimeFoundationError> {
    557     TaskMetadata::new(
    558         TaskName::new(provider_task_name(role)).map_err(|_| {
    559             MycRuntimeFoundationError::new(MycRuntimeFoundationErrorKind::TaskRegistration)
    560         })?,
    561         TaskClassification::OneShot,
    562         None,
    563     )
    564     .map_err(|_| MycRuntimeFoundationError::new(MycRuntimeFoundationErrorKind::TaskRegistration))
    565 }
    566 
    567 const fn provider_task_name(role: MycProviderRole) -> &'static str {
    568     match role {
    569         MycProviderRole::Transport => "startup_transport_provider",
    570         MycProviderRole::User => "startup_user_provider",
    571         MycProviderRole::Discovery => "startup_discovery_provider",
    572     }
    573 }
    574 
    575 const fn provider_thread_name(role: MycProviderRole) -> &'static str {
    576     match role {
    577         MycProviderRole::Transport => "myc-provider-transport",
    578         MycProviderRole::User => "myc-provider-user",
    579         MycProviderRole::Discovery => "myc-provider-discovery",
    580     }
    581 }
    582 
    583 fn startup_readiness(
    584     configuration: &MycConfigDocumentV1,
    585     providers: &[MycRuntimeProvider],
    586 ) -> Result<MycRuntimeReadiness, MycRuntimeFoundationError> {
    587     let document = configuration.normalized();
    588     let mut required = vec![
    589         MycRuntimePrerequisite::ExistingState,
    590         MycRuntimePrerequisite::TransportProvider,
    591         MycRuntimePrerequisite::UserProvider,
    592     ];
    593     if configuration
    594         .provider_contract()
    595         .binding(MycProviderRole::Discovery)
    596         .is_some()
    597     {
    598         required.push(MycRuntimePrerequisite::DiscoveryProvider);
    599     }
    600     required.push(MycRuntimePrerequisite::OutboxRecovery);
    601 
    602     let relays = document
    603         .pointer("/relays")
    604         .and_then(serde_json::Value::as_array)
    605         .ok_or_else(readiness_error)?;
    606     if relays.iter().any(|relay| {
    607         relay
    608             .pointer("/required")
    609             .and_then(serde_json::Value::as_bool)
    610             == Some(true)
    611     }) {
    612         required.push(MycRuntimePrerequisite::RequiredRelayConnectivity);
    613     }
    614     if relays.iter().any(|relay| {
    615         relay
    616             .pointer("/required")
    617             .and_then(serde_json::Value::as_bool)
    618             == Some(true)
    619             && relay.pointer("/read").and_then(serde_json::Value::as_bool) == Some(true)
    620     }) {
    621         required.push(MycRuntimePrerequisite::RequiredRelaySubscription);
    622     }
    623     required.push(MycRuntimePrerequisite::AdminListener);
    624     if document
    625         .pointer("/operations/enabled")
    626         .and_then(serde_json::Value::as_bool)
    627         .ok_or_else(readiness_error)?
    628     {
    629         required.push(MycRuntimePrerequisite::OperationsListener);
    630     }
    631 
    632     let mut satisfied = vec![MycRuntimePrerequisite::ExistingState];
    633     for provider in providers {
    634         if provider.kind() == MycProviderKind::EncryptedFile {
    635             satisfied.push(provider_prerequisite(provider.role()));
    636         }
    637     }
    638     satisfied.sort_by_key(|prerequisite| {
    639         required
    640             .iter()
    641             .position(|candidate| candidate == prerequisite)
    642             .unwrap_or(usize::MAX)
    643     });
    644     let mut reasons = required
    645         .iter()
    646         .filter(|prerequisite| !satisfied.contains(prerequisite))
    647         .map(|prerequisite| prerequisite.reason())
    648         .collect::<Vec<_>>();
    649     reasons.sort_unstable();
    650     reasons.dedup();
    651     Ok(MycRuntimeReadiness {
    652         required: required.into_boxed_slice(),
    653         satisfied: satisfied.into_boxed_slice(),
    654         reasons: reasons.into_boxed_slice(),
    655     })
    656 }
    657 
    658 const fn provider_prerequisite(role: MycProviderRole) -> MycRuntimePrerequisite {
    659     match role {
    660         MycProviderRole::Transport => MycRuntimePrerequisite::TransportProvider,
    661         MycProviderRole::User => MycRuntimePrerequisite::UserProvider,
    662         MycProviderRole::Discovery => MycRuntimePrerequisite::DiscoveryProvider,
    663     }
    664 }
    665 
    666 const fn readiness_error() -> MycRuntimeFoundationError {
    667     MycRuntimeFoundationError::new(MycRuntimeFoundationErrorKind::Readiness)
    668 }
    669 
    670 #[cfg(test)]
    671 mod tests {
    672     use super::*;
    673 
    674     #[test]
    675     fn machine_contract_and_closed_names_are_exact() {
    676         let contract: serde_json::Value =
    677             serde_json::from_str(RUNTIME_FOUNDATION_CONTRACT).expect("runtime contract");
    678         assert_eq!(contract["schema"], "radroots.myc.runtime-foundation");
    679         assert_eq!(contract["contract_version"], 1);
    680         let names = contract["readiness_prerequisites"]
    681             .as_array()
    682             .expect("prerequisite inventory")
    683             .iter()
    684             .map(|entry| entry["id"].as_str().expect("prerequisite id"))
    685             .collect::<Vec<_>>();
    686         let expected = [
    687             MycRuntimePrerequisite::ExistingState,
    688             MycRuntimePrerequisite::TransportProvider,
    689             MycRuntimePrerequisite::UserProvider,
    690             MycRuntimePrerequisite::DiscoveryProvider,
    691             MycRuntimePrerequisite::OutboxRecovery,
    692             MycRuntimePrerequisite::RequiredRelayConnectivity,
    693             MycRuntimePrerequisite::RequiredRelaySubscription,
    694             MycRuntimePrerequisite::AdminListener,
    695             MycRuntimePrerequisite::OperationsListener,
    696         ];
    697         assert_eq!(
    698             names,
    699             expected
    700                 .into_iter()
    701                 .map(MycRuntimePrerequisite::as_str)
    702                 .collect::<Vec<_>>()
    703         );
    704         let reasons = contract["readiness_prerequisites"]
    705             .as_array()
    706             .expect("prerequisite inventory")
    707             .iter()
    708             .map(|entry| entry["reason"].as_str().expect("prerequisite reason"))
    709             .collect::<Vec<_>>();
    710         assert_eq!(
    711             reasons,
    712             expected
    713                 .into_iter()
    714                 .map(MycRuntimePrerequisite::reason)
    715                 .map(MycRuntimeReadinessReason::as_str)
    716                 .collect::<Vec<_>>()
    717         );
    718     }
    719 
    720     #[test]
    721     fn safe_errors_cover_the_closed_inventory_without_sources() {
    722         for kind in [
    723             MycRuntimeFoundationErrorKind::InvalidBinding,
    724             MycRuntimeFoundationErrorKind::StateOpen,
    725             MycRuntimeFoundationErrorKind::Provider,
    726             MycRuntimeFoundationErrorKind::TaskRegistration,
    727             MycRuntimeFoundationErrorKind::TaskFailure,
    728             MycRuntimeFoundationErrorKind::Readiness,
    729             MycRuntimeFoundationErrorKind::Close,
    730         ] {
    731             let error = MycRuntimeFoundationError::new(kind);
    732             assert!(!error.code().is_empty());
    733             assert!(Error::source(&error).is_none());
    734             assert!(!format!("{error} {error:?}").contains("source"));
    735         }
    736     }
    737 }