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
//! Buffer edit messages.

use crate::{
    buffer::{BufferEdit, BufferEditError, BufferEditShape},
    ecs::components::buffer::{BufferEntity, BufferRevision},
    plugin::{CapabilityAtom, PluginIdentity},
    text_stream::TextRevision,
};
use bevy::prelude::Message;
use std::fmt::{Debug, Formatter};
use std::num::NonZeroU64;

pub use super::error::BufferEditRejectionReason;
pub use super::error::EditHistoryRejectionReason;
pub use super::error::PluginProposalDecisionRejectionReason;

/// Request to mutate the authoritative buffer.
#[derive(Clone, Debug, Eq, Message, PartialEq)]
pub struct BufferEditRequested {
    /// Buffer entity to mutate.
    pub target: BufferEntity,
    /// The edit to apply.
    pub edit: BufferEdit,
}

/// Request to mutate a buffer only if it is still at an observed revision.
///
/// This is the owner-boundary shape for snapshot-derived proposals from less-trusted
/// interpretation layers such as Wasm plugins. Ordinary editor input may use
/// [`BufferEditRequested`], while plugin edits must keep their stale-write proof visible until the
/// buffer owner accepts or rejects it.
#[derive(Clone, Debug, Eq, Message, PartialEq)]
pub struct RevisionGuardedBufferEditRequested {
    /// Buffer entity to mutate.
    pub target: BufferEntity,
    /// Provenance for the non-owner proposal.
    pub provenance: PluginBufferEditProvenance,
    /// The edit to apply if the target is still at `base_revision`.
    pub edit: BufferEdit,
}

impl RevisionGuardedBufferEditRequested {
    /// Attaches the host proposal id allocated by the proposal lane.
    #[must_use]
    pub(crate) fn with_proposal_id(mut self, proposal: PluginProposalId) -> Self {
        self.provenance = self.provenance.with_proposal_id(proposal);
        self
    }
}

/// Stable id for one host-visible plugin proposal.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PluginProposalId(NonZeroU64);

impl PluginProposalId {
    /// Creates a proposal id from a non-zero allocator value.
    #[must_use]
    pub(crate) const fn from_nonzero(value: NonZeroU64) -> Self {
        Self(value)
    }

    /// Returns the scalar id.
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0.get()
    }
}

/// Request to apply a pending plugin buffer edit proposal.
#[derive(Clone, Copy, Debug, Eq, Message, PartialEq)]
pub struct PluginBufferEditProposalApplyRequested {
    /// Proposal to route through the buffer owner.
    pub proposal: PluginProposalId,
}

/// Request to reject a pending plugin buffer edit proposal without mutation.
#[derive(Clone, Copy, Debug, Eq, Message, PartialEq)]
pub struct PluginBufferEditProposalRejectRequested {
    /// Proposal to discard from the pending lane.
    pub proposal: PluginProposalId,
}

/// Requested decision for a pending plugin buffer edit proposal.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PluginBufferEditProposalDecision {
    /// Apply the proposal through the buffer owner.
    Apply,
    /// Reject the proposal without mutation.
    Reject,
}

/// Notification that a proposal decision request could not be resolved.
#[derive(Clone, Copy, Debug, Eq, Message, PartialEq)]
pub struct PluginBufferEditProposalDecisionRejected {
    /// Proposal id that was requested.
    pub proposal: PluginProposalId,
    /// Requested decision.
    pub decision: PluginBufferEditProposalDecision,
    /// Boundary reason that prevented the decision.
    pub reason: PluginProposalDecisionRejectionReason,
}

/// Reviewable result for an id-bearing plugin proposal.
#[derive(Clone, Eq, Message, PartialEq)]
pub struct PluginBufferEditProposalReceipt {
    /// Host proposal id.
    proposal: PluginProposalId,
    /// Stable source identity.
    source_identity: PluginIdentity,
    /// Capability used to submit the proposal.
    capability: PluginBufferProposalCapability,
    /// Buffer owner target.
    target: BufferEntity,
    /// Revision observed before constructing the proposal.
    base_revision: TextRevision,
    /// Redacted proposed edit shape.
    proposed: BufferEditShape,
    /// Owner-boundary outcome.
    outcome: PluginBufferEditProposalReceiptOutcome,
}

impl PluginBufferEditProposalReceipt {
    /// Builds a receipt for a buffer-owner acceptance.
    #[must_use]
    pub(crate) fn owner_applied(
        provenance: &PluginBufferEditProvenance,
        target: BufferEntity,
        proposed: BufferEditShape,
        previous_revision: BufferRevision,
        current_revision: BufferRevision,
    ) -> Option<Self> {
        Some(Self {
            proposal: provenance.proposal_id()?,
            source_identity: provenance.source_identity.clone(),
            capability: provenance.capability(),
            target,
            base_revision: provenance.base_revision(),
            proposed,
            outcome: PluginBufferEditProposalReceiptOutcome::Applied {
                previous_revision,
                current_revision,
            },
        })
    }

    /// Builds a receipt for a buffer-owner rejection.
    #[must_use]
    pub(crate) fn owner_rejected(
        provenance: &PluginBufferEditProvenance,
        target: BufferEntity,
        proposed: BufferEditShape,
        reason: &BufferEditRejectionReason,
    ) -> Option<Self> {
        Some(Self {
            proposal: provenance.proposal_id()?,
            source_identity: provenance.source_identity.clone(),
            capability: provenance.capability(),
            target,
            base_revision: provenance.base_revision(),
            proposed,
            outcome: PluginBufferEditProposalReceiptOutcome::Rejected {
                owner: PluginBufferEditProposalReceiptOwner::BufferOwner,
                reason: PluginBufferEditProposalReceiptRejectionReason::from(reason),
            },
        })
    }

    /// Builds a receipt for explicit proposal-lane rejection before owner mutation.
    #[must_use]
    pub(crate) fn rejected_before_owner(
        proposal: PluginProposalId,
        provenance: &PluginBufferEditProvenance,
        target: BufferEntity,
        proposed: BufferEditShape,
    ) -> Self {
        Self {
            proposal,
            source_identity: provenance.source_identity.clone(),
            capability: provenance.capability(),
            target,
            base_revision: provenance.base_revision(),
            proposed,
            outcome: PluginBufferEditProposalReceiptOutcome::Rejected {
                owner: PluginBufferEditProposalReceiptOwner::ProposalLane,
                reason: PluginBufferEditProposalReceiptRejectionReason::RejectedBeforeOwner,
            },
        }
    }

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

    /// Returns the stable source identity for display and serialization.
    #[must_use]
    pub fn source_identity(&self) -> &str {
        self.source_identity_proof().as_str()
    }

    /// Returns the validated source identity.
    #[must_use]
    pub const fn source_identity_proof(&self) -> &PluginIdentity {
        &self.source_identity
    }

    /// Returns the capability used to submit the proposal.
    #[must_use]
    pub const fn capability(&self) -> PluginBufferProposalCapability {
        self.capability
    }

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

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

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

    /// Returns the receipt outcome.
    #[must_use]
    pub const fn outcome(&self) -> &PluginBufferEditProposalReceiptOutcome {
        &self.outcome
    }
}

impl Debug for PluginBufferEditProposalReceipt {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PluginBufferEditProposalReceipt")
            .field("proposal", &self.proposal)
            .field("source_identity", &self.source_identity.as_str())
            .field("capability", &self.capability)
            .field("target", &PluginProposalReceiptTargetShape::Buffer)
            .field("base_revision", &self.base_revision)
            .field("proposed", &self.proposed)
            .field("outcome", &self.outcome)
            .finish()
    }
}

/// Proposal receipt outcome.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PluginBufferEditProposalReceiptOutcome {
    /// Buffer owner applied the proposal.
    Applied {
        /// Revision before owner mutation.
        previous_revision: BufferRevision,
        /// Revision after owner mutation.
        current_revision: BufferRevision,
    },
    /// A proposal owner rejected the proposal.
    Rejected {
        /// Boundary that made the rejection decision.
        owner: PluginBufferEditProposalReceiptOwner,
        /// Closed rejection reason.
        reason: PluginBufferEditProposalReceiptRejectionReason,
    },
}

/// Owner boundary that decided a proposal.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PluginBufferEditProposalReceiptOwner {
    /// Proposal lane rejected before mutation.
    ProposalLane,
    /// Buffer owner rejected during mutation validation.
    BufferOwner,
}

/// Closed receipt rejection reason.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PluginBufferEditProposalReceiptRejectionReason {
    /// User or policy rejected the pending proposal before owner mutation.
    RejectedBeforeOwner,
    /// Target buffer no longer existed at the owner boundary.
    MissingTarget,
    /// Buffer text invariant rejected the proposed edit.
    InvalidEdit {
        /// Text-invariant failure.
        error: BufferEditError,
    },
    /// Target buffer changed since the proposal's observed revision.
    StaleRevision {
        /// Revision observed when the edit was derived.
        expected: TextRevision,
        /// Revision present at the buffer owner boundary.
        actual: TextRevision,
    },
}

impl From<&BufferEditRejectionReason> for PluginBufferEditProposalReceiptRejectionReason {
    fn from(reason: &BufferEditRejectionReason) -> Self {
        match reason {
            BufferEditRejectionReason::MissingTarget { .. } => Self::MissingTarget,
            BufferEditRejectionReason::InvalidEdit { error } => Self::InvalidEdit {
                error: error.clone(),
            },
            BufferEditRejectionReason::StaleRevision { expected, actual } => Self::StaleRevision {
                expected: *expected,
                actual: *actual,
            },
        }
    }
}

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

/// Provenance for a plugin-proposed buffer edit at the owner boundary.
#[derive(Clone, Eq, PartialEq)]
pub struct PluginBufferEditProvenance {
    /// Stable source identity.
    source_identity: PluginIdentity,
    /// Capability used to submit this proposal.
    capability: PluginBufferProposalCapability,
    /// Revision observed before constructing the edit.
    base_revision: TextRevision,
    /// Host proposal id, once the proposal lane has allocated one.
    proposal: Option<PluginProposalId>,
}

impl PluginBufferEditProvenance {
    /// Creates provenance for a `buffer.propose_edit` proposal.
    #[must_use]
    pub const fn buffer_propose_edit(
        source_identity: PluginIdentity,
        base_revision: TextRevision,
    ) -> Self {
        Self {
            source_identity,
            capability: PluginBufferProposalCapability::buffer_propose_edit(),
            base_revision,
            proposal: None,
        }
    }

    /// Returns a copy with a lane-allocated proposal id.
    #[must_use]
    pub(crate) const fn with_proposal_id(mut self, proposal: PluginProposalId) -> Self {
        self.proposal = Some(proposal);
        self
    }

    /// Returns the stable source identity for display and serialization.
    #[must_use]
    pub fn source_identity(&self) -> &str {
        self.source_identity_proof().as_str()
    }

    /// Returns the validated source identity.
    #[must_use]
    pub const fn source_identity_proof(&self) -> &PluginIdentity {
        &self.source_identity
    }

    /// Returns the capability used to submit this proposal.
    #[must_use]
    pub const fn capability(&self) -> PluginBufferProposalCapability {
        self.capability
    }

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

    /// Returns the lane-allocated proposal id, if this proposal reached the lane.
    #[must_use]
    pub const fn proposal_id(&self) -> Option<PluginProposalId> {
        self.proposal
    }
}

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

/// Capability that can produce a buffer-edit proposal.
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct PluginBufferProposalCapability {
    /// Policy-owned capability atom, constrained by this wrapper's constructors.
    atom: CapabilityAtom,
}

impl PluginBufferProposalCapability {
    /// Creates the `buffer.propose_edit` proposal capability.
    #[must_use]
    pub const fn buffer_propose_edit() -> Self {
        Self {
            atom: CapabilityAtom::BufferProposeEdit,
        }
    }

    /// Returns the policy atom that owns this capability spelling.
    #[must_use]
    pub const fn atom(self) -> CapabilityAtom {
        self.atom
    }

    /// Returns the stable capability spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        self.atom.as_str()
    }
}

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

/// Notification that the authoritative buffer revision changed.
#[derive(Clone, Copy, Debug, Eq, Message, PartialEq)]
pub struct BufferEdited {
    /// Buffer entity that changed.
    pub target: BufferEntity,
    /// Revision before the edit.
    pub previous_revision: crate::ecs::components::buffer::BufferRevision,
    /// Revision after the edit.
    pub current_revision: crate::ecs::components::buffer::BufferRevision,
}

/// Notification that an authoritative buffer edit was rejected.
#[derive(Clone, Debug, Eq, Message, PartialEq)]
pub struct BufferEditRejected {
    /// Buffer entity that rejected the edit.
    pub target: BufferEntity,
    /// Redacted shape of the edit that failed validation.
    pub rejected: BufferEditShape,
    /// Boundary reason that prevented mutation.
    pub reason: BufferEditRejectionReason,
}

/// Direction for edit-history replay.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EditHistoryDirection {
    /// Undo the most recent edit transaction.
    Undo,
    /// Redo the most recently undone edit transaction.
    Redo,
}

/// Request to replay one edit-history transaction.
#[derive(Clone, Copy, Debug, Eq, Message, PartialEq)]
pub struct EditHistoryRequested {
    /// Buffer entity whose history should be replayed.
    pub target: BufferEntity,
    /// Replay direction.
    pub direction: EditHistoryDirection,
}

impl EditHistoryRequested {
    /// Builds an undo request.
    #[must_use]
    pub const fn undo(target: BufferEntity) -> Self {
        Self {
            target,
            direction: EditHistoryDirection::Undo,
        }
    }

    /// Builds a redo request.
    #[must_use]
    pub const fn redo(target: BufferEntity) -> Self {
        Self {
            target,
            direction: EditHistoryDirection::Redo,
        }
    }
}

/// Notification that edit-history replay changed the buffer revision.
#[derive(Clone, Copy, Debug, Eq, Message, PartialEq)]
pub struct EditHistoryApplied {
    /// Buffer entity whose history changed.
    pub target: BufferEntity,
    /// Replay direction.
    pub direction: EditHistoryDirection,
    /// Revision before replay.
    pub previous_revision: crate::ecs::components::buffer::BufferRevision,
    /// Revision after replay.
    pub current_revision: crate::ecs::components::buffer::BufferRevision,
}

/// Notification that edit-history replay was rejected.
#[derive(Clone, Debug, Eq, Message, PartialEq)]
pub struct EditHistoryRejected {
    /// Buffer entity that rejected the request.
    pub target: BufferEntity,
    /// Replay direction.
    pub direction: EditHistoryDirection,
    /// Boundary reason that prevented replay.
    pub reason: EditHistoryRejectionReason,
}

#[cfg(test)]
mod tests {
    use super::{
        BufferRevision, PluginBufferEditProposalReceipt, PluginBufferEditProvenance,
        PluginProposalId,
    };
    use crate::{
        buffer::{BufferEdit, BufferEditShape},
        ecs::components::buffer::BufferEntity,
        plugin::{CapabilityAtom, PluginIdentity},
        text_stream::TextRevision,
    };
    use bevy::prelude::Entity;
    use std::num::NonZeroU64;

    #[test]
    fn provenance_and_receipts_preserve_identity_proofs() {
        let identity = PluginIdentity::try_new("proof-source").expect("identity");
        let provenance = PluginBufferEditProvenance::buffer_propose_edit(
            identity.clone(),
            TextRevision::from(7),
        )
        .with_proposal_id(PluginProposalId::from_nonzero(
            NonZeroU64::new(1).expect("non-zero id"),
        ));
        let edit = BufferEdit::insert(0, "secret payload");
        let receipt = PluginBufferEditProposalReceipt::owner_applied(
            &provenance,
            BufferEntity(Entity::from_raw_u32(1).expect("entity")),
            BufferEditShape::from_edit(&edit),
            BufferRevision {
                revision: TextRevision::from(7),
            },
            BufferRevision {
                revision: TextRevision::from(8),
            },
        )
        .expect("proposal id should produce a receipt");

        assert_eq!(provenance.source_identity_proof(), &identity);
        assert_eq!(
            provenance.capability().atom(),
            CapabilityAtom::BufferProposeEdit
        );
        assert_eq!(provenance.capability().as_str(), "buffer.propose_edit");
        assert_eq!(receipt.source_identity_proof(), &identity);
        assert_eq!(
            receipt.capability().atom(),
            CapabilityAtom::BufferProposeEdit
        );
        assert_eq!(receipt.source_identity(), "proof-source");
        assert!(!format!("{receipt:?}").contains("secret payload"));
    }
}