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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
//! Host-owned handles for plugin-visible resources.

use crate::{
    ecs::components::buffer::{BufferEntity, ViewEntity},
    plugin::PluginIdentity,
    text_stream::TextRevision,
};
use std::{
    fmt::{Debug, Display, Formatter},
    num::{NonZeroU64, NonZeroUsize},
};

/// Default maximum live resource handles for one plugin instance.
pub const DEFAULT_PLUGIN_HANDLE_LIMIT: usize = 4096;

/// Host-side handle kind.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PluginHandleKind {
    /// Authoritative editor buffer handle.
    Buffer,
    /// Editor view handle.
    View,
}

impl PluginHandleKind {
    /// Stable redacted handle kind text.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Buffer => "buffer",
            Self::View => "view",
        }
    }
}

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

/// Store generation used to reject handles issued before revocation.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct PluginHandleGeneration(u64);

impl PluginHandleGeneration {
    /// Returns the current generation as a scalar for redacted diagnostics.
    #[must_use]
    pub const fn as_u64(self) -> u64 {
        self.0
    }

    /// Advances the generation after revocation.
    const fn advance(&mut self) {
        self.0 = self.0.saturating_add(1);
    }
}

/// Bounded live-handle count for one plugin instance.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PluginHandleLimit {
    /// Maximum live handles.
    max_handles: NonZeroUsize,
}

impl PluginHandleLimit {
    /// Creates a live-handle limit.
    ///
    /// # Errors
    ///
    /// Returns [`PluginHandleError::ZeroLimit`] when `max_handles` is zero.
    pub const fn try_new(max_handles: usize) -> Result<Self, PluginHandleError> {
        match NonZeroUsize::new(max_handles) {
            Some(max_handles) => Ok(Self { max_handles }),
            None => Err(PluginHandleError::ZeroLimit),
        }
    }

    /// Returns the maximum live handles accepted by the store.
    #[must_use]
    pub const fn max_handles(self) -> usize {
        self.max_handles.get()
    }
}

impl Default for PluginHandleLimit {
    fn default() -> Self {
        Self::try_new(DEFAULT_PLUGIN_HANDLE_LIMIT).expect("default handle limit should be non-zero")
    }
}

/// Guest-visible buffer handle issued by the host.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct PluginBufferHandle {
    /// Per-store opaque identifier; unique within one live generation.
    raw: NonZeroU64,
    /// Store generation in which this handle was issued.
    generation: PluginHandleGeneration,
}

/// Guest-visible view handle issued by the host.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct PluginViewHandle {
    /// Per-store opaque identifier; unique within one live generation.
    raw: NonZeroU64,
    /// Store generation in which this handle was issued.
    generation: PluginHandleGeneration,
}

/// Implements shared diagnostic behavior for typed plugin handles.
macro_rules! impl_plugin_handle {
    ($handle:ident, $kind:expr) => {
        impl $handle {
            /// Returns the redacted diagnostic shape for this handle.
            #[must_use]
            pub const fn shape(self) -> PluginHandleShape {
                PluginHandleShape {
                    kind: $kind,
                    raw: self.raw,
                    generation: self.generation,
                }
            }
        }

        impl Debug for $handle {
            fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
                formatter
                    .debug_tuple(stringify!($handle))
                    .field(&self.shape())
                    .finish()
            }
        }
    };
}

impl_plugin_handle!(PluginBufferHandle, PluginHandleKind::Buffer);
impl_plugin_handle!(PluginViewHandle, PluginHandleKind::View);

/// Redacted handle shape safe for diagnostics.
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct PluginHandleShape {
    /// Resource kind carried by the handle.
    kind: PluginHandleKind,
    /// Per-store opaque identifier suitable for redacted diagnostics.
    raw: NonZeroU64,
    /// Store generation carried by the handle.
    generation: PluginHandleGeneration,
}

impl PluginHandleShape {
    /// Returns the handle kind.
    #[must_use]
    pub const fn kind(self) -> PluginHandleKind {
        self.kind
    }

    /// Returns the store generation encoded into the handle.
    #[must_use]
    pub const fn generation(self) -> PluginHandleGeneration {
        self.generation
    }

    /// Returns the opaque raw identifier.
    #[must_use]
    pub const fn raw(self) -> NonZeroU64 {
        self.raw
    }
}

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

/// Host-side rejection while resolving a plugin handle.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PluginHandleError {
    /// Handle limit must not be zero.
    ZeroLimit,
    /// The plugin instance already holds the maximum accepted live handles.
    TooManyHandles {
        /// Stable plugin identity.
        identity: PluginIdentity,
        /// Maximum accepted live handles.
        limit: usize,
    },
    /// The store exhausted its non-zero handle identifier space.
    ExhaustedIdentifiers {
        /// Stable plugin identity.
        identity: PluginIdentity,
    },
    /// The handle was issued before the current store generation.
    StaleGeneration {
        /// Redacted handle shape.
        handle: PluginHandleShape,
        /// Current store generation.
        current: PluginHandleGeneration,
    },
    /// The handle points at no live host record.
    Missing {
        /// Redacted handle shape.
        handle: PluginHandleShape,
    },
}

impl std::fmt::Display for PluginHandleError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ZeroLimit => formatter.write_str("plugin handle limit must be non-zero"),
            Self::TooManyHandles { identity, limit } => {
                let identity = identity.as_str();
                write!(
                    formatter,
                    "plugin {identity:?} exceeded live handle limit of {limit}"
                )
            }
            Self::ExhaustedIdentifiers { identity } => {
                let identity = identity.as_str();
                write!(
                    formatter,
                    "plugin {identity:?} exhausted handle identifiers"
                )
            }
            Self::StaleGeneration { handle, current } => write!(
                formatter,
                "plugin handle generation {} is stale; current generation is {}",
                handle.generation().as_u64(),
                current.as_u64()
            ),
            Self::Missing { handle } => write!(
                formatter,
                "plugin handle {} is not live in the current store",
                handle.kind()
            ),
        }
    }
}

/// Snapshot captured when a buffer handle is issued.
#[derive(Clone, Eq, PartialEq)]
pub struct PluginBufferSnapshot {
    /// Observed buffer revision.
    revision: TextRevision,
    /// Observed UTF-8 text.
    text: String,
}

impl PluginBufferSnapshot {
    /// Captures trusted host buffer text at a specific revision.
    #[must_use]
    pub fn new(revision: TextRevision, text: impl Into<String>) -> Self {
        Self {
            revision,
            text: text.into(),
        }
    }

    /// Returns the observed revision.
    #[must_use]
    pub const fn revision(&self) -> TextRevision {
        self.revision
    }

    /// Returns observed text.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns observed text length in bytes.
    #[must_use]
    pub const fn byte_len(&self) -> usize {
        self.text.len()
    }
}

impl Debug for PluginBufferSnapshot {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PluginBufferSnapshot")
            .field("revision", &self.revision)
            .field("byte_len", &self.text.len())
            .finish()
    }
}

/// Resolved buffer handle target and provenance.
#[derive(Eq, PartialEq)]
pub struct ResolvedPluginBuffer {
    /// Authoritative host buffer entity.
    target: BufferEntity,
    /// Buffer revision observed when the handle was issued.
    observed_revision: Option<TextRevision>,
    /// Text snapshot observed when the handle was issued.
    observed_snapshot: Option<PluginBufferSnapshot>,
    /// View that produced this buffer authority, when applicable.
    source_view: Option<ViewEntity>,
}

impl ResolvedPluginBuffer {
    /// Returns the authoritative buffer target.
    #[must_use]
    pub const fn target(&self) -> BufferEntity {
        self.target
    }

    /// Returns the buffer revision observed when the handle was issued, if known.
    #[must_use]
    pub const fn observed_revision(&self) -> Option<TextRevision> {
        self.observed_revision
    }

    /// Returns the text snapshot observed when the handle was issued, if captured.
    #[must_use]
    pub const fn observed_snapshot(&self) -> Option<&PluginBufferSnapshot> {
        self.observed_snapshot.as_ref()
    }

    /// Returns the source view associated with this handle, if any.
    #[must_use]
    pub const fn source_view(&self) -> Option<ViewEntity> {
        self.source_view
    }

    /// Returns a diagnostic shape that does not expose ECS ids or buffer text.
    const fn shape(&self) -> ResolvedPluginBufferShape {
        ResolvedPluginBufferShape {
            target: PluginHandleKind::Buffer,
            observed_revision: self.observed_revision,
            has_observed_snapshot: self.observed_snapshot.is_some(),
            has_source_view: self.source_view.is_some(),
        }
    }
}

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

/// Resolved view handle target.
#[derive(Eq, PartialEq)]
pub struct ResolvedPluginView {
    /// Authoritative host view entity.
    target: ViewEntity,
}

impl ResolvedPluginView {
    /// Returns the editor view target.
    #[must_use]
    pub const fn target(&self) -> ViewEntity {
        self.target
    }
}

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

/// Redacted resolved buffer shape.
#[derive(Clone, Debug, Eq, PartialEq)]
struct ResolvedPluginBufferShape {
    /// Host target kind.
    target: PluginHandleKind,
    /// Revision captured when the handle was issued.
    observed_revision: Option<TextRevision>,
    /// Whether a text snapshot is present.
    has_observed_snapshot: bool,
    /// Whether a view produced the buffer authority.
    has_source_view: bool,
}

/// Live buffer handle table entry.
#[derive(Clone, Eq, PartialEq)]
struct BufferHandleRecord {
    /// Handle issued to the guest.
    handle: PluginBufferHandle,
    /// Authoritative host buffer entity.
    target: BufferEntity,
    /// Buffer revision observed when the handle was issued.
    observed_revision: Option<TextRevision>,
    /// Text snapshot observed when the handle was issued.
    observed_snapshot: Option<PluginBufferSnapshot>,
    /// View that produced this buffer authority, when applicable.
    source_view: Option<ViewEntity>,
}

impl BufferHandleRecord {
    /// Returns a diagnostic shape that does not expose ECS ids or buffer text.
    const fn shape(&self) -> BufferHandleRecordShape {
        BufferHandleRecordShape {
            handle: self.handle.shape(),
            target: PluginHandleKind::Buffer,
            observed_revision: self.observed_revision,
            has_observed_snapshot: self.observed_snapshot.is_some(),
            has_source_view: self.source_view.is_some(),
        }
    }
}

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

/// Live view handle table entry.
#[derive(Clone, Copy, Eq, PartialEq)]
struct ViewHandleRecord {
    /// Handle issued to the guest.
    handle: PluginViewHandle,
    /// Authoritative host view entity.
    target: ViewEntity,
}

impl ViewHandleRecord {
    /// Returns a diagnostic shape that does not expose ECS ids.
    const fn shape(self) -> ViewHandleRecordShape {
        ViewHandleRecordShape {
            handle: self.handle.shape(),
            target: PluginHandleKind::View,
        }
    }
}

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

/// Redacted buffer handle record shape.
#[derive(Clone, Debug, Eq, PartialEq)]
struct BufferHandleRecordShape {
    /// Guest-visible handle shape.
    handle: PluginHandleShape,
    /// Host target kind.
    target: PluginHandleKind,
    /// Revision captured when the handle was issued.
    observed_revision: Option<TextRevision>,
    /// Whether a text snapshot is present.
    has_observed_snapshot: bool,
    /// Whether a view produced the buffer authority.
    has_source_view: bool,
}

/// Redacted view handle record shape.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ViewHandleRecordShape {
    /// Guest-visible handle shape.
    handle: PluginHandleShape,
    /// Host target kind.
    target: PluginHandleKind,
}

/// Per-plugin handle table.
#[derive(Eq, PartialEq)]
pub struct PluginHandleStore {
    /// Plugin identity that owns this table.
    identity: PluginIdentity,
    /// Current store generation; revocation advances it and invalidates old handles.
    generation: PluginHandleGeneration,
    /// Maximum live handles accepted for this plugin instance.
    limit: PluginHandleLimit,
    /// Next raw identifier to issue in the current generation.
    next_raw: NonZeroU64,
    /// Live buffer handles issued to the plugin.
    buffers: Vec<BufferHandleRecord>,
    /// Live view handles issued to the plugin.
    views: Vec<ViewHandleRecord>,
}

impl PluginHandleStore {
    /// Creates an empty handle store for one plugin instance.
    #[must_use]
    pub fn new(identity: PluginIdentity) -> Self {
        Self::from_validated_limit(identity, PluginHandleLimit::default())
    }

    /// Creates an empty handle store with an explicit live-handle limit.
    #[must_use]
    pub fn with_limit(identity: PluginIdentity, limit: PluginHandleLimit) -> Self {
        Self::from_validated_limit(identity, limit)
    }

    /// Creates an empty handle store from an already-validated limit proof.
    #[must_use]
    pub(in crate::plugin) fn from_validated_limit(
        identity: PluginIdentity,
        limit: PluginHandleLimit,
    ) -> Self {
        Self {
            identity,
            generation: PluginHandleGeneration::default(),
            limit,
            next_raw: NonZeroU64::MIN,
            buffers: Vec::new(),
            views: Vec::new(),
        }
    }

    /// Returns the plugin identity that owns this handle store.
    #[must_use]
    pub const fn identity(&self) -> &PluginIdentity {
        &self.identity
    }

    /// Returns the current handle generation.
    #[must_use]
    pub const fn generation(&self) -> PluginHandleGeneration {
        self.generation
    }

    /// Returns the configured live-handle limit.
    #[must_use]
    pub const fn limit(&self) -> PluginHandleLimit {
        self.limit
    }

    /// Returns the number of currently live handles across all resource kinds.
    #[must_use]
    pub const fn live_handle_count(&self) -> usize {
        self.buffers.len() + self.views.len()
    }

    /// Invalidates all handles issued by this store.
    pub fn revoke_all(&mut self) {
        self.generation.advance();
        self.buffers.clear();
        self.views.clear();
    }

    /// Issues a buffer handle for a host-owned buffer entity.
    ///
    /// # Errors
    ///
    /// Returns [`PluginHandleError`] when the live-handle cap is exhausted.
    pub fn issue_buffer(
        &mut self,
        target: BufferEntity,
        observed_revision: Option<TextRevision>,
        source_view: Option<ViewEntity>,
    ) -> Result<PluginBufferHandle, PluginHandleError> {
        let raw = self.prepare_raw()?;
        self.commit_raw(raw);
        let handle = PluginBufferHandle {
            raw,
            generation: self.generation,
        };
        self.buffers.push(BufferHandleRecord {
            handle,
            target,
            observed_revision,
            observed_snapshot: None,
            source_view,
        });
        Ok(handle)
    }

    /// Issues a buffer handle with an observed text snapshot.
    ///
    /// # Errors
    ///
    /// Returns [`PluginHandleError`] when the live-handle cap is exhausted.
    pub fn issue_observed_buffer(
        &mut self,
        target: BufferEntity,
        snapshot: PluginBufferSnapshot,
        source_view: Option<ViewEntity>,
    ) -> Result<PluginBufferHandle, PluginHandleError> {
        let observed_revision = Some(snapshot.revision());
        let raw = self.prepare_raw()?;
        self.commit_raw(raw);
        let handle = PluginBufferHandle {
            raw,
            generation: self.generation,
        };
        self.buffers.push(BufferHandleRecord {
            handle,
            target,
            observed_revision,
            observed_snapshot: Some(snapshot),
            source_view,
        });
        Ok(handle)
    }

    /// Issues a view handle for a host-owned view entity.
    ///
    /// # Errors
    ///
    /// Returns [`PluginHandleError`] when the live-handle cap is exhausted.
    pub fn issue_view(
        &mut self,
        target: ViewEntity,
    ) -> Result<PluginViewHandle, PluginHandleError> {
        let raw = self.prepare_raw()?;
        self.commit_raw(raw);
        let handle = PluginViewHandle {
            raw,
            generation: self.generation,
        };
        self.views.push(ViewHandleRecord { handle, target });
        Ok(handle)
    }

    /// Resolves a typed buffer handle.
    ///
    /// # Errors
    ///
    /// Returns [`PluginHandleError`] when the handle belongs to an old generation or no matching
    /// live buffer record exists.
    pub fn resolve_buffer(
        &self,
        handle: PluginBufferHandle,
    ) -> Result<ResolvedPluginBuffer, PluginHandleError> {
        self.ensure_generation(handle.shape())?;
        self.buffers
            .iter()
            .find(|record| record.handle == handle)
            .map(|record| ResolvedPluginBuffer {
                target: record.target,
                observed_revision: record.observed_revision,
                observed_snapshot: record.observed_snapshot.clone(),
                source_view: record.source_view,
            })
            .ok_or_else(|| PluginHandleError::Missing {
                handle: handle.shape(),
            })
    }

    /// Resolves a typed view handle.
    ///
    /// # Errors
    ///
    /// Returns [`PluginHandleError`] when the handle belongs to an old generation or no matching
    /// live view record exists.
    pub fn resolve_view(
        &self,
        handle: PluginViewHandle,
    ) -> Result<ResolvedPluginView, PluginHandleError> {
        self.ensure_generation(handle.shape())?;
        self.views
            .iter()
            .find(|record| record.handle == handle)
            .map(|record| ResolvedPluginView {
                target: record.target,
            })
            .ok_or_else(|| PluginHandleError::Missing {
                handle: handle.shape(),
            })
    }

    /// Returns the first live buffer handle in this store.
    #[cfg(feature = "plugin-runtime")]
    #[must_use]
    pub(in crate::plugin) fn first_buffer_handle(&self) -> Option<PluginBufferHandle> {
        self.buffers.first().map(|record| record.handle)
    }

    /// Returns the first live view handle in this store.
    #[cfg(feature = "plugin-runtime")]
    #[must_use]
    pub(in crate::plugin) fn first_view_handle(&self) -> Option<PluginViewHandle> {
        self.views.first().map(|record| record.handle)
    }

    /// Captures the live handles visible to one guest update.
    #[must_use]
    pub(in crate::plugin) fn snapshot(&self) -> PluginHandleStoreSnapshot {
        PluginHandleStoreSnapshot {
            identity: self.identity.clone(),
            generation: self.generation,
            buffers: self.buffers.clone(),
            views: self.views.clone(),
        }
    }

    /// Returns the next non-zero raw handle identifier without committing it.
    fn prepare_raw(&self) -> Result<NonZeroU64, PluginHandleError> {
        if self.live_handle_count() >= self.limit.max_handles() {
            return Err(PluginHandleError::TooManyHandles {
                identity: self.identity.clone(),
                limit: self.limit.max_handles(),
            });
        }
        let _next = self.next_raw.get().checked_add(1).ok_or_else(|| {
            PluginHandleError::ExhaustedIdentifiers {
                identity: self.identity.clone(),
            }
        })?;
        Ok(self.next_raw)
    }

    /// Commits a prepared raw handle identifier after all fallible issuance work.
    const fn commit_raw(&mut self, raw: NonZeroU64) {
        self.next_raw = NonZeroU64::new(raw.get() + 1)
            .expect("prepare_raw rejects the only overflowing identifier");
    }

    /// Rejects handles that were issued before the current store generation.
    fn ensure_generation(&self, handle: PluginHandleShape) -> Result<(), PluginHandleError> {
        if handle.generation != self.generation {
            return Err(PluginHandleError::StaleGeneration {
                handle,
                current: self.generation,
            });
        }
        Ok(())
    }
}

impl Debug for PluginHandleStore {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PluginHandleStore")
            .field("identity", &self.identity)
            .field("generation", &self.generation)
            .field("limit", &self.limit)
            .field("next_raw", &self.next_raw)
            .field("buffer_handles", &self.buffers.len())
            .field("view_handles", &self.views.len())
            .finish()
    }
}

/// Handle table proof captured for one guest update.
#[derive(Clone, Eq, PartialEq)]
pub(in crate::plugin) struct PluginHandleStoreSnapshot {
    /// Plugin identity that owns the captured handles.
    identity: PluginIdentity,
    /// Generation accepted by this update.
    generation: PluginHandleGeneration,
    /// Captured buffer handles.
    buffers: Vec<BufferHandleRecord>,
    /// Captured view handles.
    views: Vec<ViewHandleRecord>,
}

impl PluginHandleStoreSnapshot {
    /// Resolves a captured buffer handle.
    pub(in crate::plugin) fn resolve_buffer(
        &self,
        handle: PluginBufferHandle,
    ) -> Result<ResolvedPluginBuffer, PluginHandleError> {
        self.ensure_generation(handle.shape())?;
        self.buffers
            .iter()
            .find(|record| record.handle == handle)
            .map(|record| ResolvedPluginBuffer {
                target: record.target,
                observed_revision: record.observed_revision,
                observed_snapshot: record.observed_snapshot.clone(),
                source_view: record.source_view,
            })
            .ok_or_else(|| PluginHandleError::Missing {
                handle: handle.shape(),
            })
    }

    /// Resolves a captured view handle.
    pub(in crate::plugin) fn resolve_view(
        &self,
        handle: PluginViewHandle,
    ) -> Result<ResolvedPluginView, PluginHandleError> {
        self.ensure_generation(handle.shape())?;
        self.views
            .iter()
            .find(|record| record.handle == handle)
            .map(|record| ResolvedPluginView {
                target: record.target,
            })
            .ok_or_else(|| PluginHandleError::Missing {
                handle: handle.shape(),
            })
    }

    /// Rejects handles outside this update generation.
    fn ensure_generation(&self, handle: PluginHandleShape) -> Result<(), PluginHandleError> {
        if handle.generation != self.generation {
            return Err(PluginHandleError::StaleGeneration {
                handle,
                current: self.generation,
            });
        }
        Ok(())
    }
}

impl Debug for PluginHandleStoreSnapshot {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PluginHandleStoreSnapshot")
            .field("identity", &self.identity)
            .field("generation", &self.generation)
            .field("buffer_handles", &self.buffers.len())
            .field("view_handles", &self.views.len())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::{PluginHandleError, PluginHandleKind, PluginHandleLimit, PluginHandleStore};
    use crate::{
        ecs::components::buffer::{BufferEntity, ViewEntity},
        plugin::PluginIdentity,
        text_stream::TextRevision,
    };
    use bevy::prelude::Entity;
    use proptest::prelude::*;

    #[test]
    fn buffer_handles_resolve_to_host_targets_with_revision_provenance() {
        let buffer = BufferEntity(test_entity(1));
        let view = ViewEntity(test_entity(2));
        let mut store = handle_store();

        let handle = store
            .issue_buffer(buffer, Some(TextRevision::from(7)), Some(view))
            .expect("handle issuance should fit");
        let resolved = store
            .resolve_buffer(handle)
            .expect("issued handle should resolve");

        assert_eq!(resolved.target(), buffer);
        assert_eq!(resolved.observed_revision(), Some(TextRevision::from(7)));
        assert_eq!(resolved.source_view(), Some(view));
    }

    #[test]
    fn resolved_handle_debug_redacts_host_targets_and_snapshots() {
        let buffer = BufferEntity(test_entity(1));
        let view = ViewEntity(test_entity(2));
        let mut store = handle_store();

        let buffer_handle = store
            .issue_observed_buffer(
                buffer,
                super::PluginBufferSnapshot::new(TextRevision::from(7), "secret buffer text"),
                Some(view),
            )
            .expect("buffer handle");
        let view_handle = store.issue_view(view).expect("view handle");

        let buffer_debug = format!(
            "{:?}",
            store
                .resolve_buffer(buffer_handle)
                .expect("buffer should resolve")
        );
        let view_debug = format!(
            "{:?}",
            store
                .resolve_view(view_handle)
                .expect("view should resolve")
        );

        assert!(buffer_debug.contains("ResolvedPluginBuffer"));
        assert!(buffer_debug.contains("observed_revision"));
        assert!(buffer_debug.contains("has_observed_snapshot"));
        assert!(buffer_debug.contains("has_source_view"));
        assert!(view_debug.contains("ResolvedPluginView"));
        for debug in [buffer_debug.as_str(), view_debug.as_str()] {
            assert!(!debug.contains("Entity"));
            assert!(!debug.contains("BufferEntity"));
            assert!(!debug.contains("ViewEntity"));
            assert!(!debug.contains("secret"));
            assert!(!debug.contains("buffer text"));
        }
    }

    #[test]
    fn revocation_invalidates_previously_issued_handles() {
        let buffer = BufferEntity(test_entity(1));
        let mut store = handle_store();
        let handle = store
            .issue_buffer(buffer, None, None)
            .expect("handle issuance should fit");
        let old_generation = store.generation();

        store.revoke_all();

        assert_ne!(store.generation(), old_generation);
        assert_eq!(
            store.resolve_buffer(handle),
            Err(PluginHandleError::StaleGeneration {
                handle: handle.shape(),
                current: store.generation(),
            })
        );
    }

    #[test]
    fn snapshots_capture_the_generation_visible_to_one_update() {
        let buffer = BufferEntity(test_entity(1));
        let mut store = handle_store();
        let buffer_handle = store
            .issue_buffer(buffer, Some(TextRevision::from(1)), None)
            .expect("buffer handle");
        let snapshot = store.snapshot();

        store.revoke_all();

        assert_eq!(
            snapshot
                .resolve_buffer(buffer_handle)
                .expect("captured buffer should resolve")
                .target(),
            buffer
        );
        assert_eq!(
            store.resolve_buffer(buffer_handle),
            Err(PluginHandleError::StaleGeneration {
                handle: buffer_handle.shape(),
                current: store.generation(),
            })
        );
    }

    #[test]
    fn handle_store_rejects_zero_limit() {
        assert_eq!(
            PluginHandleLimit::try_new(0),
            Err(PluginHandleError::ZeroLimit)
        );
    }

    #[test]
    fn handle_kinds_have_stable_redacted_text() {
        for (kind, expected) in [
            (PluginHandleKind::Buffer, "buffer"),
            (PluginHandleKind::View, "view"),
        ] {
            assert_eq!(kind.as_str(), expected);
            assert_eq!(kind.to_string(), expected);
        }
    }

    #[test]
    fn handle_store_bounds_live_handles_without_partial_issuance() {
        let mut store = PluginHandleStore::from_validated_limit(
            PluginIdentity::try_new("formatter").expect("identity is valid"),
            PluginHandleLimit::try_new(1).expect("limit should be valid"),
        );

        let _handle = store
            .issue_view(ViewEntity(test_entity(1)))
            .expect("first handle should fit");
        assert_eq!(store.live_handle_count(), 1);

        let error = store
            .issue_view(ViewEntity(test_entity(2)))
            .expect_err("second live handle should exceed limit");

        assert_eq!(
            error,
            PluginHandleError::TooManyHandles {
                identity: PluginIdentity::try_new("formatter").expect("identity is valid"),
                limit: 1,
            }
        );
        assert_eq!(store.live_handle_count(), 1);
    }

    #[test]
    fn revocation_clears_live_handle_count_and_preserves_limit() {
        let mut store = PluginHandleStore::from_validated_limit(
            PluginIdentity::try_new("formatter").expect("identity is valid"),
            PluginHandleLimit::try_new(1).expect("limit should be valid"),
        );
        let _handle = store
            .issue_view(ViewEntity(test_entity(1)))
            .expect("first handle should fit");

        store.revoke_all();

        assert_eq!(store.live_handle_count(), 0);
        assert_eq!(store.limit().max_handles(), 1);
        let _handle = store
            .issue_view(ViewEntity(test_entity(2)))
            .expect("new generation can issue up to the same limit");
        assert_eq!(store.live_handle_count(), 1);
    }

    #[test]
    fn handle_store_debug_redacts_host_targets() {
        let mut store = handle_store();
        let _handle = store
            .issue_buffer(BufferEntity(test_entity(1)), None, None)
            .expect("handle issuance should fit");
        let debug = format!("{store:?}");

        assert!(debug.contains("PluginHandleStore"));
        assert!(debug.contains("buffer_handles"));
        assert!(!debug.contains("Entity"));
    }

    proptest! {
        #[test]
        fn handle_limit_and_revocation_are_generation_scoped(limit in 1usize..32) {
            let mut store = PluginHandleStore::from_validated_limit(
                PluginIdentity::try_new("formatter").expect("identity is valid"),
                PluginHandleLimit::try_new(limit).expect("limit should be valid"),
            );
            let mut handles = Vec::with_capacity(limit);

            for index in 0..limit {
                let target = ViewEntity(test_entity(u32::try_from(index + 1).expect("index fits")));
                let handle = store.issue_view(target).expect("handle issuance should fit");
                prop_assert_eq!(
                    store
                        .resolve_view(handle)
                        .expect("issued handle should resolve")
                        .target(),
                    target
                );
                handles.push(handle);
            }

            prop_assert_eq!(store.live_handle_count(), limit);
            let error = store
                .issue_view(ViewEntity(test_entity(100)))
                .expect_err("over-limit handle should reject");
            prop_assert_eq!(
                error,
                PluginHandleError::TooManyHandles {
                    identity: PluginIdentity::try_new("formatter").expect("identity is valid"),
                    limit,
                }
            );
            prop_assert_eq!(store.live_handle_count(), limit);

            let old_generation = store.generation();
            store.revoke_all();

            prop_assert_ne!(store.generation(), old_generation);
            prop_assert_eq!(store.live_handle_count(), 0);
            for handle in handles {
                prop_assert_eq!(
                    store.resolve_view(handle),
                    Err(PluginHandleError::StaleGeneration {
                        handle: handle.shape(),
                        current: store.generation(),
                    })
                );
            }

            let fresh = store
                .issue_view(ViewEntity(test_entity(200)))
                .expect("new generation should issue up to the same limit");
            prop_assert_eq!(fresh.shape().generation(), store.generation());
        }
    }

    fn handle_store() -> PluginHandleStore {
        PluginHandleStore::new(PluginIdentity::try_new("formatter").expect("identity is valid"))
    }

    fn test_entity(index: u32) -> Entity {
        Entity::from_raw_u32(index).expect("test entity index should be valid")
    }
}