alma 0.1.1

A Bevy-native modal text editor with Vim-style navigation.
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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
use crate::plugin::{
    PluginHostImportDiscardReport, PluginHostImportError, PluginIdentity,
    PluginInstanceAccessError, PluginOperationalEvent, PluginOperationalExport,
    PluginOperationalImport, PluginOperationalRuntimeFailure, PluginRuntimeLimitField,
    PluginWorkspaceObserveTaskEnqueueError, PluginWorkspaceObserveTaskQueueError,
    SealedPluginWorkspaceObserveTaskBatch,
};
use std::fmt::{Debug, Display, Formatter};

/// Redacted Wasmtime or OS failure detail.
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct WasmtimePluginRuntimeFailure {
    /// Failure class only.
    kind: WasmtimePluginRuntimeFailureKind,
}

impl WasmtimePluginRuntimeFailure {
    /// Failure class.
    #[must_use]
    pub const fn kind(self) -> WasmtimePluginRuntimeFailureKind {
        self.kind
    }

    /// Creates a redacted failure class.
    pub(super) const fn new(kind: WasmtimePluginRuntimeFailureKind) -> Self {
        Self { kind }
    }

    /// Drops raw Wasmtime error detail.
    pub(super) const fn from_wasmtime<T>(
        kind: WasmtimePluginRuntimeFailureKind,
        _source: &T,
    ) -> Self {
        Self::new(kind)
    }

    /// Drops raw OS error detail.
    pub(super) const fn from_io(
        kind: WasmtimePluginRuntimeFailureKind,
        _source: &std::io::Error,
    ) -> Self {
        Self::new(kind)
    }
}

/// Closed redacted Wasmtime or OS failure class.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum WasmtimePluginRuntimeFailureKind {
    /// Runtime engine setup.
    Engine,
    /// Runtime epoch driver setup.
    RuntimeTimer,
    /// Component validation or compilation.
    Component,
    /// Host import linker construction.
    Linker,
    /// Component instantiation.
    Instantiate,
    /// Lifecycle export lookup.
    Export,
    /// Fuel setup before guest execution.
    Fuel,
    /// Guest trap during export execution.
    GuestTrap,
    /// Canonical ABI post-return cleanup.
    PostReturn,
}

impl WasmtimePluginRuntimeFailureKind {
    /// Stable redacted failure class text.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Engine => "engine",
            Self::RuntimeTimer => "timer",
            Self::Component => "component",
            Self::Linker => "linker",
            Self::Instantiate => "instantiate",
            Self::Export => "export",
            Self::Fuel => "fuel",
            Self::GuestTrap => "guest trap",
            Self::PostReturn => "post-return",
        }
    }
}

impl Display for WasmtimePluginRuntimeFailureKind {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl Debug for WasmtimePluginRuntimeFailure {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("WasmtimePluginRuntimeFailure")
            .field("kind", &self.kind.as_str())
            .finish()
    }
}

impl Display for WasmtimePluginRuntimeFailure {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.kind.as_str())
    }
}

/// Stable phase for a Wasmtime adapter failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum WasmtimePluginRuntimePhase {
    /// Runtime engine setup.
    Engine,
    /// Component validation or compilation.
    Component,
    /// Host-width runtime limit projection.
    Limit,
    /// Component instantiation.
    Instantiate,
    /// Lifecycle export lookup.
    Export,
    /// Fuel setup.
    Fuel,
    /// Deadline setup.
    Timer,
    /// Guest wall-clock deadline.
    Timeout,
    /// Guest trap outside an expected host import rejection.
    GuestTrap,
    /// Update rejected before guest execution.
    Scheduling,
    /// Host session setup before guest execution.
    UpdateSetup,
    /// Host import rejection during guest execution.
    HostImport,
    /// Runtime instance and host state came from different plugins.
    InstanceStateMismatch,
}

/// Wasmtime observe-task enqueue failure class.
#[derive(Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum WasmtimeWorkspaceObserveTaskEnqueueErrorKind {
    /// Lifecycle state denied scheduling before queue admission.
    SchedulingDenied,
    /// Runtime instance was paired with state for another plugin.
    InstanceStateMismatch,
    /// Runtime instance was paired with a task batch from another plugin.
    BatchIdentityMismatch,
    /// Queue admission failed after lifecycle gating.
    Queue,
}

impl WasmtimeWorkspaceObserveTaskEnqueueErrorKind {
    /// Stable diagnostic spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SchedulingDenied => "scheduling-denied",
            Self::InstanceStateMismatch => "instance-state-mismatch",
            Self::BatchIdentityMismatch => "batch-identity-mismatch",
            Self::Queue => "queue",
        }
    }
}

impl Display for WasmtimeWorkspaceObserveTaskEnqueueErrorKind {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl Debug for WasmtimeWorkspaceObserveTaskEnqueueErrorKind {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Wasmtime observe-task enqueue failure that preserves retryable work.
#[derive(Eq, PartialEq, thiserror::Error)]
#[error("{source}")]
pub struct WasmtimeWorkspaceObserveTaskEnqueueError {
    /// Rejection paired with its still-retryable task batch.
    #[source]
    source: WasmtimeWorkspaceObserveTaskEnqueueErrorSource,
}

/// Runtime/state identities involved in an instance-state mismatch.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WasmtimeWorkspaceObserveTaskInstanceStateMismatchIdentities<'identity> {
    /// Runtime instance identity.
    pub runtime_identity: &'identity PluginIdentity,
    /// Host state identity.
    pub state_identity: &'identity PluginIdentity,
}

/// Runtime/batch identities involved in a task-batch mismatch.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WasmtimeWorkspaceObserveTaskBatchIdentityMismatchIdentities<'identity> {
    /// Runtime instance identity.
    pub runtime_identity: &'identity PluginIdentity,
    /// Task batch identity.
    pub batch_identity: &'identity PluginIdentity,
}

/// Private enqueue rejection payload. Constructors keep the batch and source paired.
#[derive(Debug, Eq, PartialEq, thiserror::Error)]
enum WasmtimeWorkspaceObserveTaskEnqueueErrorSource {
    /// Lifecycle state denied scheduling before queue admission.
    #[error("plugin workspace observe task enqueue denied: {source}")]
    SchedulingDenied {
        /// Lifecycle rejection.
        #[source]
        source: PluginInstanceAccessError,
        /// Still-sealed task batch retained for explicit discard.
        batch: SealedPluginWorkspaceObserveTaskBatch,
    },
    /// Runtime instance was paired with state for another plugin.
    #[error("plugin workspace observe task enqueue denied by instance state mismatch")]
    InstanceStateMismatch {
        /// Runtime instance identity.
        runtime_identity: PluginIdentity,
        /// Host state identity.
        state_identity: PluginIdentity,
        /// Still-sealed task batch retained for explicit discard.
        batch: SealedPluginWorkspaceObserveTaskBatch,
    },
    /// Runtime instance was paired with a task batch for another plugin.
    #[error("plugin workspace observe task enqueue denied by batch identity mismatch")]
    BatchIdentityMismatch {
        /// Runtime instance identity.
        runtime_identity: PluginIdentity,
        /// Task batch identity.
        batch_identity: PluginIdentity,
        /// Still-sealed task batch retained for explicit discard.
        batch: SealedPluginWorkspaceObserveTaskBatch,
    },
    /// Queue admission failed after lifecycle gating.
    #[error(transparent)]
    Queue(#[from] PluginWorkspaceObserveTaskEnqueueError),
}

impl WasmtimeWorkspaceObserveTaskEnqueueError {
    /// Builds a lifecycle-denied enqueue error.
    pub(super) const fn scheduling_denied(
        source: PluginInstanceAccessError,
        batch: SealedPluginWorkspaceObserveTaskBatch,
    ) -> Self {
        Self {
            source: WasmtimeWorkspaceObserveTaskEnqueueErrorSource::SchedulingDenied {
                source,
                batch,
            },
        }
    }

    /// Builds an identity-mismatch enqueue error.
    pub(super) const fn instance_state_mismatch(
        runtime_identity: PluginIdentity,
        state_identity: PluginIdentity,
        batch: SealedPluginWorkspaceObserveTaskBatch,
    ) -> Self {
        Self {
            source: WasmtimeWorkspaceObserveTaskEnqueueErrorSource::InstanceStateMismatch {
                runtime_identity,
                state_identity,
                batch,
            },
        }
    }

    /// Builds a runtime/batch identity-mismatch enqueue error.
    pub(super) const fn batch_identity_mismatch(
        runtime_identity: PluginIdentity,
        batch_identity: PluginIdentity,
        batch: SealedPluginWorkspaceObserveTaskBatch,
    ) -> Self {
        Self {
            source: WasmtimeWorkspaceObserveTaskEnqueueErrorSource::BatchIdentityMismatch {
                runtime_identity,
                batch_identity,
                batch,
            },
        }
    }

    /// Builds a queue-admission enqueue error.
    pub(super) const fn from_queue(source: PluginWorkspaceObserveTaskEnqueueError) -> Self {
        Self {
            source: WasmtimeWorkspaceObserveTaskEnqueueErrorSource::Queue(source),
        }
    }

    /// Returns the closed failure class.
    #[must_use]
    pub const fn kind(&self) -> WasmtimeWorkspaceObserveTaskEnqueueErrorKind {
        match &self.source {
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::SchedulingDenied { .. } => {
                WasmtimeWorkspaceObserveTaskEnqueueErrorKind::SchedulingDenied
            }
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::InstanceStateMismatch { .. } => {
                WasmtimeWorkspaceObserveTaskEnqueueErrorKind::InstanceStateMismatch
            }
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::BatchIdentityMismatch { .. } => {
                WasmtimeWorkspaceObserveTaskEnqueueErrorKind::BatchIdentityMismatch
            }
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::Queue(_) => {
                WasmtimeWorkspaceObserveTaskEnqueueErrorKind::Queue
            }
        }
    }

    /// Returns the sealed batch retained for retry or explicit discard.
    #[must_use]
    pub const fn batch(&self) -> &SealedPluginWorkspaceObserveTaskBatch {
        match &self.source {
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::SchedulingDenied { batch, .. }
            | WasmtimeWorkspaceObserveTaskEnqueueErrorSource::InstanceStateMismatch {
                batch, ..
            }
            | WasmtimeWorkspaceObserveTaskEnqueueErrorSource::BatchIdentityMismatch {
                batch, ..
            } => batch,
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::Queue(source) => source.batch(),
        }
    }

    /// Returns the lifecycle rejection when enqueue was denied before queue admission.
    #[must_use]
    pub const fn scheduling_error(&self) -> Option<&PluginInstanceAccessError> {
        match &self.source {
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::SchedulingDenied { source, .. } => {
                Some(source)
            }
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::InstanceStateMismatch { .. }
            | WasmtimeWorkspaceObserveTaskEnqueueErrorSource::BatchIdentityMismatch { .. }
            | WasmtimeWorkspaceObserveTaskEnqueueErrorSource::Queue(_) => None,
        }
    }

    /// Returns the mismatched runtime and state identities when lifecycle ownership failed.
    #[must_use]
    pub const fn instance_state_mismatch_identities(
        &self,
    ) -> Option<WasmtimeWorkspaceObserveTaskInstanceStateMismatchIdentities<'_>> {
        match &self.source {
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::InstanceStateMismatch {
                runtime_identity,
                state_identity,
                ..
            } => Some(
                WasmtimeWorkspaceObserveTaskInstanceStateMismatchIdentities {
                    runtime_identity,
                    state_identity,
                },
            ),
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::SchedulingDenied { .. }
            | WasmtimeWorkspaceObserveTaskEnqueueErrorSource::BatchIdentityMismatch { .. }
            | WasmtimeWorkspaceObserveTaskEnqueueErrorSource::Queue(_) => None,
        }
    }

    /// Returns the mismatched runtime and task-batch identities.
    #[must_use]
    pub const fn batch_identity_mismatch_identities(
        &self,
    ) -> Option<WasmtimeWorkspaceObserveTaskBatchIdentityMismatchIdentities<'_>> {
        match &self.source {
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::BatchIdentityMismatch {
                runtime_identity,
                batch_identity,
                ..
            } => Some(
                WasmtimeWorkspaceObserveTaskBatchIdentityMismatchIdentities {
                    runtime_identity,
                    batch_identity,
                },
            ),
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::SchedulingDenied { .. }
            | WasmtimeWorkspaceObserveTaskEnqueueErrorSource::InstanceStateMismatch { .. }
            | WasmtimeWorkspaceObserveTaskEnqueueErrorSource::Queue(_) => None,
        }
    }

    /// Returns the queue rejection when lifecycle gating passed.
    #[must_use]
    pub const fn queue_error(&self) -> Option<&PluginWorkspaceObserveTaskQueueError> {
        match &self.source {
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::Queue(source) => {
                Some(source.queue_error())
            }
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::SchedulingDenied { .. }
            | WasmtimeWorkspaceObserveTaskEnqueueErrorSource::InstanceStateMismatch { .. }
            | WasmtimeWorkspaceObserveTaskEnqueueErrorSource::BatchIdentityMismatch { .. } => None,
        }
    }

    /// Redacted operational event for enqueue failures that should be reported.
    #[must_use]
    pub fn operational_event(&self) -> Option<PluginOperationalEvent> {
        match &self.source {
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::SchedulingDenied { .. } => None,
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::InstanceStateMismatch {
                runtime_identity,
                ..
            } => Some(PluginOperationalEvent::runtime_failure(
                runtime_identity,
                PluginOperationalRuntimeFailure::InstanceStateMismatch,
            )),
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::BatchIdentityMismatch {
                runtime_identity,
                ..
            } => Some(PluginOperationalEvent::runtime_failure(
                runtime_identity,
                PluginOperationalRuntimeFailure::BatchIdentityMismatch,
            )),
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::Queue(source) => {
                source.queue_error().operational_event()
            }
        }
    }

    /// Consumes the error and returns the retryable sealed batch.
    #[must_use]
    pub fn into_batch(self) -> SealedPluginWorkspaceObserveTaskBatch {
        match self.source {
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::SchedulingDenied { batch, .. }
            | WasmtimeWorkspaceObserveTaskEnqueueErrorSource::InstanceStateMismatch {
                batch, ..
            }
            | WasmtimeWorkspaceObserveTaskEnqueueErrorSource::BatchIdentityMismatch {
                batch, ..
            } => batch,
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::Queue(source) => source.into_batch(),
        }
    }

    /// Discards the retained sealed batch instead of retrying admission.
    #[must_use]
    pub fn discard_batch(self) -> crate::plugin::PluginWorkspaceObserveTaskDiscardReport {
        self.into_batch().discard()
    }
}

impl Debug for WasmtimeWorkspaceObserveTaskEnqueueError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        let mut debug = formatter.debug_struct("WasmtimeWorkspaceObserveTaskEnqueueError");
        let _debug = debug
            .field("kind", &self.kind())
            .field("batch_identity", self.batch().identity_proof())
            .field("task_count", &self.batch().task_count());
        match &self.source {
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::SchedulingDenied { source, .. } => {
                let _debug = debug.field("scheduling_error", source);
            }
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::InstanceStateMismatch {
                runtime_identity,
                state_identity,
                ..
            } => {
                let _debug = debug
                    .field("runtime_identity", runtime_identity)
                    .field("state_identity", state_identity);
            }
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::BatchIdentityMismatch {
                runtime_identity,
                batch_identity,
                ..
            } => {
                let _debug = debug
                    .field("runtime_identity", runtime_identity)
                    .field("mismatched_batch_identity", batch_identity);
            }
            WasmtimeWorkspaceObserveTaskEnqueueErrorSource::Queue(source) => {
                let _debug = debug.field("queue_error_kind", &source.queue_error().kind());
            }
        }
        debug.finish()
    }
}

/// Wasmtime adapter failure with redacted data.
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum WasmtimePluginRuntimeError {
    /// Engine creation failed.
    Engine {
        /// Failure class.
        failure: WasmtimePluginRuntimeFailure,
    },
    /// Component validation or compilation failed.
    Component {
        /// Stable identity.
        identity: PluginIdentity,
        /// Component bytes.
        byte_len: usize,
        /// Failure class.
        failure: WasmtimePluginRuntimeFailure,
    },
    /// Store limit conversion failed.
    Limit {
        /// Stable identity.
        identity: PluginIdentity,
        /// Config field.
        field: PluginRuntimeLimitField,
        /// Rejected value.
        value: u64,
    },
    /// Component instantiation failed.
    Instantiate {
        /// Stable identity.
        identity: PluginIdentity,
        /// Failure class.
        failure: WasmtimePluginRuntimeFailure,
    },
    /// Lifecycle export was missing or had the wrong type.
    Export {
        /// Stable identity.
        identity: PluginIdentity,
        /// Lifecycle export.
        export: PluginOperationalExport,
        /// Failure class.
        failure: WasmtimePluginRuntimeFailure,
    },
    /// Fuel setup failed before guest execution.
    Fuel {
        /// Stable identity.
        identity: PluginIdentity,
        /// Failure class.
        failure: WasmtimePluginRuntimeFailure,
    },
    /// Deadline setup failed before guest execution.
    Timer {
        /// Stable identity.
        identity: PluginIdentity,
        /// Failure class.
        failure: WasmtimePluginRuntimeFailure,
    },
    /// Runtime epoch driver setup failed.
    RuntimeTimer {
        /// Failure class.
        failure: WasmtimePluginRuntimeFailure,
    },
    /// Guest execution exceeded the wall-clock limit.
    Timeout {
        /// Stable identity.
        identity: PluginIdentity,
        /// Lifecycle export.
        export: PluginOperationalExport,
        /// Timeout cap.
        timeout_ms: u64,
    },
    /// Guest execution trapped.
    GuestTrap {
        /// Stable identity.
        identity: PluginIdentity,
        /// Lifecycle export.
        export: PluginOperationalExport,
        /// Failure class.
        failure: WasmtimePluginRuntimeFailure,
    },
    /// Update was denied before guest execution.
    SchedulingDenied(#[source] crate::plugin::PluginInstanceAccessError),
    /// Host session setup failed before guest execution.
    UpdateSetup {
        /// Stable identity.
        identity: PluginIdentity,
        /// Setup rejection.
        source: PluginHostImportError,
    },
    /// Host import failed during guest execution.
    HostImport {
        /// Stable identity.
        identity: PluginIdentity,
        /// Lifecycle export.
        export: PluginOperationalExport,
        /// Generated host import that failed.
        import: PluginOperationalImport,
        /// Typed import rejection.
        source: PluginHostImportError,
    },
    /// Runtime instance was paired with state for another plugin.
    InstanceStateMismatch {
        /// Runtime instance identity.
        runtime_identity: PluginIdentity,
        /// Host state identity.
        state_identity: PluginIdentity,
    },
    /// Guest update failed after pending work was discarded.
    UpdateFailed {
        /// Original failure.
        source: Box<Self>,
        /// Discard evidence.
        discarded: PluginHostImportDiscardReport,
    },
}

impl WasmtimePluginRuntimeError {
    /// Attaches discard evidence.
    pub(super) fn with_discard(self, discarded: PluginHostImportDiscardReport) -> Self {
        Self::UpdateFailed {
            source: Box::new(self),
            discarded,
        }
    }

    /// Returns the root failure phase.
    #[must_use]
    pub fn phase(&self) -> WasmtimePluginRuntimePhase {
        match self {
            Self::Engine { .. } => WasmtimePluginRuntimePhase::Engine,
            Self::Component { .. } => WasmtimePluginRuntimePhase::Component,
            Self::Limit { .. } => WasmtimePluginRuntimePhase::Limit,
            Self::Instantiate { .. } => WasmtimePluginRuntimePhase::Instantiate,
            Self::Export { .. } => WasmtimePluginRuntimePhase::Export,
            Self::Fuel { .. } => WasmtimePluginRuntimePhase::Fuel,
            Self::Timer { .. } | Self::RuntimeTimer { .. } => WasmtimePluginRuntimePhase::Timer,
            Self::Timeout { .. } => WasmtimePluginRuntimePhase::Timeout,
            Self::GuestTrap { .. } => WasmtimePluginRuntimePhase::GuestTrap,
            Self::SchedulingDenied(_) => WasmtimePluginRuntimePhase::Scheduling,
            Self::UpdateSetup { .. } => WasmtimePluginRuntimePhase::UpdateSetup,
            Self::HostImport { .. } => WasmtimePluginRuntimePhase::HostImport,
            Self::InstanceStateMismatch { .. } => WasmtimePluginRuntimePhase::InstanceStateMismatch,
            Self::UpdateFailed { source, .. } => source.phase(),
        }
    }

    /// Returns discard evidence when a failed update crossed the pending-work boundary.
    #[must_use]
    pub const fn discarded_update(&self) -> Option<&PluginHostImportDiscardReport> {
        match self {
            Self::UpdateFailed { discarded, .. } => Some(discarded),
            _other => None,
        }
    }

    /// Redacted event for observable failures.
    #[must_use]
    pub fn operational_event(&self) -> Option<PluginOperationalEvent> {
        match self {
            Self::Timeout {
                identity,
                timeout_ms,
                ..
            } => Some(PluginOperationalEvent::timeout(identity, *timeout_ms)),
            Self::UpdateSetup { identity, source } => Some(host_import_operational_event(
                identity,
                PluginOperationalImport::HostImport,
                source,
            )),
            Self::HostImport {
                identity,
                import,
                source,
                ..
            } => Some(host_import_operational_event(identity, *import, source)),
            Self::GuestTrap {
                identity,
                export,
                failure,
            } => match operational_failure_from_runtime_failure(failure.kind()) {
                PluginOperationalRuntimeFailure::Export => {
                    Some(PluginOperationalEvent::guest_trap(identity, *export))
                }
                failure => Some(PluginOperationalEvent::runtime_failure(identity, failure)),
            },
            Self::UpdateFailed { source, .. } => source.operational_event(),
            Self::Engine { .. } => Some(PluginOperationalEvent::unscoped_runtime_failure(
                PluginOperationalRuntimeFailure::Engine,
            )),
            Self::RuntimeTimer { .. } => Some(PluginOperationalEvent::unscoped_runtime_failure(
                PluginOperationalRuntimeFailure::RuntimeTimer,
            )),
            Self::Component { identity, .. } => Some(PluginOperationalEvent::runtime_failure(
                identity,
                PluginOperationalRuntimeFailure::Component,
            )),
            Self::Limit { identity, .. } => Some(PluginOperationalEvent::runtime_failure(
                identity,
                PluginOperationalRuntimeFailure::Limit,
            )),
            Self::Instantiate {
                identity, failure, ..
            } => Some(PluginOperationalEvent::runtime_failure(
                identity,
                operational_failure_from_runtime_failure(failure.kind()),
            )),
            Self::Export { identity, .. } => Some(PluginOperationalEvent::runtime_failure(
                identity,
                PluginOperationalRuntimeFailure::Export,
            )),
            Self::Fuel { identity, .. } => Some(PluginOperationalEvent::runtime_failure(
                identity,
                PluginOperationalRuntimeFailure::Fuel,
            )),
            Self::Timer { identity, .. } => Some(PluginOperationalEvent::runtime_failure(
                identity,
                PluginOperationalRuntimeFailure::Timer,
            )),
            Self::InstanceStateMismatch {
                runtime_identity, ..
            } => Some(PluginOperationalEvent::runtime_failure(
                runtime_identity,
                PluginOperationalRuntimeFailure::InstanceStateMismatch,
            )),
            Self::SchedulingDenied(_) => None,
        }
    }
}

impl Debug for WasmtimePluginRuntimeError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        let mut debug = formatter.debug_struct("WasmtimePluginRuntimeError");
        let _debug = debug.field("phase", &self.phase());
        match self {
            Self::Engine { failure } | Self::RuntimeTimer { failure } => {
                let _debug = debug.field("failure", failure);
            }
            Self::Component {
                identity,
                byte_len,
                failure,
            } => {
                let _debug = debug.field("identity", identity);
                let _debug = debug.field("byte_len", byte_len);
                let _debug = debug.field("failure", failure);
            }
            Self::Limit {
                identity,
                field,
                value,
            } => {
                let _debug = debug.field("identity", identity);
                let _debug = debug.field("field", field);
                let _debug = debug.field("value", value);
            }
            Self::Instantiate { identity, failure }
            | Self::Fuel { identity, failure }
            | Self::Timer { identity, failure } => {
                let _debug = debug.field("identity", identity);
                let _debug = debug.field("failure", failure);
            }
            Self::Export {
                identity,
                export,
                failure,
            }
            | Self::GuestTrap {
                identity,
                export,
                failure,
            } => {
                let _debug = debug.field("identity", identity);
                let _debug = debug.field("export", export);
                let _debug = debug.field("failure", failure);
            }
            Self::Timeout {
                identity,
                export,
                timeout_ms,
            } => {
                let _debug = debug.field("identity", identity);
                let _debug = debug.field("export", export);
                let _debug = debug.field("timeout_ms", timeout_ms);
            }
            Self::SchedulingDenied(source) => {
                let _debug = debug.field("source", source);
            }
            Self::UpdateSetup { identity, source } => {
                let _debug = debug.field("identity", identity);
                let _debug = debug.field("source", source);
            }
            Self::HostImport {
                identity,
                export,
                import,
                source,
            } => {
                let _debug = debug.field("identity", identity);
                let _debug = debug.field("export", export);
                let _debug = debug.field("import", import);
                let _debug = debug.field("source", source);
            }
            Self::InstanceStateMismatch {
                runtime_identity,
                state_identity,
            } => {
                let _debug = debug.field("runtime_identity", runtime_identity);
                let _debug = debug.field("state_identity", state_identity);
            }
            Self::UpdateFailed { source, discarded } => {
                let _debug = debug.field("source", source);
                let _debug = debug.field("discarded", discarded);
            }
        }
        debug.finish()
    }
}

impl Display for WasmtimePluginRuntimeError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Engine { .. } => {
                formatter.write_str("plugin Wasmtime engine initialization failed")
            }
            Self::Component {
                identity, byte_len, ..
            } => fmt_component_validation_error(formatter, identity, *byte_len),
            Self::Limit {
                identity,
                field,
                value,
            } => fmt_limit_error(formatter, identity, *field, *value),
            Self::Instantiate { identity, .. } => {
                write!(
                    formatter,
                    "plugin {:?} component instantiation failed",
                    identity.as_str()
                )
            }
            Self::Export {
                identity, export, ..
            } => {
                write!(
                    formatter,
                    "plugin {:?} export {export} is not callable",
                    identity.as_str()
                )
            }
            Self::Fuel { identity, .. } => write!(
                formatter,
                "plugin {:?} fuel setup failed",
                identity.as_str()
            ),
            Self::Timer { identity, .. } => write!(
                formatter,
                "plugin {:?} timeout setup failed",
                identity.as_str()
            ),
            Self::RuntimeTimer { .. } => {
                formatter.write_str("plugin Wasmtime timeout driver setup failed")
            }
            Self::Timeout {
                identity,
                export,
                timeout_ms,
            } => {
                write!(
                    formatter,
                    "plugin {:?} export {export} exceeded {timeout_ms} ms",
                    identity.as_str()
                )
            }
            Self::GuestTrap {
                identity, export, ..
            } => write!(
                formatter,
                "plugin {:?} export {export} trapped",
                identity.as_str()
            ),
            Self::SchedulingDenied(source) => {
                write!(formatter, "plugin scheduling denied: {source}")
            }
            Self::UpdateSetup { identity, source } => {
                write!(
                    formatter,
                    "plugin {:?} update setup failed: {source}",
                    identity.as_str()
                )
            }
            Self::HostImport {
                identity,
                export,
                import,
                source,
            } => {
                write!(
                    formatter,
                    "plugin {:?} export {export} host import {import} failed: {source}",
                    identity.as_str()
                )
            }
            Self::InstanceStateMismatch {
                runtime_identity,
                state_identity,
            } => fmt_instance_state_mismatch(formatter, runtime_identity, state_identity),
            Self::UpdateFailed { source, discarded } => write!(
                formatter,
                "plugin update failed: {source}; discarded {} effects, {} workspace requests, and {} workspace observe tasks",
                discarded.effects().discarded_effects(),
                discarded.workspace_io().discarded_requests(),
                discarded.workspace_observe_tasks().discarded_tasks()
            ),
        }
    }
}

/// Formats component validation failure without exposing component contents.
fn fmt_component_validation_error(
    formatter: &mut Formatter<'_>,
    identity: &PluginIdentity,
    byte_len: usize,
) -> std::fmt::Result {
    write!(
        formatter,
        "plugin {:?} component validation failed for {byte_len} bytes",
        identity.as_str()
    )
}

/// Formats rejected runtime limit projection.
fn fmt_limit_error(
    formatter: &mut Formatter<'_>,
    identity: &PluginIdentity,
    field: PluginRuntimeLimitField,
    value: u64,
) -> std::fmt::Result {
    write!(
        formatter,
        "plugin {:?} runtime limit {field} value {value} does not fit host",
        identity.as_str()
    )
}

/// Formats runtime/state identity mismatch without exposing instance internals.
fn fmt_instance_state_mismatch(
    formatter: &mut Formatter<'_>,
    runtime_identity: &PluginIdentity,
    state_identity: &PluginIdentity,
) -> std::fmt::Result {
    write!(
        formatter,
        "plugin runtime {:?} cannot use state for {:?}",
        runtime_identity.as_str(),
        state_identity.as_str()
    )
}

/// Maps a host import rejection to a redacted operational event.
fn host_import_operational_event(
    identity: &PluginIdentity,
    import: PluginOperationalImport,
    source: &PluginHostImportError,
) -> PluginOperationalEvent {
    source.operational_rejection().map_or_else(
        || PluginOperationalEvent::denied_import(identity, import),
        |reason| PluginOperationalEvent::rejected_import(identity, import, reason),
    )
}

/// Projects Wasmtime failure detail into the operational runtime vocabulary.
const fn operational_failure_from_runtime_failure(
    failure: WasmtimePluginRuntimeFailureKind,
) -> PluginOperationalRuntimeFailure {
    match failure {
        WasmtimePluginRuntimeFailureKind::Engine => PluginOperationalRuntimeFailure::Engine,
        WasmtimePluginRuntimeFailureKind::RuntimeTimer => {
            PluginOperationalRuntimeFailure::RuntimeTimer
        }
        WasmtimePluginRuntimeFailureKind::Component => PluginOperationalRuntimeFailure::Component,
        WasmtimePluginRuntimeFailureKind::Linker => PluginOperationalRuntimeFailure::Linker,
        WasmtimePluginRuntimeFailureKind::Instantiate => {
            PluginOperationalRuntimeFailure::Instantiate
        }
        WasmtimePluginRuntimeFailureKind::Export | WasmtimePluginRuntimeFailureKind::GuestTrap => {
            PluginOperationalRuntimeFailure::Export
        }
        WasmtimePluginRuntimeFailureKind::PostReturn => PluginOperationalRuntimeFailure::PostReturn,
        WasmtimePluginRuntimeFailureKind::Fuel => PluginOperationalRuntimeFailure::Fuel,
    }
}