asupersync 0.3.0

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
//! SPORK: OTP-grade supervision, registry, and actor layer for Asupersync.
//!
//! This module provides a unified entry point for all Spork functionality.
//! The module layout mirrors the OTP mental model:
//!
//! | OTP Concept     | Spork Module           | Key Types                              |
//! |-----------------|------------------------|----------------------------------------|
//! | Application     | [`app`]                | `AppSpec`, `AppHandle`, `CompiledApp`  |
//! | Supervisor      | [`supervisor`]         | `SupervisorBuilder`, `ChildSpec`       |
//! | GenServer       | [`gen_server`]         | `GenServer`, `GenServerHandle`, `Reply`, `SystemMsg` |
//! | Registry        | [`registry`]           | `NameRegistry`, `RegistryHandle`, `NameLease` |
//! | Monitor         | [`monitor`]            | `MonitorRef`, `DownReason`             |
//! | Link            | [`link`]               | `LinkRef`, `ExitPolicy`, `ExitSignal`  |
//!
//! # Quick Start
//!
//! ```ignore
//! use asupersync::spork::prelude::*;
//!
//! // Build an application with a supervisor and children
//! let app = AppSpec::new("my_app")
//!     .child(
//!         ChildSpec::new("worker", MyWorkerStart)
//!             .restart_policy(SupervisionStrategy::Restart(
//!                 RestartConfig::default()
//!             ))
//!     )
//!     .start(&mut cx)
//!     .await?;
//!
//! app.stop(&mut cx).await?;
//! ```
//!
//! # Invariant Checklist
//!
//! When adding or reviewing Spork behavior, validate these contracts explicitly:
//!
//! - Region close implies quiescence and no orphan children.
//! - Cancellation follows request -> drain -> finalize with bounded cleanup.
//! - Reply/name/permit obligations are always committed or aborted.
//! - Ordering-sensitive behavior follows deterministic tie-break rules.
//!
//! Canonical references:
//!
//! - [`docs/spork_glossary_invariants.md`](../docs/spork_glossary_invariants.md)
//! - [`docs/spork_deterministic_ordering.md`](../docs/spork_deterministic_ordering.md)
//! - [`docs/replay-debugging.md`](../docs/replay-debugging.md)
//!
//! # Primitive Semantics Matrix
//!
//! | Primitive | Cancellation Semantics | Determinism / Ordering Contract | Obligation Linearity |
//! |-----------|------------------------|---------------------------------|----------------------|
//! | `spork::app` | Region close implies quiescence | Child start/stop ordering follows supervisor contracts | N/A |
//! | `spork::supervisor` | Failed children are drained before restart/escalation | `SUP-START` / `SUP-STOP` ordering in deterministic docs | Child lifecycle transitions remain monotone |
//! | `spork::gen_server` | Request -> drain -> `on_stop` under terminate budget | Mailbox FIFO + `SYS-ORDER` for shutdown messages | Calls create reply obligations that must resolve |
//! | `spork::registry` | Name ownership ends on task/region close | `REG-FIRST` and deterministic collision tie-breaks | Name leases are obligations |
//! | `spork::monitor` | Monitor scope ends with owner region | `DOWN-ORDER`: `(vt, tid)` for batched down notifications | N/A |
//! | `spork::link` | Exit propagation participates in cancel protocol | `SYS-LINK-MONITOR` for `Down`/`Exit` ordering | N/A |
//! | `spork::crash` | Crash artifacts emitted on terminal failure paths | Replay certificates detect ordering divergence | Artifact manifest must remain internally consistent |
//!
//! # Deterministic Failure Triage
//!
//! Standard incident workflow for humans and coding agents:
//!
//! 1. Read `repro_manifest.json` and capture `test_id` + `seed`.
//! 2. Re-run with the same seed and artifact directory.
//! 3. Inspect and verify the trace file.
//! 4. If needed, diff against a known-good trace.
//!
//! ```bash
//! ASUPERSYNC_SEED=<seed> ASUPERSYNC_TEST_ARTIFACTS_DIR=target/test-artifacts \
//!   cargo test <test_id> -- --nocapture
//!
//! cargo run --features cli --bin asupersync -- trace info target/test-artifacts/trace.async
//! cargo run --features cli --bin asupersync -- trace verify --strict \
//!   target/test-artifacts/trace.async
//! cargo run --features cli --bin asupersync -- trace diff <trace_a> <trace_b>
//! ```
//!
//! # Minimal Compile-Time Example
//!
//! ```
//! use asupersync::spork::error::{SporkError, SporkSeverity};
//! use asupersync::spork::prelude::{CastError, RestartConfig, RestartPolicy, SupervisionStrategy};
//!
//! let strategy = SupervisionStrategy::Restart(RestartConfig::default());
//! let policy = RestartPolicy::OneForOne;
//! assert!(matches!(strategy, SupervisionStrategy::Restart(_)));
//! assert!(matches!(policy, RestartPolicy::OneForOne));
//!
//! let err = SporkError::from(CastError::Full);
//! assert_eq!(err.severity(), SporkSeverity::Transient);
//! ```
//!
//! # Prelude
//!
//! The [`prelude`] re-exports the most commonly needed types so that a
//! single `use asupersync::spork::prelude::*` is sufficient for typical
//! supervised application development.
//!
//! # Bead
//!
//! bd-2td4e | Parent: bd-1f3nn

/// Application lifecycle: build, compile, start, stop.
///
/// Re-exports from [`crate::app`].
/// Cancellation semantics: app stop triggers region cancellation and requires
/// quiescence before completion.
pub mod app {
    pub use crate::app::{
        AppCompileError, AppHandle, AppSpawnError, AppSpec, AppStartError, AppStopError,
        CompiledApp, StoppedApp,
    };
}

/// Supervision trees: strategies, child specs, builders.
///
/// Re-exports from [`crate::supervision`].
/// Determinism contract: child start/stop follows compiled ordering and
/// restart policy tie-break rules.
pub mod supervisor {
    pub use crate::supervision::{
        BackoffStrategy, ChildName, ChildSpec, ChildStart, CompiledSupervisor, EscalationPolicy,
        RestartConfig, RestartPolicy, StartTieBreak, StartedChild, SupervisionStrategy,
        SupervisorBuilder, SupervisorCompileError, SupervisorHandle, SupervisorSpawnError,
    };
}

/// Typed request-response actors (GenServer pattern).
///
/// Re-exports from [`crate::gen_server`].
/// Invariant notes:
/// - Cancellation uses request -> drain -> finalize.
/// - Ordering follows mailbox FIFO and shutdown `SYS-ORDER`.
/// - `call` replies are linear obligations (reply or abort).
pub mod gen_server {
    pub use crate::gen_server::{
        CallError, CastError, CastOverflowPolicy, DownMsg, ExitMsg, GenServer, GenServerHandle,
        GenServerRef, InfoError, NamedGenServerStart, Reply, ReplyOutcome, SystemMsg, TimeoutMsg,
        named_gen_server_start,
    };
}

/// Capability-scoped name registry and lease obligations.
///
/// Re-exports from [`crate::cx::registry`].
/// Determinism contract: first-commit collision resolution with stable
/// tie-break behavior in lab mode.
pub mod registry {
    pub use crate::cx::registry::{
        GrantedLease, NameCollisionOutcome, NameCollisionPolicy, NameLease, NameLeaseError,
        NameOwnershipKind, NameOwnershipNotification, NamePermit, NameRegistry, NameWatchRef,
        RegistryCap, RegistryEvent, RegistryHandle,
    };
}

/// Unidirectional down notifications.
///
/// Re-exports from [`crate::monitor`].
/// Ordering contract: batched down notifications are delivered by `(vt, tid)`.
pub mod monitor {
    pub use crate::monitor::{DownNotification, DownReason, MonitorRef};
}

/// Bidirectional exit signal propagation.
///
/// Re-exports from [`crate::link`].
/// Shutdown ordering contract: link exits follow `Down` and precede timeouts
/// for equal virtual timestamps.
pub mod link {
    pub use crate::link::{ExitPolicy, ExitSignal, LinkRef};
}

/// Crash pack format and artifact writing.
///
/// Re-exports from [`crate::trace::crashpack`].
/// Replay contract: crash artifacts preserve deterministic repro commands and
/// schedule certificate correlation.
pub mod crash {
    pub use crate::trace::crashpack::{
        ArtifactId, CrashPack, CrashPackConfig, CrashPackManifest, CrashPackWriteError,
        CrashPackWriter, FailureInfo, FailureOutcome, FileCrashPackWriter, MemoryCrashPackWriter,
        ReplayCommand,
    };
}

/// The SPORK prelude: import this for typical supervised application development.
///
/// ```ignore
/// use asupersync::spork::prelude::*;
/// ```
///
/// This exports the minimal set of types needed to build, run, and debug
/// a supervised application. Advanced types (evidence ledgers, obligation
/// tokens, etc.) are available through the sub-modules.
///
/// # What's Included
///
/// - **App lifecycle**: `AppSpec`, `AppHandle`, `StoppedApp`
/// - **Supervision**: `SupervisorBuilder`, `ChildSpec`, `ChildStart`,
///   `SupervisionStrategy`, `RestartConfig`, `RestartPolicy`
/// - **GenServer**: `GenServer`, `GenServerHandle`, `Reply`,
///   `SystemMsg`, `DownMsg`, `ExitMsg`, `TimeoutMsg`
/// - **Registry**: `NameRegistry`, `RegistryHandle`, `NameLease`
/// - **Monitoring**: `MonitorRef`, `DownReason`, `DownNotification`
/// - **Linking**: `ExitPolicy`, `ExitSignal`, `LinkRef`
/// - **Errors**: `AppStartError`, `CallError`, `CastError`
pub mod prelude {
    // -- Application lifecycle --
    pub use crate::app::{AppHandle, AppSpec, StoppedApp};

    // -- Supervision --
    pub use crate::supervision::{
        BackoffStrategy, ChildName, ChildSpec, ChildStart, RestartConfig, RestartPolicy,
        SupervisionStrategy, SupervisorBuilder,
    };

    // -- GenServer --
    pub use crate::gen_server::{
        CallError, CastError, DownMsg, ExitMsg, GenServer, GenServerHandle, NamedGenServerStart,
        Reply, SystemMsg, TimeoutMsg, named_gen_server_start,
    };

    // -- Registry --
    pub use crate::cx::{NameLease, NameRegistry, RegistryHandle};

    // -- Monitor --
    pub use crate::monitor::{DownNotification, DownReason, MonitorRef};

    // -- Link --
    pub use crate::link::{ExitPolicy, ExitSignal, LinkRef};

    // -- Errors --
    pub use crate::app::{AppCompileError, AppStartError};
    pub use crate::supervision::SupervisorCompileError;

    // -- Unified error --
    pub use super::error::SporkError;
}

// =============================================================================
// Unified Error Taxonomy (bd-2x5xc)
// =============================================================================

/// Unified SPORK error taxonomy.
///
/// Rather than requiring callers to memorize domain-specific error enums
/// (`AppStartError`, `CallError`, `SupervisorCompileError`, ...),
/// `SporkError` provides a single error type that covers all SPORK operations.
///
/// # Domains
///
/// | Domain         | Covers                                      |
/// |----------------|---------------------------------------------|
/// | `Lifecycle`    | `AppStartError`, `AppStopError`             |
/// | `Compile`      | `AppCompileError`, `SupervisorCompileError` |
/// | `Spawn`        | `AppSpawnError`, `SupervisorSpawnError`      |
/// | `Call`         | `GenServerHandle::call()` failures          |
/// | `Cast`         | `GenServerHandle::cast()` failures          |
/// | `Info`         | `GenServerHandle::info()` failures          |
///
/// # Severity
///
/// All variants carry a [`SporkSeverity`] classification that is monotone:
/// a failure that was classified as `Permanent` by its origin domain will
/// never be downgraded by wrapping it in `SporkError`.
///
/// # Example
///
/// ```ignore
/// use asupersync::spork::prelude::*;
///
/// let result: Result<(), SporkError> = app.start(&mut cx).await.map_err(SporkError::from);
/// match result {
///     Err(e) if e.is_permanent() => eprintln!("fatal: {e}"),
///     Err(e) => eprintln!("transient: {e}"),
///     Ok(()) => {},
/// }
/// ```
pub mod error {
    use crate::app::{AppCompileError, AppSpawnError, AppStartError, AppStopError};
    use crate::gen_server::{CallError, CastError, InfoError};
    use crate::runtime::{RegionCreateError, SpawnError};
    use crate::supervision::{SupervisorCompileError, SupervisorSpawnError};

    /// Severity classification for SPORK errors.
    ///
    /// Monotone: wrapping an error in `SporkError` never downgrades severity.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub enum SporkSeverity {
        /// The operation may succeed if retried (e.g., mailbox full).
        Transient,
        /// The operation failed and should not be retried in the same way
        /// (e.g., cycle in topology, server stopped).
        Permanent,
    }

    /// Unified error type for all SPORK operations.
    #[derive(Debug)]
    pub enum SporkError {
        /// Application start failed (compile or spawn phase).
        Start(AppStartError),
        /// Application stop failed.
        Stop(AppStopError),
        /// Supervisor topology compilation failed.
        Compile(AppCompileError),
        /// Supervisor spawn failed.
        Spawn(AppSpawnError),
        /// GenServer `call()` failed.
        Call(CallError),
        /// GenServer `cast()` failed.
        Cast(CastError),
        /// GenServer `info()` send failed.
        Info(InfoError),
    }

    impl SporkError {
        fn region_create_severity(error: &RegionCreateError) -> SporkSeverity {
            match error {
                RegionCreateError::ParentAtCapacity { .. } => SporkSeverity::Transient,
                RegionCreateError::ParentNotFound(_) | RegionCreateError::ParentClosed(_) => {
                    SporkSeverity::Permanent
                }
                RegionCreateError::ResourcePressure { .. } => SporkSeverity::Transient,
            }
        }

        fn runtime_spawn_severity(error: &SpawnError) -> SporkSeverity {
            match error {
                SpawnError::RegionAtCapacity { .. } => SporkSeverity::Transient,
                SpawnError::RuntimeUnavailable
                | SpawnError::RegionNotFound(_)
                | SpawnError::RegionClosed(_)
                | SpawnError::LocalSchedulerUnavailable
                | SpawnError::NameRegistrationFailed { .. } => SporkSeverity::Permanent,
            }
        }

        fn supervisor_spawn_severity(error: &SupervisorSpawnError) -> SporkSeverity {
            match error {
                SupervisorSpawnError::RegionCreate(error) => Self::region_create_severity(error),
                SupervisorSpawnError::ChildStartFailed { err, .. } => {
                    Self::runtime_spawn_severity(err)
                }
                SupervisorSpawnError::DependencyUnavailable {
                    dependency_error, ..
                } => dependency_error
                    .as_ref()
                    .map_or(SporkSeverity::Permanent, Self::runtime_spawn_severity),
            }
        }

        fn app_spawn_severity(error: &AppSpawnError) -> SporkSeverity {
            match error {
                AppSpawnError::RegionCreate(error) => Self::region_create_severity(error),
                AppSpawnError::SpawnFailed(error) => Self::supervisor_spawn_severity(error),
            }
        }

        /// Classify the severity of this error.
        ///
        /// Severity is monotone: permanent errors remain permanent.
        #[must_use]
        pub fn severity(&self) -> SporkSeverity {
            match self {
                Self::Start(AppStartError::CompileFailed(_)) | Self::Stop(_) | Self::Compile(_) => {
                    SporkSeverity::Permanent
                }
                Self::Start(AppStartError::SpawnFailed(error)) | Self::Spawn(error) => {
                    Self::app_spawn_severity(error)
                }
                // Communication errors depend on the variant
                Self::Call(e) => match e {
                    CallError::ServerStopped | CallError::NoReply | CallError::Cancelled(_) => {
                        SporkSeverity::Permanent
                    }
                },
                Self::Cast(e) => match e {
                    CastError::Full => SporkSeverity::Transient,
                    CastError::ServerStopped | CastError::Cancelled(_) => SporkSeverity::Permanent,
                },
                Self::Info(e) => match e {
                    InfoError::Full => SporkSeverity::Transient,
                    InfoError::ServerStopped | InfoError::Cancelled(_) => SporkSeverity::Permanent,
                },
            }
        }

        /// Returns `true` if this error is permanent (should not retry).
        #[must_use]
        pub fn is_permanent(&self) -> bool {
            self.severity() == SporkSeverity::Permanent
        }

        /// Returns `true` if this error is transient (may succeed on retry).
        #[must_use]
        pub fn is_transient(&self) -> bool {
            self.severity() == SporkSeverity::Transient
        }

        /// Returns a short domain tag for this error (e.g., `"start"`, `"call"`).
        #[must_use]
        pub fn domain(&self) -> &'static str {
            match self {
                Self::Start(_) => "start",
                Self::Stop(_) => "stop",
                Self::Compile(_) => "compile",
                Self::Spawn(_) => "spawn",
                Self::Call(_) => "call",
                Self::Cast(_) => "cast",
                Self::Info(_) => "info",
            }
        }
    }

    impl std::fmt::Display for SporkError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                Self::Start(e) => write!(f, "spork start: {e}"),
                Self::Stop(e) => write!(f, "spork stop: {e}"),
                Self::Compile(e) => write!(f, "spork compile: {e}"),
                Self::Spawn(e) => write!(f, "spork spawn: {e}"),
                Self::Call(e) => write!(f, "spork call: {e}"),
                Self::Cast(e) => write!(f, "spork cast: {e}"),
                Self::Info(e) => write!(f, "spork info: {e}"),
            }
        }
    }

    impl std::error::Error for SporkError {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            match self {
                Self::Start(e) => Some(e),
                Self::Stop(e) => Some(e),
                Self::Compile(e) => Some(e),
                Self::Spawn(e) => Some(e),
                Self::Call(e) => Some(e),
                Self::Cast(e) => Some(e),
                Self::Info(e) => Some(e),
            }
        }
    }

    // -- From conversions (zero-cost wrapping) --

    impl From<AppStartError> for SporkError {
        fn from(e: AppStartError) -> Self {
            Self::Start(e)
        }
    }

    impl From<AppStopError> for SporkError {
        fn from(e: AppStopError) -> Self {
            Self::Stop(e)
        }
    }

    impl From<AppCompileError> for SporkError {
        fn from(e: AppCompileError) -> Self {
            Self::Compile(e)
        }
    }

    impl From<AppSpawnError> for SporkError {
        fn from(e: AppSpawnError) -> Self {
            Self::Spawn(e)
        }
    }

    impl From<SupervisorCompileError> for SporkError {
        fn from(e: SupervisorCompileError) -> Self {
            Self::Compile(AppCompileError::SupervisorCompile(e))
        }
    }

    impl From<SupervisorSpawnError> for SporkError {
        fn from(e: SupervisorSpawnError) -> Self {
            Self::Spawn(AppSpawnError::SpawnFailed(e))
        }
    }

    impl From<CallError> for SporkError {
        fn from(e: CallError) -> Self {
            Self::Call(e)
        }
    }

    impl From<CastError> for SporkError {
        fn from(e: CastError) -> Self {
            Self::Cast(e)
        }
    }

    impl From<InfoError> for SporkError {
        fn from(e: InfoError) -> Self {
            Self::Info(e)
        }
    }
}

#[cfg(test)]
#[allow(clippy::no_effect_underscore_binding)]
mod tests {
    use super::*;

    fn init_test(name: &str) {
        crate::test_utils::init_test_logging();
        crate::test_phase!(name);
    }

    #[test]
    fn prelude_imports_compile() {
        init_test("prelude_imports_compile");

        // Verify all prelude types are accessible
        let _ = std::any::type_name::<prelude::AppSpec>();
        let _ = std::any::type_name::<prelude::AppHandle>();
        let _ = std::any::type_name::<prelude::StoppedApp>();
        let _ = std::any::type_name::<prelude::SupervisorBuilder>();
        let _ = std::any::type_name::<prelude::ChildSpec>();
        let _ = std::any::type_name::<prelude::RestartConfig>();
        let _ = std::any::type_name::<prelude::SupervisionStrategy>();
        let _ = std::any::type_name::<prelude::RestartPolicy>();
        let _ = std::any::type_name::<prelude::BackoffStrategy>();
        let _ = std::any::type_name::<prelude::NameRegistry>();
        let _ = std::any::type_name::<prelude::RegistryHandle>();
        let _ = std::any::type_name::<prelude::NameLease>();
        let _ = std::any::type_name::<prelude::MonitorRef>();
        let _ = std::any::type_name::<prelude::DownReason>();
        let _ = std::any::type_name::<prelude::DownNotification>();
        let _ = std::any::type_name::<prelude::DownMsg>();
        let _ = std::any::type_name::<prelude::ExitMsg>();
        let _ = std::any::type_name::<prelude::TimeoutMsg>();
        let _ = std::any::type_name::<prelude::ExitPolicy>();
        let _ = std::any::type_name::<prelude::LinkRef>();
        let _ = std::any::type_name::<prelude::CallError>();
        let _ = std::any::type_name::<prelude::CastError>();
        let _ = std::any::type_name::<prelude::AppStartError>();
        let _ = std::any::type_name::<prelude::AppCompileError>();
        let _ = std::any::type_name::<prelude::SupervisorCompileError>();

        crate::test_complete!("prelude_imports_compile");
    }

    #[test]
    fn submodule_types_accessible() {
        init_test("submodule_types_accessible");

        // App sub-module
        let _ = std::any::type_name::<app::CompiledApp>();
        let _ = std::any::type_name::<app::AppSpawnError>();
        let _ = std::any::type_name::<app::AppStopError>();

        // Supervisor sub-module
        let _ = std::any::type_name::<supervisor::CompiledSupervisor>();
        let _ = std::any::type_name::<supervisor::EscalationPolicy>();
        let _ = std::any::type_name::<supervisor::StartTieBreak>();
        let _ = std::any::type_name::<supervisor::SupervisorHandle>();
        let _ = std::any::type_name::<supervisor::StartedChild>();
        let _ = std::any::type_name::<supervisor::SupervisorSpawnError>();

        // GenServer sub-module
        let _ = std::any::type_name::<gen_server::CastOverflowPolicy>();
        let _ = std::any::type_name::<gen_server::InfoError>();
        let _ = std::any::type_name::<gen_server::ReplyOutcome>();
        let _ = std::any::type_name::<gen_server::DownMsg>();
        let _ = std::any::type_name::<gen_server::ExitMsg>();
        let _ = std::any::type_name::<gen_server::TimeoutMsg>();

        // Registry sub-module
        let _ = std::any::type_name::<registry::NameRegistry>();
        let _ = std::any::type_name::<registry::RegistryHandle>();
        let _ = std::any::type_name::<registry::NameLease>();
        let _ = std::any::type_name::<registry::NameCollisionPolicy>();

        // Monitor sub-module
        let _ = std::any::type_name::<monitor::MonitorRef>();

        // Link sub-module
        let _ = std::any::type_name::<link::ExitPolicy>();

        // Crash sub-module
        let _ = std::any::type_name::<crash::CrashPack>();
        let _ = std::any::type_name::<crash::CrashPackConfig>();
        let _ = std::any::type_name::<crash::ReplayCommand>();

        crate::test_complete!("submodule_types_accessible");
    }

    #[test]
    fn supervision_strategy_constructible() {
        init_test("supervision_strategy_constructible");

        // Verify the prelude types can actually be used to construct values
        let _stop = prelude::SupervisionStrategy::Stop;
        let _restart = prelude::SupervisionStrategy::Restart(prelude::RestartConfig::default());
        let _escalate = prelude::SupervisionStrategy::Escalate;

        let _one_for_one = prelude::RestartPolicy::OneForOne;
        let _one_for_all = prelude::RestartPolicy::OneForAll;
        let _rest_for_one = prelude::RestartPolicy::RestForOne;

        let _none = prelude::BackoffStrategy::None;

        crate::test_complete!("supervision_strategy_constructible");
    }

    #[test]
    fn down_reason_constructible() {
        init_test("down_reason_constructible");

        let _normal = prelude::DownReason::Normal;
        let _error = prelude::DownReason::Error("oops".to_string());

        crate::test_complete!("down_reason_constructible");
    }

    #[test]
    fn exit_policy_constructible() {
        init_test("exit_policy_constructible");

        let _prop = prelude::ExitPolicy::Propagate;
        let _trap = prelude::ExitPolicy::Trap;
        let _ignore = prelude::ExitPolicy::Ignore;

        crate::test_complete!("exit_policy_constructible");
    }

    // =====================================================================
    // Unified Error Taxonomy tests (bd-2x5xc)
    // =====================================================================

    mod error_taxonomy {
        use crate::app::{AppCompileError, AppSpawnError, AppStartError, AppStopError};
        use crate::gen_server::{CallError, CastError, InfoError};
        use crate::runtime::{RegionCreateError, SpawnError};
        use crate::spork::error::{SporkError, SporkSeverity};
        use crate::supervision::{SupervisorCompileError, SupervisorSpawnError};
        use crate::types::RegionId;
        use crate::util::arena::ArenaIndex;

        fn dummy_region_id() -> RegionId {
            RegionId::from_arena(ArenaIndex::new(0, 0))
        }

        fn parent_capacity_error(region: RegionId) -> RegionCreateError {
            RegionCreateError::ParentAtCapacity {
                region,
                limit: 1,
                live: 1,
            }
        }

        fn region_task_capacity_error(region: RegionId) -> SpawnError {
            SpawnError::RegionAtCapacity {
                region,
                limit: 1,
                live: 1,
            }
        }

        fn init_test(name: &str) {
            crate::test_utils::init_test_logging();
            crate::test_phase!(name);
        }

        // -- From conversions --

        #[test]
        fn from_call_error() {
            init_test("from_call_error");
            let e: SporkError = CallError::ServerStopped.into();
            assert!(matches!(e, SporkError::Call(CallError::ServerStopped)));
            crate::test_complete!("from_call_error");
        }

        #[test]
        fn from_cast_error() {
            init_test("from_cast_error");
            let e: SporkError = CastError::Full.into();
            assert!(matches!(e, SporkError::Cast(CastError::Full)));
            crate::test_complete!("from_cast_error");
        }

        #[test]
        fn from_info_error() {
            init_test("from_info_error");
            let e: SporkError = InfoError::ServerStopped.into();
            assert!(matches!(e, SporkError::Info(InfoError::ServerStopped)));
            crate::test_complete!("from_info_error");
        }

        #[test]
        fn from_app_compile_error() {
            init_test("from_app_compile_error");
            let inner = AppCompileError::SupervisorCompile(
                SupervisorCompileError::DuplicateChildName("dup".into()),
            );
            let e: SporkError = inner.into();
            assert!(matches!(e, SporkError::Compile(_)));
            crate::test_complete!("from_app_compile_error");
        }

        #[test]
        fn from_supervisor_compile_error() {
            init_test("from_supervisor_compile_error");
            let inner = SupervisorCompileError::DuplicateChildName("x".into());
            let e: SporkError = inner.into();
            // Should wrap via AppCompileError::SupervisorCompile
            assert!(matches!(
                e,
                SporkError::Compile(AppCompileError::SupervisorCompile(_))
            ));
            crate::test_complete!("from_supervisor_compile_error");
        }

        #[test]
        fn from_app_start_error() {
            init_test("from_app_start_error");
            let inner = AppStartError::CompileFailed(AppCompileError::SupervisorCompile(
                SupervisorCompileError::DuplicateChildName("a".into()),
            ));
            let e: SporkError = inner.into();
            assert!(matches!(e, SporkError::Start(_)));
            crate::test_complete!("from_app_start_error");
        }

        #[test]
        fn from_app_stop_error() {
            init_test("from_app_stop_error");
            let inner = AppStopError::RegionNotFound(dummy_region_id());
            let e: SporkError = inner.into();
            assert!(matches!(e, SporkError::Stop(_)));
            crate::test_complete!("from_app_stop_error");
        }

        // -- Severity classification --

        #[test]
        fn severity_permanent_lifecycle() {
            init_test("severity_permanent_lifecycle");
            let e = SporkError::Start(AppStartError::CompileFailed(
                AppCompileError::SupervisorCompile(SupervisorCompileError::DuplicateChildName(
                    "a".into(),
                )),
            ));
            assert_eq!(e.severity(), SporkSeverity::Permanent);
            assert!(e.is_permanent());
            assert!(!e.is_transient());
            crate::test_complete!("severity_permanent_lifecycle");
        }

        #[test]
        fn severity_permanent_call() {
            init_test("severity_permanent_call");
            let e = SporkError::Call(CallError::ServerStopped);
            assert_eq!(e.severity(), SporkSeverity::Permanent);
            assert!(e.is_permanent());
            crate::test_complete!("severity_permanent_call");
        }

        #[test]
        fn severity_transient_cast_full() {
            init_test("severity_transient_cast_full");
            let e = SporkError::Cast(CastError::Full);
            assert_eq!(e.severity(), SporkSeverity::Transient);
            assert!(e.is_transient());
            assert!(!e.is_permanent());
            crate::test_complete!("severity_transient_cast_full");
        }

        #[test]
        fn severity_transient_info_full() {
            init_test("severity_transient_info_full");
            let e = SporkError::Info(InfoError::Full);
            assert_eq!(e.severity(), SporkSeverity::Transient);
            assert!(e.is_transient());
            crate::test_complete!("severity_transient_info_full");
        }

        #[test]
        fn severity_permanent_cast_stopped() {
            init_test("severity_permanent_cast_stopped");
            let e = SporkError::Cast(CastError::ServerStopped);
            assert_eq!(e.severity(), SporkSeverity::Permanent);
            crate::test_complete!("severity_permanent_cast_stopped");
        }

        #[test]
        fn severity_transient_spawn_parent_capacity() {
            init_test("severity_transient_spawn_parent_capacity");
            let region = dummy_region_id();
            let e = SporkError::Spawn(AppSpawnError::RegionCreate(parent_capacity_error(region)));
            assert_eq!(e.severity(), SporkSeverity::Transient);
            assert!(e.is_transient());
            crate::test_complete!("severity_transient_spawn_parent_capacity");
        }

        #[test]
        fn severity_transient_start_parent_capacity() {
            init_test("severity_transient_start_parent_capacity");
            let region = dummy_region_id();
            let e = SporkError::Start(AppStartError::SpawnFailed(AppSpawnError::RegionCreate(
                parent_capacity_error(region),
            )));
            assert_eq!(e.severity(), SporkSeverity::Transient);
            assert!(e.is_transient());
            crate::test_complete!("severity_transient_start_parent_capacity");
        }

        #[test]
        fn severity_transient_spawn_child_start_region_capacity() {
            init_test("severity_transient_spawn_child_start_region_capacity");
            let region = dummy_region_id();
            let e = SporkError::Spawn(AppSpawnError::SpawnFailed(
                SupervisorSpawnError::ChildStartFailed {
                    child: "worker".into(),
                    err: region_task_capacity_error(region),
                    region,
                },
            ));
            assert_eq!(e.severity(), SporkSeverity::Transient);
            assert!(e.is_transient());
            crate::test_complete!("severity_transient_spawn_child_start_region_capacity");
        }

        #[test]
        fn severity_transient_spawn_dependency_unavailable_preserves_root_cause() {
            init_test("severity_transient_spawn_dependency_unavailable_preserves_root_cause");
            let region = dummy_region_id();
            let e = SporkError::Spawn(AppSpawnError::SpawnFailed(
                SupervisorSpawnError::DependencyUnavailable {
                    child: "api".into(),
                    dependency: "db".into(),
                    dependency_error: Some(region_task_capacity_error(region)),
                    region,
                },
            ));
            assert_eq!(e.severity(), SporkSeverity::Transient);
            assert!(e.is_transient());
            crate::test_complete!(
                "severity_transient_spawn_dependency_unavailable_preserves_root_cause"
            );
        }

        // -- Domain tags --

        #[test]
        fn domain_tags() {
            init_test("domain_tags");
            assert_eq!(
                SporkError::Start(AppStartError::CompileFailed(
                    AppCompileError::SupervisorCompile(SupervisorCompileError::DuplicateChildName(
                        "a".into()
                    ))
                ))
                .domain(),
                "start"
            );
            assert_eq!(
                SporkError::Stop(AppStopError::RegionNotFound(dummy_region_id())).domain(),
                "stop"
            );
            assert_eq!(
                SporkError::Compile(AppCompileError::SupervisorCompile(
                    SupervisorCompileError::DuplicateChildName("a".into())
                ))
                .domain(),
                "compile"
            );
            assert_eq!(SporkError::Call(CallError::ServerStopped).domain(), "call");
            assert_eq!(SporkError::Cast(CastError::Full).domain(), "cast");
            assert_eq!(SporkError::Info(InfoError::ServerStopped).domain(), "info");
            crate::test_complete!("domain_tags");
        }

        // -- Display --

        #[test]
        fn display_format() {
            init_test("display_format");
            let e = SporkError::Call(CallError::ServerStopped);
            let s = format!("{e}");
            assert!(s.starts_with("spork call:"), "got: {s}");

            let e2 = SporkError::Cast(CastError::Full);
            let s2 = format!("{e2}");
            assert!(s2.starts_with("spork cast:"), "got: {s2}");
            crate::test_complete!("display_format");
        }

        // -- Error source chain --

        #[test]
        fn error_source_chain() {
            init_test("error_source_chain");
            let e = SporkError::Call(CallError::NoReply);
            let source = std::error::Error::source(&e);
            assert!(source.is_some(), "SporkError should have a source");
            crate::test_complete!("error_source_chain");
        }

        // -- SporkSeverity ordering --

        #[test]
        fn severity_ordering() {
            init_test("severity_ordering");
            assert!(SporkSeverity::Transient < SporkSeverity::Permanent);
            crate::test_complete!("severity_ordering");
        }
    }
}