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
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
//! Plugin proposal lane model.

use crate::{
    buffer::{BufferEditKind, BufferEditShape},
    ecs::{
        components::buffer::BufferEntity,
        events::edit::{
            PluginBufferEditProposalReceipt, PluginBufferEditProvenance, PluginProposalId,
            RevisionGuardedBufferEditRequested,
        },
    },
    plugin::{
        PluginIdentity, PluginOperationalEvent, PluginOperationalQueue, PluginProposalReviewMode,
        ValidatedPluginRegistry,
    },
    text_stream::{TextRange, TextRevision},
};
use bevy::prelude::Resource;
use std::{
    collections::VecDeque,
    fmt::{Debug, Display, Formatter},
    num::{NonZeroU64, NonZeroUsize},
};

/// Fallback pending proposal cap.
pub const DEFAULT_PLUGIN_PROPOSAL_LANE_LIMIT: usize = 1024;
/// Fallback retained proposal receipt cap.
pub const DEFAULT_PLUGIN_PROPOSAL_RECEIPT_LOG_LIMIT: usize = 1024;

/// Pending plugin proposal cap.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PluginProposalLaneLimit {
    /// Pending proposals accepted before UI or policy decisions.
    max_pending: NonZeroUsize,
}

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

    /// Returns the pending proposal cap.
    #[must_use]
    pub const fn max_pending(self) -> usize {
        self.max_pending.get()
    }

    /// Returns the pending proposal cap as a non-zero proof for diagnostics.
    #[must_use]
    const fn max_pending_limit(self) -> NonZeroUsize {
        self.max_pending
    }
}

impl Default for PluginProposalLaneLimit {
    fn default() -> Self {
        Self::try_new(DEFAULT_PLUGIN_PROPOSAL_LANE_LIMIT)
            .expect("default proposal lane limit should be non-zero")
    }
}

/// Policy for the plugin proposal lane.
#[derive(Clone, Debug, Eq, PartialEq, Resource)]
pub struct PluginProposalLanePolicy {
    /// Fallback review mode for proposals without a configured enabled plugin.
    default_buffer_edit_mode: PluginProposalReviewMode,
    /// Per-plugin review modes derived from validated config.
    plugin_buffer_edit_modes: Vec<(PluginIdentity, PluginProposalReviewMode)>,
}

impl PluginProposalLanePolicy {
    /// Creates a policy with an explicit fallback review mode.
    #[must_use]
    pub const fn new(mode: PluginProposalReviewMode) -> Self {
        Self {
            default_buffer_edit_mode: mode,
            plugin_buffer_edit_modes: Vec::new(),
        }
    }

    /// Derives per-plugin proposal policy from validated static config.
    #[must_use]
    pub fn from_validated_registry(registry: &ValidatedPluginRegistry) -> Self {
        let plugin_buffer_edit_modes = registry
            .enabled_plugins()
            .map(|plugin| {
                (
                    plugin.identity().clone(),
                    plugin.proposal_policy().buffer_edit_review_mode(),
                )
            })
            .collect();

        Self {
            default_buffer_edit_mode: PluginProposalReviewMode::AutoApply,
            plugin_buffer_edit_modes,
        }
    }

    /// Returns the fallback review mode.
    #[must_use]
    pub const fn default_buffer_edit_mode(&self) -> PluginProposalReviewMode {
        self.default_buffer_edit_mode
    }

    /// Returns the review mode for a plugin's buffer edit proposals.
    #[must_use]
    pub fn buffer_edit_mode_for(&self, identity: &PluginIdentity) -> PluginProposalReviewMode {
        self.plugin_buffer_edit_modes
            .iter()
            .find_map(|(plugin, mode)| (plugin == identity).then_some(*mode))
            .unwrap_or(self.default_buffer_edit_mode)
    }
}

impl Default for PluginProposalLanePolicy {
    fn default() -> Self {
        Self::new(PluginProposalReviewMode::AutoApply)
    }
}

/// Host-visible plugin proposals awaiting a decision.
#[derive(Resource)]
pub struct PluginProposalLane {
    /// Pending proposal cap.
    limit: PluginProposalLaneLimit,
    /// Next allocated proposal id.
    next_id: NonZeroU64,
    /// Pending buffer edit proposals.
    buffer_edits: VecDeque<PendingPluginBufferEditProposal>,
}

impl PluginProposalLane {
    /// Creates an empty proposal lane.
    #[must_use]
    pub const fn with_limit(limit: PluginProposalLaneLimit) -> Self {
        Self {
            limit,
            next_id: NonZeroU64::MIN,
            buffer_edits: VecDeque::new(),
        }
    }

    /// Queues a buffer edit proposal for policy or UI decision.
    ///
    /// # Errors
    ///
    /// Returns [`PluginProposalLaneError`] when the lane is full or id allocation is exhausted.
    pub fn push_buffer_edit(
        &mut self,
        request: RevisionGuardedBufferEditRequested,
    ) -> Result<PluginProposalId, PluginProposalLaneError> {
        let identity = request.provenance.source_identity_proof().clone();
        if self.buffer_edits.len() >= self.limit.max_pending() {
            return Err(PluginProposalLaneError::TooManyPending {
                identity,
                limit: self.limit.max_pending_limit(),
            });
        }
        let id = self.allocate_id(&identity)?;
        let request = request.with_proposal_id(id);
        self.buffer_edits
            .push_back(PendingPluginBufferEditProposal { id, request });
        Ok(id)
    }

    /// Removes a pending proposal and returns its owner-boundary request.
    ///
    /// # Errors
    ///
    /// Returns [`PluginProposalDecisionError::UnknownProposal`] when `id` is no longer pending.
    pub fn take_buffer_edit_for_apply(
        &mut self,
        id: PluginProposalId,
    ) -> Result<RevisionGuardedBufferEditRequested, PluginProposalDecisionError> {
        let index = self
            .buffer_edits
            .iter()
            .position(|proposal| proposal.id == id)
            .ok_or(PluginProposalDecisionError::UnknownProposal { id })?;
        Ok(self
            .buffer_edits
            .remove(index)
            .expect("proposal index came from the same queue")
            .into_request())
    }

    /// Removes a pending proposal without mutation.
    ///
    /// # Errors
    ///
    /// Returns [`PluginProposalDecisionError::UnknownProposal`] when `id` is no longer pending.
    pub fn reject_buffer_edit(
        &mut self,
        id: PluginProposalId,
    ) -> Result<RejectedPluginBufferEditProposal, PluginProposalDecisionError> {
        let index = self
            .buffer_edits
            .iter()
            .position(|proposal| proposal.id == id)
            .ok_or(PluginProposalDecisionError::UnknownProposal { id })?;
        let proposal = self
            .buffer_edits
            .remove(index)
            .expect("proposal index came from the same queue");
        Ok(RejectedPluginBufferEditProposal {
            id,
            target: proposal.request.target,
            provenance: proposal.request.provenance,
            rejected: BufferEditShape::from_edit(&proposal.request.edit),
        })
    }

    /// Returns the pending proposal cap.
    #[must_use]
    pub const fn limit(&self) -> PluginProposalLaneLimit {
        self.limit
    }

    /// Returns the pending buffer edit count.
    #[must_use]
    pub fn len(&self) -> usize {
        self.buffer_edits.len()
    }

    /// Returns whether the proposal lane is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.buffer_edits.is_empty()
    }

    /// Returns pending buffer edit proposals in insertion order.
    pub fn pending_buffer_edits(&self) -> impl Iterator<Item = &PendingPluginBufferEditProposal> {
        self.buffer_edits.iter()
    }

    /// Returns a pending buffer edit proposal by id.
    #[must_use]
    pub fn pending_buffer_edit(
        &self,
        id: PluginProposalId,
    ) -> Option<&PendingPluginBufferEditProposal> {
        self.buffer_edits.iter().find(|proposal| proposal.id == id)
    }

    /// Returns the first pending proposal id.
    #[must_use]
    pub fn first_pending_id(&self) -> Option<PluginProposalId> {
        self.buffer_edits.front().map(|proposal| proposal.id)
    }

    /// Allocates a non-zero proposal id.
    fn allocate_id(
        &mut self,
        identity: &PluginIdentity,
    ) -> Result<PluginProposalId, PluginProposalLaneError> {
        let id = self.next_id;
        self.next_id = NonZeroU64::new(id.get().checked_add(1).ok_or_else(|| {
            PluginProposalLaneError::IdExhausted {
                identity: identity.clone(),
            }
        })?)
        .expect("checked increment from non-zero remains non-zero");
        Ok(PluginProposalId::from_nonzero(id))
    }
}

impl Default for PluginProposalLane {
    fn default() -> Self {
        Self::with_limit(PluginProposalLaneLimit::default())
    }
}

impl Debug for PluginProposalLane {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PluginProposalLane")
            .field("limit", &self.limit)
            .field("next_id", &self.next_id)
            .field("pending_buffer_edits", &self.buffer_edits.len())
            .finish()
    }
}

/// Retained proposal receipt cap.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PluginProposalReceiptLogLimit {
    /// Receipts retained for review.
    max_receipts: NonZeroUsize,
}

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

    /// Returns the retained receipt cap.
    #[must_use]
    pub const fn max_receipts(self) -> usize {
        self.max_receipts.get()
    }
}

impl Default for PluginProposalReceiptLogLimit {
    fn default() -> Self {
        Self::try_new(DEFAULT_PLUGIN_PROPOSAL_RECEIPT_LOG_LIMIT)
            .expect("default proposal receipt log limit should be non-zero")
    }
}

/// Bounded in-session proposal receipt log.
#[derive(Resource)]
pub struct PluginProposalReceiptLog {
    /// Retained receipt cap.
    limit: PluginProposalReceiptLogLimit,
    /// Receipts in observation order.
    receipts: VecDeque<PluginBufferEditProposalReceipt>,
}

impl PluginProposalReceiptLog {
    /// Creates an empty receipt log.
    #[must_use]
    pub const fn with_limit(limit: PluginProposalReceiptLogLimit) -> Self {
        Self {
            limit,
            receipts: VecDeque::new(),
        }
    }

    /// Retains one proposal receipt, evicting the oldest receipt at capacity.
    pub fn push(&mut self, receipt: PluginBufferEditProposalReceipt) {
        if self.receipts.len() >= self.limit.max_receipts() {
            let _oldest = self.receipts.pop_front();
        }
        self.receipts.push_back(receipt);
    }

    /// Returns retained receipts in observation order.
    pub fn receipts(&self) -> impl ExactSizeIterator<Item = &PluginBufferEditProposalReceipt> {
        self.receipts.iter()
    }

    /// Returns the most recent retained receipt.
    #[must_use]
    pub fn latest(&self) -> Option<&PluginBufferEditProposalReceipt> {
        self.receipts.back()
    }

    /// Returns the retained receipt cap.
    #[must_use]
    pub const fn limit(&self) -> PluginProposalReceiptLogLimit {
        self.limit
    }

    /// Returns the retained receipt count.
    #[must_use]
    pub fn len(&self) -> usize {
        self.receipts.len()
    }

    /// Returns whether the receipt log is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.receipts.is_empty()
    }
}

impl Default for PluginProposalReceiptLog {
    fn default() -> Self {
        Self::with_limit(PluginProposalReceiptLogLimit::default())
    }
}

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

/// Pending plugin buffer edit proposal.
pub struct PendingPluginBufferEditProposal {
    /// Stable proposal id.
    id: PluginProposalId,
    /// Owner-boundary request retained until decision.
    request: RevisionGuardedBufferEditRequested,
}

impl PendingPluginBufferEditProposal {
    /// Returns the proposal id.
    #[must_use]
    pub const fn id(&self) -> PluginProposalId {
        self.id
    }

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

    /// Returns the proposal provenance.
    #[must_use]
    pub const fn provenance(&self) -> &PluginBufferEditProvenance {
        &self.request.provenance
    }

    /// Returns the redacted edit shape.
    #[must_use]
    pub fn edit_shape(&self) -> BufferEditShape {
        BufferEditShape::from_edit(&self.request.edit)
    }

    /// Returns the redacted diff preview.
    #[must_use]
    pub(crate) fn diff_preview(&self) -> PluginBufferEditDiffPreview {
        PluginBufferEditDiffPreview::from_shape(
            self.request.provenance.base_revision(),
            &self.edit_shape(),
        )
    }

    /// Consumes the pending proposal into the owner-boundary request.
    fn into_request(self) -> RevisionGuardedBufferEditRequested {
        self.request
    }
}

impl Debug for PendingPluginBufferEditProposal {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PendingPluginBufferEditProposal")
            .field("id", &self.id)
            .field("target", &PluginProposalTargetShape::Buffer)
            .field("provenance", &self.request.provenance)
            .field("edit", &BufferEditShape::from_edit(&self.request.edit))
            .finish()
    }
}

/// Redacted diff preview for a pending plugin proposal.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PluginBufferEditDiffPreview {
    /// Replace the whole buffer. Removed bytes are unknown until the owner resolves the buffer.
    SetAll {
        /// Revision observed when the proposal was built.
        base_revision: TextRevision,
        /// Proposed replacement byte count.
        added_byte_len: usize,
    },
    /// Insert bytes at one byte index.
    Insert {
        /// Revision observed when the proposal was built.
        base_revision: TextRevision,
        /// Proposed insertion point.
        byte_index: usize,
        /// Proposed insertion byte count.
        added_byte_len: usize,
    },
    /// Replace one byte range.
    Replace {
        /// Revision observed when the proposal was built.
        base_revision: TextRevision,
        /// Proposed byte range.
        range: TextRange,
        /// Proposed removed byte count, when the range is well formed.
        removed_byte_len: Option<usize>,
        /// Proposed replacement byte count.
        added_byte_len: usize,
    },
    /// Delete one byte range.
    Delete {
        /// Revision observed when the proposal was built.
        base_revision: TextRevision,
        /// Proposed byte range.
        range: TextRange,
        /// Proposed removed byte count, when the range is well formed.
        removed_byte_len: Option<usize>,
    },
}

impl PluginBufferEditDiffPreview {
    /// Builds a redacted preview from the already-redacted edit shape.
    #[must_use]
    fn from_shape(base_revision: TextRevision, shape: &BufferEditShape) -> Self {
        match shape.kind() {
            BufferEditKind::SetAll => Self::SetAll {
                base_revision,
                added_byte_len: shape.replacement_byte_len().unwrap_or(0),
            },
            BufferEditKind::Insert => Self::Insert {
                base_revision,
                byte_index: shape.byte_index().unwrap_or(0),
                added_byte_len: shape.replacement_byte_len().unwrap_or(0),
            },
            BufferEditKind::Replace => {
                let range = shape.range().unwrap_or_else(|| TextRange::new(0, 0));
                Self::Replace {
                    base_revision,
                    range,
                    removed_byte_len: text_range_len(range),
                    added_byte_len: shape.replacement_byte_len().unwrap_or(0),
                }
            }
            BufferEditKind::Delete => {
                let range = shape.range().unwrap_or_else(|| TextRange::new(0, 0));
                Self::Delete {
                    base_revision,
                    range,
                    removed_byte_len: text_range_len(range),
                }
            }
        }
    }
}

/// Returns a range length only when the proposed coordinates are ordered.
const fn text_range_len(range: TextRange) -> Option<usize> {
    if range.end() >= range.start() {
        Some(range.end() - range.start())
    } else {
        None
    }
}

/// Proposal rejected before owner mutation.
#[derive(Clone, Eq, PartialEq)]
pub struct RejectedPluginBufferEditProposal {
    /// Rejected proposal id.
    id: PluginProposalId,
    /// Target buffer.
    target: BufferEntity,
    /// Proposal provenance.
    provenance: PluginBufferEditProvenance,
    /// Redacted edit shape.
    rejected: BufferEditShape,
}

impl Debug for RejectedPluginBufferEditProposal {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("RejectedPluginBufferEditProposal")
            .field("id", &self.id)
            .field("target", &PluginProposalTargetShape::Buffer)
            .field("provenance", &self.provenance)
            .field("rejected", &self.rejected)
            .finish()
    }
}

/// Redacted proposal target shape.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PluginProposalTargetShape {
    /// Buffer owner target.
    Buffer,
}

impl RejectedPluginBufferEditProposal {
    /// Returns the rejected proposal id.
    #[must_use]
    pub const fn id(&self) -> PluginProposalId {
        self.id
    }

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

    /// Returns the rejected proposal provenance.
    #[must_use]
    pub const fn provenance(&self) -> &PluginBufferEditProvenance {
        &self.provenance
    }

    /// Returns the redacted edit shape.
    #[must_use]
    pub const fn rejected(&self) -> &BufferEditShape {
        &self.rejected
    }
}

/// Proposal lane rejection.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum PluginProposalLaneError {
    /// Lane limit was zero.
    ZeroLimit,
    /// Proposal id space was exhausted.
    IdExhausted {
        /// Rejected plugin identity.
        identity: PluginIdentity,
    },
    /// Lane already holds the maximum accepted proposals.
    TooManyPending {
        /// Rejected plugin identity.
        identity: PluginIdentity,
        /// Maximum pending proposals.
        limit: NonZeroUsize,
    },
}

/// Proposal lane rejection class.
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum PluginProposalLaneErrorKind {
    /// Lane limit was zero.
    ZeroLimit,
    /// Proposal id space was exhausted.
    IdExhausted,
    /// Pending proposal capacity was exhausted.
    TooManyPending,
}

impl PluginProposalLaneErrorKind {
    /// Stable diagnostic spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ZeroLimit => "zero-limit",
            Self::IdExhausted => "id-exhausted",
            Self::TooManyPending => "too-many-pending",
        }
    }
}

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

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

/// Proposal decision rejection.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum PluginProposalDecisionError {
    /// Proposal is no longer pending.
    UnknownProposal {
        /// Requested proposal id.
        id: PluginProposalId,
    },
}

/// Proposal decision rejection class.
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum PluginProposalDecisionErrorKind {
    /// Proposal is no longer pending.
    UnknownProposal,
}

impl PluginProposalDecisionErrorKind {
    /// Stable diagnostic spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::UnknownProposal => "unknown-proposal",
        }
    }
}

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

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

/// Receipt log construction rejection.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum PluginProposalReceiptLogError {
    /// Receipt log limit was zero.
    ZeroLimit,
}

/// Proposal receipt log rejection class.
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum PluginProposalReceiptLogErrorKind {
    /// Receipt log limit was zero.
    ZeroLimit,
}

impl PluginProposalReceiptLogErrorKind {
    /// Stable diagnostic spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ZeroLimit => "zero-limit",
        }
    }
}

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

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

impl Display for PluginProposalLaneError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ZeroLimit => formatter.write_str("plugin proposal lane limit must be non-zero"),
            Self::IdExhausted { identity } => {
                let identity = identity.as_str();
                write!(
                    formatter,
                    "plugin {identity:?} exhausted proposal identifiers"
                )
            }
            Self::TooManyPending { identity, limit } => {
                let identity = identity.as_str();
                let limit = limit.get();
                write!(
                    formatter,
                    "plugin {identity:?} exceeded proposal lane pending limit of {limit}"
                )
            }
        }
    }
}

impl PluginProposalLaneError {
    /// Closed rejection class for caller decisions and diagnostics.
    #[must_use]
    pub const fn kind(&self) -> PluginProposalLaneErrorKind {
        match self {
            Self::ZeroLimit => PluginProposalLaneErrorKind::ZeroLimit,
            Self::IdExhausted { .. } => PluginProposalLaneErrorKind::IdExhausted,
            Self::TooManyPending { .. } => PluginProposalLaneErrorKind::TooManyPending,
        }
    }

    /// Returns the rejected proposal identity for display and serialization.
    #[must_use]
    pub fn identity(&self) -> Option<&str> {
        self.identity_proof().map(PluginIdentity::as_str)
    }

    /// Returns the rejected proposal identity proof.
    #[must_use]
    pub const fn identity_proof(&self) -> Option<&PluginIdentity> {
        match self {
            Self::ZeroLimit => None,
            Self::IdExhausted { identity } | Self::TooManyPending { identity, .. } => {
                Some(identity)
            }
        }
    }

    /// Returns a redacted operational event for proposal-lane saturation.
    #[must_use]
    pub fn operational_event(&self) -> Option<PluginOperationalEvent> {
        match self {
            Self::TooManyPending { identity, limit } => {
                Some(PluginOperationalEvent::queue_saturated_for(
                    identity,
                    PluginOperationalQueue::ProposalLane,
                    *limit,
                ))
            }
            Self::ZeroLimit | Self::IdExhausted { .. } => None,
        }
    }
}

impl PluginProposalDecisionError {
    /// Closed rejection class for caller decisions and diagnostics.
    #[must_use]
    pub const fn kind(&self) -> PluginProposalDecisionErrorKind {
        match self {
            Self::UnknownProposal { .. } => PluginProposalDecisionErrorKind::UnknownProposal,
        }
    }
}

impl Display for PluginProposalDecisionError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnknownProposal { id } => {
                write!(formatter, "plugin proposal {} is not pending", id.get())
            }
        }
    }
}

impl PluginProposalReceiptLogError {
    /// Closed rejection class for caller decisions and diagnostics.
    #[must_use]
    pub const fn kind(&self) -> PluginProposalReceiptLogErrorKind {
        match self {
            Self::ZeroLimit => PluginProposalReceiptLogErrorKind::ZeroLimit,
        }
    }
}

impl Display for PluginProposalReceiptLogError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ZeroLimit => {
                formatter.write_str("plugin proposal receipt log limit must be non-zero")
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        PluginProposalDecisionError, PluginProposalDecisionErrorKind, PluginProposalLane,
        PluginProposalLaneError, PluginProposalLaneErrorKind, PluginProposalLaneLimit,
        PluginProposalReceiptLog, PluginProposalReceiptLogError, PluginProposalReceiptLogErrorKind,
        PluginProposalReceiptLogLimit,
    };
    use crate::{
        buffer::{BufferEdit, BufferEditKind},
        ecs::{
            components::buffer::BufferEntity,
            events::edit::{
                PluginBufferEditProposalReceipt, PluginBufferEditProvenance,
                RevisionGuardedBufferEditRequested,
            },
        },
        plugin::PluginIdentity,
        text_stream::{TextRange, TextRevision},
    };
    use bevy::prelude::Entity;
    use std::num::{NonZeroU64, NonZeroUsize};

    #[test]
    fn proposal_lane_error_kinds_are_closed() {
        let identity = plugin_identity("proposal-test");
        let cases = [
            (
                PluginProposalLaneError::ZeroLimit,
                PluginProposalLaneErrorKind::ZeroLimit,
                "zero-limit",
            ),
            (
                PluginProposalLaneError::IdExhausted {
                    identity: identity.clone(),
                },
                PluginProposalLaneErrorKind::IdExhausted,
                "id-exhausted",
            ),
            (
                PluginProposalLaneError::TooManyPending {
                    identity,
                    limit: count_limit(1),
                },
                PluginProposalLaneErrorKind::TooManyPending,
                "too-many-pending",
            ),
        ];

        for (error, kind, expected) in cases {
            assert_eq!(error.kind(), kind);
            assert_eq!(kind.as_str(), expected);
            assert_eq!(kind.to_string(), expected);
            assert_eq!(format!("{kind:?}"), expected);
        }
    }

    #[test]
    fn proposal_decision_and_receipt_error_kinds_are_closed() {
        let proposal = crate::ecs::events::edit::PluginProposalId::from_nonzero(
            NonZeroU64::new(1).expect("proposal id should be non-zero"),
        );
        let decision = PluginProposalDecisionError::UnknownProposal { id: proposal };
        let receipt = PluginProposalReceiptLogError::ZeroLimit;

        assert_eq!(
            decision.kind(),
            PluginProposalDecisionErrorKind::UnknownProposal
        );
        assert_eq!(
            PluginProposalDecisionErrorKind::UnknownProposal.as_str(),
            "unknown-proposal"
        );
        assert_eq!(
            PluginProposalDecisionErrorKind::UnknownProposal.to_string(),
            "unknown-proposal"
        );
        assert_eq!(
            format!("{:?}", PluginProposalDecisionErrorKind::UnknownProposal),
            "unknown-proposal"
        );
        assert_eq!(receipt.kind(), PluginProposalReceiptLogErrorKind::ZeroLimit);
        assert_eq!(
            PluginProposalReceiptLogErrorKind::ZeroLimit.as_str(),
            "zero-limit"
        );
        assert_eq!(
            PluginProposalReceiptLogErrorKind::ZeroLimit.to_string(),
            "zero-limit"
        );
        assert_eq!(
            format!("{:?}", PluginProposalReceiptLogErrorKind::ZeroLimit),
            "zero-limit"
        );
    }

    #[test]
    fn proposal_lane_is_bounded_without_partial_enqueue() {
        let mut lane = PluginProposalLane::with_limit(
            PluginProposalLaneLimit::try_new(1).expect("limit should be valid"),
        );

        let _id = lane
            .push_buffer_edit(request("first secret"))
            .expect("first proposal should fit");
        let error = lane
            .push_buffer_edit(request("second secret"))
            .expect_err("second proposal should exceed the lane limit");

        assert_eq!(
            error,
            PluginProposalLaneError::TooManyPending {
                identity: plugin_identity("proposal-test"),
                limit: count_limit(1),
            }
        );
        assert_eq!(error.identity(), Some("proposal-test"));
        assert_eq!(
            error
                .identity_proof()
                .map(crate::plugin::PluginIdentity::as_str),
            Some("proposal-test")
        );
        assert_eq!(
            error.to_string(),
            "plugin \"proposal-test\" exceeded proposal lane pending limit of 1"
        );
        assert_eq!(lane.len(), 1);
    }

    #[test]
    fn proposal_lane_id_exhaustion_preserves_rejected_identity() {
        let mut lane = PluginProposalLane {
            next_id: NonZeroU64::new(u64::MAX).expect("max id should be non-zero"),
            ..PluginProposalLane::default()
        };

        let error = lane
            .push_buffer_edit(request("secret plugin payload"))
            .expect_err("exhausted id allocator should reject");

        assert_eq!(
            error,
            PluginProposalLaneError::IdExhausted {
                identity: plugin_identity("proposal-test"),
            }
        );
        assert_eq!(error.identity(), Some("proposal-test"));
        assert_eq!(error.operational_event(), None);
        assert!(lane.is_empty());
    }

    #[test]
    fn proposal_lane_saturation_event_is_redacted() {
        let identity = PluginIdentity::try_new("proposal-test").expect("identity");
        let error = PluginProposalLaneError::TooManyPending {
            identity,
            limit: count_limit(1),
        };

        let event = error
            .operational_event()
            .expect("saturation should produce an event");

        assert_eq!(event.identity(), Some("proposal-test"));
        assert_eq!(
            event.kind(),
            crate::plugin::PluginOperationalEventKind::QueueSaturated {
                queue: crate::plugin::PluginOperationalQueue::ProposalLane,
                limit: count_limit(1),
            }
        );
        assert!(!format!("{event:?}").contains("secret"));
        assert_eq!(
            event.to_string(),
            "plugin \"proposal-test\" saturated proposal-lane queue at 1"
        );
    }

    #[test]
    fn pending_proposal_debug_redacts_edit_text() {
        let mut lane = PluginProposalLane::default();
        let id = lane
            .push_buffer_edit(request("secret plugin payload"))
            .expect("proposal should fit");
        let proposal = lane.pending_buffer_edit(id).expect("pending proposal");

        assert_eq!(proposal.edit_shape().kind(), BufferEditKind::Insert);
        assert_eq!(proposal.provenance().proposal_id(), Some(id));
        let debug = format!("{proposal:?}");
        assert!(debug.contains("PendingPluginBufferEditProposal"));
        assert!(debug.contains("Insert"));
        assert!(!debug.contains("Entity"));
        assert!(!debug.contains("BufferEntity"));
        assert!(!debug.contains("secret"));
        assert!(!debug.contains("payload"));
    }

    #[test]
    fn pending_proposal_diff_preview_redacts_edit_text() {
        let mut lane = PluginProposalLane::default();
        let id = lane
            .push_buffer_edit(RevisionGuardedBufferEditRequested {
                target: BufferEntity(Entity::from_raw_u32(1).expect("entity")),
                provenance: PluginBufferEditProvenance::buffer_propose_edit(
                    plugin_identity("proposal-test"),
                    TextRevision::from(7),
                ),
                edit: BufferEdit::replace_unchecked(1..3, "secret replacement"),
            })
            .expect("proposal should fit");
        let proposal = lane.pending_buffer_edit(id).expect("pending proposal");

        assert_eq!(
            proposal.diff_preview(),
            super::PluginBufferEditDiffPreview::Replace {
                base_revision: TextRevision::from(7),
                range: TextRange::new(1, 3),
                removed_byte_len: Some(2),
                added_byte_len: 18,
            }
        );
        let debug = format!("{:?}", proposal.diff_preview());
        assert!(!debug.contains("secret"));
        assert!(!debug.contains("replacement"));
    }

    #[test]
    fn receipt_log_retains_bounded_recent_receipts() {
        let mut lane = PluginProposalLane::default();
        let mut log = PluginProposalReceiptLog::with_limit(
            PluginProposalReceiptLogLimit::try_new(1).expect("limit should be valid"),
        );
        let first = rejected_receipt(&mut lane, "first");
        let second = rejected_receipt(&mut lane, "second");

        log.push(first);
        log.push(second.clone());

        assert_eq!(log.len(), 1);
        assert_eq!(
            log.receipts()
                .next()
                .expect("most recent receipt should be retained")
                .proposal(),
            second.proposal()
        );
    }

    fn request(text: &str) -> RevisionGuardedBufferEditRequested {
        RevisionGuardedBufferEditRequested {
            target: BufferEntity(Entity::from_raw_u32(1).expect("entity")),
            provenance: PluginBufferEditProvenance::buffer_propose_edit(
                plugin_identity("proposal-test"),
                TextRevision::from(0),
            ),
            edit: BufferEdit::insert(0, text),
        }
    }

    fn rejected_receipt(
        lane: &mut PluginProposalLane,
        text: &str,
    ) -> PluginBufferEditProposalReceipt {
        let id = lane
            .push_buffer_edit(request(text))
            .expect("proposal should fit");
        let rejected = lane.reject_buffer_edit(id).expect("proposal should reject");

        PluginBufferEditProposalReceipt::rejected_before_owner(
            rejected.id(),
            rejected.provenance(),
            rejected.target(),
            rejected.rejected().clone(),
        )
    }

    fn plugin_identity(identity: &str) -> PluginIdentity {
        PluginIdentity::try_new(identity).expect("test identity should be valid")
    }

    fn count_limit(value: usize) -> NonZeroUsize {
        NonZeroUsize::new(value).expect("test count limit should be non-zero")
    }
}