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
//! Static plugin capability grants and authorization query shapes.

use super::{
    PluginCapabilityShape, WitCapabilityRefError, WorkspacePathError, WorkspacePathGrant,
    WorkspacePathRef, workspace::intersect_path_grants,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Formatter};

/// Static capability grants for one plugin.
#[derive(Clone, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct PluginCapabilities {
    /// Whether the plugin may observe host-issued buffer handles.
    #[serde(rename = "buffer.observe")]
    pub buffer_observe: bool,
    /// Whether the plugin may propose edits against host-issued buffer handles.
    #[serde(rename = "buffer.propose_edit")]
    pub buffer_propose_edit: bool,
    /// Workspace-relative observation path grants.
    #[serde(rename = "workspace.observe")]
    pub workspace_observe: Vec<WorkspacePathGrant>,
    /// Workspace-relative artifact write path grants.
    #[serde(rename = "workspace.artifact_write")]
    pub workspace_artifact_write: Vec<WorkspacePathGrant>,
    /// Whether the plugin may emit scoped status messages.
    #[serde(rename = "status.publish")]
    pub status_publish: bool,
}

impl PluginCapabilities {
    /// Returns the granted intersection of config and manifest capabilities.
    #[must_use]
    pub fn intersection(&self, requested: &Self) -> Self {
        CapabilitySet::from(self)
            .intersection(&CapabilitySet::from(requested))
            .into_capabilities()
    }

    /// Returns whether this grant set authorizes `capability`.
    #[must_use]
    pub fn allows(&self, capability: PluginCapabilityRef<'_>) -> bool {
        grants_allow_capability(
            self.buffer_observe,
            self.buffer_propose_edit,
            &self.workspace_observe,
            &self.workspace_artifact_write,
            self.status_publish,
            capability,
        )
    }
}

impl Debug for PluginCapabilities {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PluginCapabilities")
            .field("buffer_observe", &self.buffer_observe)
            .field("buffer_propose_edit", &self.buffer_propose_edit)
            .field(
                "workspace_observe",
                &WorkspaceGrantListDebug(&self.workspace_observe),
            )
            .field(
                "workspace_artifact_write",
                &WorkspaceGrantListDebug(&self.workspace_artifact_write),
            )
            .field("status_publish", &self.status_publish)
            .finish()
    }
}

/// One granular authority atom understood by the plugin host.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum CapabilityAtom {
    /// Observe an authorized buffer handle.
    BufferObserve,
    /// Propose an edit against an authorized buffer handle.
    BufferProposeEdit,
    /// Observe workspace data under path grants.
    WorkspaceObserve,
    /// Write attributed artifacts under path grants.
    WorkspaceArtifactWrite,
    /// Publish scoped status text.
    StatusPublish,
}

impl CapabilityAtom {
    /// Returns every accepted capability atom in stable order.
    #[must_use]
    pub const fn all() -> [Self; 5] {
        [
            Self::BufferObserve,
            Self::BufferProposeEdit,
            Self::WorkspaceObserve,
            Self::WorkspaceArtifactWrite,
            Self::StatusPublish,
        ]
    }

    /// Returns every accepted capability spelling in stable order.
    #[must_use]
    pub const fn names() -> [&'static str; 5] {
        [
            Self::BufferObserve.as_str(),
            Self::BufferProposeEdit.as_str(),
            Self::WorkspaceObserve.as_str(),
            Self::WorkspaceArtifactWrite.as_str(),
            Self::StatusPublish.as_str(),
        ]
    }

    /// Returns the stable config, manifest, and WIT spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::BufferObserve => "buffer.observe",
            Self::BufferProposeEdit => "buffer.propose_edit",
            Self::WorkspaceObserve => "workspace.observe",
            Self::WorkspaceArtifactWrite => "workspace.artifact_write",
            Self::StatusPublish => "status.publish",
        }
    }

    /// Returns this atom's redacted diagnostic shape.
    #[must_use]
    pub const fn shape(self) -> PluginCapabilityShape {
        match self {
            Self::BufferObserve => PluginCapabilityShape::BufferObserve,
            Self::BufferProposeEdit => PluginCapabilityShape::BufferProposeEdit,
            Self::WorkspaceObserve => PluginCapabilityShape::WorkspaceObserve,
            Self::WorkspaceArtifactWrite => PluginCapabilityShape::WorkspaceArtifactWrite,
            Self::StatusPublish => PluginCapabilityShape::StatusPublish,
        }
    }

    /// Builds a host authorization query from this atom and an optional workspace path payload.
    ///
    /// # Errors
    ///
    /// Returns [`WitCapabilityRefError`] when a workspace capability is missing a path, a scalar
    /// capability receives an unexpected path, or the supplied path is not a normalized
    /// workspace-relative path.
    pub fn authorization_ref(
        self,
        path: Option<&str>,
    ) -> Result<PluginCapabilityRef<'_>, WitCapabilityRefError> {
        match self {
            Self::BufferObserve => {
                scalar_capability_ref(path, self, PluginCapabilityRef::BufferObserve)
            }
            Self::BufferProposeEdit => {
                scalar_capability_ref(path, self, PluginCapabilityRef::BufferProposeEdit)
            }
            Self::WorkspaceObserve => {
                let path = path.ok_or_else(|| WitCapabilityRefError::MissingPath {
                    capability: self.shape(),
                })?;
                PluginCapabilityRef::workspace_observe(path).map_err(|source| {
                    WitCapabilityRefError::InvalidPath {
                        capability: self.shape(),
                        source,
                    }
                })
            }
            Self::WorkspaceArtifactWrite => {
                let path = path.ok_or_else(|| WitCapabilityRefError::MissingPath {
                    capability: self.shape(),
                })?;
                PluginCapabilityRef::workspace_artifact_write(path).map_err(|source| {
                    WitCapabilityRefError::InvalidPath {
                        capability: self.shape(),
                        source,
                    }
                })
            }
            Self::StatusPublish => {
                scalar_capability_ref(path, self, PluginCapabilityRef::StatusPublish)
            }
        }
    }
}

impl TryFrom<&str> for CapabilityAtom {
    type Error = ();

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "buffer.observe" => Ok(Self::BufferObserve),
            "buffer.propose_edit" => Ok(Self::BufferProposeEdit),
            "workspace.observe" => Ok(Self::WorkspaceObserve),
            "workspace.artifact_write" => Ok(Self::WorkspaceArtifactWrite),
            "status.publish" => Ok(Self::StatusPublish),
            _unknown => Err(()),
        }
    }
}

impl From<CapabilityAtom> for PluginCapabilityShape {
    fn from(atom: CapabilityAtom) -> Self {
        atom.shape()
    }
}

/// Converts a scalar capability atom to an authorization query, rejecting unused path payloads.
const fn scalar_capability_ref<'path>(
    path: Option<&'path str>,
    atom: CapabilityAtom,
    reference: PluginCapabilityRef<'path>,
) -> Result<PluginCapabilityRef<'path>, WitCapabilityRefError> {
    if path.is_some() {
        return Err(WitCapabilityRefError::UnexpectedPath {
            capability: atom.shape(),
        });
    }

    Ok(reference)
}

/// Composable plugin capability set used for authorization decisions.
#[derive(Clone, Default, Eq, PartialEq)]
pub struct CapabilitySet {
    /// Buffer observation grant.
    buffer_observe: bool,
    /// Buffer edit proposal grant.
    buffer_propose_edit: bool,
    /// Workspace observation path grants.
    workspace_observe: Vec<WorkspacePathGrant>,
    /// Workspace artifact write path grants.
    workspace_artifact_write: Vec<WorkspacePathGrant>,
    /// Status publication grant.
    status_publish: bool,
}

impl CapabilitySet {
    /// Returns the granted intersection of two capability sets.
    #[must_use]
    pub fn intersection(&self, requested: &Self) -> Self {
        Self {
            buffer_observe: self.buffer_observe && requested.buffer_observe,
            buffer_propose_edit: self.buffer_propose_edit && requested.buffer_propose_edit,
            workspace_observe: intersect_path_grants(
                &self.workspace_observe,
                &requested.workspace_observe,
            ),
            workspace_artifact_write: intersect_path_grants(
                &self.workspace_artifact_write,
                &requested.workspace_artifact_write,
            ),
            status_publish: self.status_publish && requested.status_publish,
        }
    }

    /// Returns whether this set authorizes one host-import query.
    #[must_use]
    pub fn allows(&self, capability: PluginCapabilityRef<'_>) -> bool {
        grants_allow_capability(
            self.buffer_observe,
            self.buffer_propose_edit,
            &self.workspace_observe,
            &self.workspace_artifact_write,
            self.status_publish,
            capability,
        )
    }

    /// Returns whether every authority in this set is also present in `other`.
    #[must_use]
    pub fn is_subset_of(&self, other: &Self) -> bool {
        (!self.buffer_observe || other.buffer_observe)
            && (!self.buffer_propose_edit || other.buffer_propose_edit)
            && (!self.status_publish || other.status_publish)
            && path_grants_are_subset(&self.workspace_observe, &other.workspace_observe)
            && path_grants_are_subset(
                &self.workspace_artifact_write,
                &other.workspace_artifact_write,
            )
    }

    /// Converts this set back to the current serialized capability DTO.
    #[must_use]
    pub fn into_capabilities(self) -> PluginCapabilities {
        PluginCapabilities {
            buffer_observe: self.buffer_observe,
            buffer_propose_edit: self.buffer_propose_edit,
            workspace_observe: self.workspace_observe,
            workspace_artifact_write: self.workspace_artifact_write,
            status_publish: self.status_publish,
        }
    }
}

impl Debug for CapabilitySet {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("CapabilitySet")
            .field("buffer_observe", &self.buffer_observe)
            .field("buffer_propose_edit", &self.buffer_propose_edit)
            .field(
                "workspace_observe",
                &WorkspaceGrantListDebug(&self.workspace_observe),
            )
            .field(
                "workspace_artifact_write",
                &WorkspaceGrantListDebug(&self.workspace_artifact_write),
            )
            .field("status_publish", &self.status_publish)
            .finish()
    }
}

impl From<&PluginCapabilities> for CapabilitySet {
    fn from(capabilities: &PluginCapabilities) -> Self {
        Self {
            buffer_observe: capabilities.buffer_observe,
            buffer_propose_edit: capabilities.buffer_propose_edit,
            workspace_observe: capabilities.workspace_observe.clone(),
            workspace_artifact_write: capabilities.workspace_artifact_write.clone(),
            status_publish: capabilities.status_publish,
        }
    }
}

/// Capability check requested at a host import boundary.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PluginCapabilityRef<'path> {
    /// Observe an authorized buffer handle.
    BufferObserve,
    /// Propose an edit through an authorized buffer handle.
    BufferProposeEdit,
    /// Observe a workspace-relative path.
    WorkspaceObserve(WorkspacePathRef<'path>),
    /// Write an attributed artifact under a workspace-relative path.
    WorkspaceArtifactWrite(WorkspacePathRef<'path>),
    /// Emit a scoped status message.
    StatusPublish,
}

impl<'path> PluginCapabilityRef<'path> {
    /// Returns the policy atom this authorization query spends.
    #[must_use]
    pub const fn atom(self) -> CapabilityAtom {
        match self {
            Self::BufferObserve => CapabilityAtom::BufferObserve,
            Self::BufferProposeEdit => CapabilityAtom::BufferProposeEdit,
            Self::WorkspaceObserve(_path) => CapabilityAtom::WorkspaceObserve,
            Self::WorkspaceArtifactWrite(_path) => CapabilityAtom::WorkspaceArtifactWrite,
            Self::StatusPublish => CapabilityAtom::StatusPublish,
        }
    }

    /// Returns the redacted diagnostic shape without exposing path payload.
    #[must_use]
    pub const fn shape(self) -> PluginCapabilityShape {
        self.atom().shape()
    }

    /// Creates a workspace observation capability query for a validated relative path.
    ///
    /// # Errors
    ///
    /// Returns [`WorkspacePathError`] when `path` is not a normalized workspace-relative path.
    pub fn workspace_observe(path: &'path str) -> Result<Self, WorkspacePathError> {
        Ok(Self::WorkspaceObserve(WorkspacePathRef::try_from(path)?))
    }

    /// Creates a workspace artifact-write capability query for a validated relative path.
    ///
    /// # Errors
    ///
    /// Returns [`WorkspacePathError`] when `path` is not a normalized workspace-relative path.
    pub fn workspace_artifact_write(path: &'path str) -> Result<Self, WorkspacePathError> {
        Ok(Self::WorkspaceArtifactWrite(WorkspacePathRef::try_from(
            path,
        )?))
    }
}

impl From<PluginCapabilityRef<'_>> for PluginCapabilityShape {
    fn from(capability: PluginCapabilityRef<'_>) -> Self {
        capability.shape()
    }
}

/// Returns whether every left grant is covered by some right grant.
fn path_grants_are_subset(left: &[WorkspacePathGrant], right: &[WorkspacePathGrant]) -> bool {
    left.iter().all(|grant| {
        right
            .iter()
            .any(|candidate| candidate.covers(grant.prefix()))
    })
}

/// Shared borrowed authorization over either serialized or internal grant storage.
fn grants_allow_capability(
    buffer_observe: bool,
    buffer_propose_edit: bool,
    workspace_observe: &[WorkspacePathGrant],
    workspace_artifact_write: &[WorkspacePathGrant],
    status_publish: bool,
    capability: PluginCapabilityRef<'_>,
) -> bool {
    match capability {
        PluginCapabilityRef::BufferObserve => buffer_observe,
        PluginCapabilityRef::BufferProposeEdit => buffer_propose_edit,
        PluginCapabilityRef::WorkspaceObserve(path) => {
            workspace_observe.iter().any(|grant| grant.allows(path))
        }
        PluginCapabilityRef::WorkspaceArtifactWrite(path) => workspace_artifact_write
            .iter()
            .any(|grant| grant.allows(path)),
        PluginCapabilityRef::StatusPublish => status_publish,
    }
}

/// Redacted workspace grant list for capability debug output.
struct WorkspaceGrantListDebug<'grants>(&'grants [WorkspacePathGrant]);

impl Debug for WorkspaceGrantListDebug<'_> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_list()
            .entries(self.0.iter().map(WorkspaceGrantDebug::from))
            .finish()
    }
}

/// Redacted workspace grant shape.
struct WorkspaceGrantDebug {
    /// Whether this grant intentionally covers the whole workspace.
    all_workspace: bool,
    /// Grant prefix byte length only.
    prefix_byte_len: usize,
}

impl From<&WorkspacePathGrant> for WorkspaceGrantDebug {
    fn from(grant: &WorkspacePathGrant) -> Self {
        Self {
            all_workspace: grant.is_all_workspace(),
            prefix_byte_len: grant.prefix().len(),
        }
    }
}

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

#[cfg(test)]
/// Property-test helpers for plugin capabilities.
pub mod tests {
    use super::{CapabilityAtom, CapabilitySet, PluginCapabilities, PluginCapabilityRef};
    use crate::plugin::{
        PluginCapabilityShape, WitCapability, WitCapabilityRefError, WorkspacePathError,
        WorkspacePathGrant,
        policy::workspace::tests::{grant_witness_paths, path_grant_strategy},
    };
    use proptest::prelude::*;
    use serde_json::json;

    /// Generates plugin capabilities with arbitrary scalar and workspace grants.
    pub fn capabilities_strategy() -> impl Strategy<Value = PluginCapabilities> {
        (
            any::<bool>(),
            any::<bool>(),
            prop::collection::vec(path_grant_strategy(), 0..8),
            prop::collection::vec(path_grant_strategy(), 0..8),
            any::<bool>(),
        )
            .prop_map(
                |(
                    buffer_observe,
                    buffer_propose_edit,
                    workspace_observe,
                    workspace_artifact_write,
                    status_publish,
                )| {
                    PluginCapabilities {
                        buffer_observe,
                        buffer_propose_edit,
                        workspace_observe,
                        workspace_artifact_write,
                        status_publish,
                    }
                },
            )
    }

    fn scalar_subset(left: &PluginCapabilities, right: &PluginCapabilities) -> bool {
        (!left.buffer_observe || right.buffer_observe)
            && (!left.buffer_propose_edit || right.buffer_propose_edit)
            && (!left.status_publish || right.status_publish)
    }

    fn path_grant_subset(left: &[WorkspacePathGrant], right: &[WorkspacePathGrant]) -> bool {
        left.iter()
            .all(|grant| public_grant_is_authorized_by(grant, right))
    }

    fn capability_subset(left: &PluginCapabilities, right: &PluginCapabilities) -> bool {
        scalar_subset(left, right)
            && path_grant_subset(&left.workspace_observe, &right.workspace_observe)
            && path_grant_subset(
                &left.workspace_artifact_write,
                &right.workspace_artifact_write,
            )
    }

    fn public_grant_is_authorized_by(
        grant: &WorkspacePathGrant,
        candidates: &[WorkspacePathGrant],
    ) -> bool {
        let grants = PluginCapabilities {
            workspace_observe: candidates.to_vec(),
            workspace_artifact_write: candidates.to_vec(),
            ..PluginCapabilities::default()
        };
        grant_witness_paths(grant).into_iter().all(|path| {
            let read = PluginCapabilityRef::workspace_observe(&path)
                .expect("generated witness path should be valid");
            let write = PluginCapabilityRef::workspace_artifact_write(&path)
                .expect("generated witness path should be valid");
            grants.allows(read) && grants.allows(write)
        })
    }

    #[test]
    fn capability_atoms_own_names_and_shapes() {
        let cases = [
            (
                CapabilityAtom::BufferObserve,
                "buffer.observe",
                PluginCapabilityShape::BufferObserve,
            ),
            (
                CapabilityAtom::BufferProposeEdit,
                "buffer.propose_edit",
                PluginCapabilityShape::BufferProposeEdit,
            ),
            (
                CapabilityAtom::WorkspaceObserve,
                "workspace.observe",
                PluginCapabilityShape::WorkspaceObserve,
            ),
            (
                CapabilityAtom::WorkspaceArtifactWrite,
                "workspace.artifact_write",
                PluginCapabilityShape::WorkspaceArtifactWrite,
            ),
            (
                CapabilityAtom::StatusPublish,
                "status.publish",
                PluginCapabilityShape::StatusPublish,
            ),
        ];

        assert_eq!(
            CapabilityAtom::names(),
            cases.map(|(_atom, name, _shape)| name)
        );

        for (atom, name, shape) in cases {
            assert_eq!(atom.as_str(), name);
            assert_eq!(atom.shape(), shape);
            assert_eq!(PluginCapabilityShape::from(atom), shape);
            assert_eq!(CapabilityAtom::try_from(name), Ok(atom));
        }

        assert!(CapabilityAtom::try_from("process.exec").is_err());
    }

    #[test]
    fn workspace_capability_ref_debug_redacts_path_payload() {
        let path = "docs/secret-capability-path.txt";
        let read = PluginCapabilityRef::workspace_observe(path).expect("path should validate");
        let write =
            PluginCapabilityRef::workspace_artifact_write(path).expect("path should validate");

        for debug in [format!("{read:?}"), format!("{write:?}")] {
            assert!(debug.contains("Workspace"));
            assert!(debug.contains("path_byte_len"));
            assert!(!debug.contains(path));
            assert!(!debug.contains("secret-capability-path"));
        }
    }

    #[test]
    fn capability_debug_redacts_workspace_grant_prefixes() {
        let observe_prefix = "docs/secret-capability-grant.txt";
        let artifact_prefix = "generated/secret-artifact-grant.txt";
        let capabilities = PluginCapabilities {
            buffer_observe: true,
            workspace_observe: vec![
                WorkspacePathGrant::new(observe_prefix),
                WorkspacePathGrant::all_workspace(),
            ],
            workspace_artifact_write: vec![WorkspacePathGrant::new(artifact_prefix)],
            ..PluginCapabilities::default()
        };

        for (debug, type_name) in [
            (format!("{capabilities:?}"), "PluginCapabilities"),
            (
                format!("{:?}", CapabilitySet::from(&capabilities)),
                "CapabilitySet",
            ),
        ] {
            assert!(debug.contains(type_name));
            assert!(debug.contains("workspace_observe"));
            assert!(debug.contains("workspace_artifact_write"));
            assert!(debug.contains("all_workspace"));
            assert!(debug.contains("prefix_byte_len"));
            assert!(!debug.contains(observe_prefix));
            assert!(!debug.contains(artifact_prefix));
            assert!(!debug.contains("secret-capability-grant"));
            assert!(!debug.contains("secret-artifact-grant"));
        }
    }

    #[test]
    fn capability_atoms_build_authorization_refs_with_path_arity() {
        assert_eq!(
            CapabilityAtom::BufferObserve.authorization_ref(None),
            Ok(PluginCapabilityRef::BufferObserve)
        );
        assert_eq!(
            CapabilityAtom::BufferObserve.authorization_ref(Some("docs/input.txt")),
            Err(WitCapabilityRefError::UnexpectedPath {
                capability: PluginCapabilityShape::BufferObserve,
            })
        );

        assert_eq!(
            CapabilityAtom::WorkspaceObserve.authorization_ref(None),
            Err(WitCapabilityRefError::MissingPath {
                capability: PluginCapabilityShape::WorkspaceObserve,
            })
        );
        assert_eq!(
            CapabilityAtom::WorkspaceObserve.authorization_ref(Some("docs/input.txt")),
            Ok(PluginCapabilityRef::WorkspaceObserve(
                crate::plugin::WorkspacePathRef::try_from("docs/input.txt")
                    .expect("path should validate")
            ))
        );
        assert_eq!(
            CapabilityAtom::WorkspaceArtifactWrite.authorization_ref(Some("docs/../secret.txt")),
            Err(WitCapabilityRefError::InvalidPath {
                capability: PluginCapabilityShape::WorkspaceArtifactWrite,
                source: WorkspacePathError::DotComponent,
            })
        );
    }

    #[test]
    fn capability_refs_project_atom_and_redacted_shape() {
        for (reference, atom, shape) in [
            (
                PluginCapabilityRef::BufferObserve,
                CapabilityAtom::BufferObserve,
                PluginCapabilityShape::BufferObserve,
            ),
            (
                PluginCapabilityRef::BufferProposeEdit,
                CapabilityAtom::BufferProposeEdit,
                PluginCapabilityShape::BufferProposeEdit,
            ),
            (
                PluginCapabilityRef::workspace_observe("docs/private")
                    .expect("path should be valid"),
                CapabilityAtom::WorkspaceObserve,
                PluginCapabilityShape::WorkspaceObserve,
            ),
            (
                PluginCapabilityRef::workspace_artifact_write("docs/generated/private")
                    .expect("path should be valid"),
                CapabilityAtom::WorkspaceArtifactWrite,
                PluginCapabilityShape::WorkspaceArtifactWrite,
            ),
            (
                PluginCapabilityRef::StatusPublish,
                CapabilityAtom::StatusPublish,
                PluginCapabilityShape::StatusPublish,
            ),
        ] {
            assert_eq!(reference.atom(), atom);
            assert_eq!(reference.shape(), shape);
            assert_eq!(PluginCapabilityShape::from(reference), shape);
        }
    }

    #[test]
    fn workspace_path_grants_are_prefix_scoped() {
        let grants = PluginCapabilities {
            workspace_observe: vec![WorkspacePathGrant::new("docs")],
            workspace_artifact_write: vec![WorkspacePathGrant::new("docs/generated")],
            ..PluginCapabilities::default()
        };

        assert!(grants.allows(
            PluginCapabilityRef::workspace_observe("docs/arch.md").expect("path should be valid")
        ));
        assert!(
            grants.allows(
                PluginCapabilityRef::workspace_observe("docs").expect("path should be valid")
            )
        );
        assert!(!grants.allows(
            PluginCapabilityRef::workspace_observe("src/docs.rs").expect("path should be valid")
        ));
        assert!(
            grants.allows(
                PluginCapabilityRef::workspace_artifact_write("docs/generated/plugin.md")
                    .expect("path should be valid")
            )
        );
        assert!(
            !grants.allows(
                PluginCapabilityRef::workspace_artifact_write("docs/arch.md")
                    .expect("path should be valid")
            )
        );
    }

    #[test]
    fn scalar_capabilities_default_deny() {
        let grants = PluginCapabilities::default();

        assert!(!grants.allows(PluginCapabilityRef::BufferObserve));
        assert!(!grants.allows(PluginCapabilityRef::BufferProposeEdit));
        assert!(!grants.allows(PluginCapabilityRef::StatusPublish));
    }

    #[test]
    fn capability_json_uses_documented_names() {
        let grants = PluginCapabilities {
            buffer_observe: true,
            workspace_artifact_write: vec![WorkspacePathGrant::new("docs")],
            ..PluginCapabilities::default()
        };
        let value = serde_json::to_value(grants).expect("capabilities should serialize");

        assert_eq!(
            value,
            json!({
                "buffer.observe": true,
                "buffer.propose_edit": false,
                "workspace.observe": [],
                "workspace.artifact_write": [{"prefix": "docs"}],
                "status.publish": false,
            })
        );
    }

    #[test]
    fn capability_json_rejects_unknown_fields_and_invalid_grants() {
        let unknown_field = json!({
            "buffer.observe": false,
            "buffer.propose_edit": false,
            "workspace.observe": [],
            "workspace.artifact_write": [],
            "status.publish": false,
            "process.exec": true,
        });
        let invalid_grant = json!({
            "workspace.observe": [{"prefix": "docs/../secrets"}],
        });
        let missing_prefix_grant = json!({
            "workspace.observe": [{}],
        });
        let implicit_all_workspace_grant = json!({
            "workspace.observe": [{"prefix": ""}],
        });
        let old_names = json!({
            "buffer.read": true,
            "buffer.edit": true,
            "workspace.read": [],
            "workspace.write": [],
            "status.write": true,
        });

        assert!(serde_json::from_value::<PluginCapabilities>(unknown_field).is_err());
        assert!(serde_json::from_value::<PluginCapabilities>(invalid_grant).is_err());
        assert!(serde_json::from_value::<PluginCapabilities>(missing_prefix_grant).is_err());
        assert!(
            serde_json::from_value::<PluginCapabilities>(implicit_all_workspace_grant).is_err()
        );
        assert!(serde_json::from_value::<PluginCapabilities>(old_names).is_err());
    }

    #[test]
    fn wit_capability_names_match_json_capability_names() {
        let grants = PluginCapabilities::default();
        let value = serde_json::to_value(grants).expect("capabilities should serialize");
        let object = value.as_object().expect("capabilities should be an object");

        for capability in WitCapability::all() {
            assert!(object.contains_key(capability.as_str()));
        }
    }

    proptest! {
        #[test]
        fn capability_intersection_is_subset_of_both_inputs(
            configured in capabilities_strategy(),
            requested in capabilities_strategy(),
        ) {
            let intersection = configured.intersection(&requested);

            prop_assert!(capability_subset(&intersection, &configured));
            prop_assert!(capability_subset(&intersection, &requested));
            let intersection_set = CapabilitySet::from(&intersection);
            prop_assert!(intersection_set.is_subset_of(&CapabilitySet::from(&configured)));
            prop_assert!(intersection_set.is_subset_of(&CapabilitySet::from(&requested)));
        }

        #[test]
        fn capability_intersection_authorizes_only_public_effective_grants(
            configured in capabilities_strategy(),
            requested in capabilities_strategy(),
        ) {
            let intersection = configured.intersection(&requested);

            for grant in &intersection.workspace_observe {
                for path in grant_witness_paths(grant) {
                    let reference = PluginCapabilityRef::workspace_observe(&path)
                        .expect("generated witness path should be valid");
                    prop_assert!(intersection.allows(reference));
                    prop_assert!(configured.allows(reference));
                    prop_assert!(requested.allows(reference));
                }
            }

            for grant in &intersection.workspace_artifact_write {
                for path in grant_witness_paths(grant) {
                    let reference = PluginCapabilityRef::workspace_artifact_write(&path)
                        .expect("generated witness path should be valid");
                    prop_assert!(intersection.allows(reference));
                    prop_assert!(configured.allows(reference));
                    prop_assert!(requested.allows(reference));
                }
            }
        }
    }
}