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
//! Plugin load and authorization errors.

use super::{PluginIdentity, WorkspacePathError};
use crate::fs_utils::{EscapedDisplayText, FileReadError, PathPolicyError};
use std::{
    fmt::{Debug, Display, Formatter},
    path::{Path, PathBuf},
};

/// Errors returned while loading plugin metadata.
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum PluginLoadError {
    /// Plugin identity was invalid at the load boundary.
    InvalidIdentity {
        /// Rejected plugin identity.
        identity: String,
        /// Identity validation failure.
        source: PluginIdentityError,
    },
    /// Plugin manifest JSON could not be parsed.
    ManifestParse {
        /// Manifest path, when known.
        path: Option<PathBuf>,
        /// Underlying parse error.
        source: serde_json::Error,
    },
    /// Plugin identity in host config and manifest did not match.
    IdentityMismatch {
        /// Identity from host config.
        configured: PluginIdentity,
        /// Identity from plugin manifest.
        manifest: PluginIdentity,
    },
    /// Plugin WIT world in host config and manifest did not match.
    WitWorldMismatch {
        /// WIT world from host config.
        configured: String,
        /// WIT world from plugin manifest.
        manifest: String,
    },
    /// Plugin WIT world is unsupported by this Alma build.
    UnsupportedWitWorld {
        /// Rejected WIT world.
        wit_world: String,
    },
    /// Plugin is disabled by host config.
    Disabled {
        /// Stable plugin identity.
        identity: PluginIdentity,
    },
    /// Configured component path is not safe to pass to the runtime loader.
    InvalidComponentPath {
        /// Stable plugin identity.
        identity: PluginIdentity,
        /// Component path validation failure.
        source: PluginComponentPathError,
    },
    /// Configured runtime limits are not safe to use for guest execution.
    InvalidRuntimeLimits {
        /// Stable plugin identity.
        identity: PluginIdentity,
        /// Runtime limit validation failure.
        source: PluginRuntimeLimitError,
    },
}

/// Errors returned while opening a plugin manifest through filesystem policy.
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum PluginManifestOpenError {
    /// Filesystem policy or bounded read rejected the manifest file.
    Read {
        /// Policy-read failure.
        source: FileReadError,
    },
    /// Plugin manifest JSON could not be parsed after a policy-approved read.
    Parse {
        /// Escaped manifest path for diagnostics.
        display_path: EscapedDisplayText,
        /// Underlying parse error.
        source: serde_json::Error,
    },
}

/// Errors returned while opening a plugin component through filesystem policy.
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum PluginComponentOpenError {
    /// Filesystem policy or bounded read rejected the component file.
    Read {
        /// Stable plugin identity.
        identity: PluginIdentity,
        /// Policy-read failure.
        source: FileReadError,
    },
}

/// Errors returned while validating a statically configured plugin registry.
#[derive(Clone, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PluginRegistryError {
    /// A plugin entry did not declare a valid stable identity.
    InvalidIdentity {
        /// Rejected plugin identity.
        identity: String,
        /// Identity validation failure.
        source: PluginIdentityError,
    },
    /// More than one plugin entry declared the same identity.
    DuplicateIdentity {
        /// Duplicated stable plugin identity.
        identity: PluginIdentity,
    },
    /// An enabled plugin entry had an invalid component path.
    InvalidEnabledComponentPath {
        /// Stable plugin identity.
        identity: PluginIdentity,
        /// Component path validation failure.
        source: PluginComponentPathError,
    },
    /// An enabled plugin entry declared an unsupported WIT world.
    UnsupportedEnabledWitWorld {
        /// Stable plugin identity.
        identity: PluginIdentity,
        /// Rejected WIT world.
        wit_world: String,
    },
    /// An enabled plugin entry declared invalid runtime limits.
    InvalidEnabledRuntimeLimits {
        /// Stable plugin identity.
        identity: PluginIdentity,
        /// Runtime limit validation failure.
        source: PluginRuntimeLimitError,
    },
}

impl Debug for PluginLoadError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidIdentity { identity, source } => formatter
                .debug_struct("InvalidIdentity")
                .field("identity_byte_len", &identity.len())
                .field("source", source)
                .finish(),
            Self::ManifestParse { path, source } => formatter
                .debug_struct("ManifestParse")
                .field("path_byte_len", &path.as_deref().map(path_byte_len))
                .field("source", &JsonErrorShape::from(source))
                .finish(),
            Self::IdentityMismatch {
                configured,
                manifest,
            } => formatter
                .debug_struct("IdentityMismatch")
                .field("configured", configured)
                .field("manifest", manifest)
                .finish(),
            Self::WitWorldMismatch {
                configured,
                manifest,
            } => formatter
                .debug_struct("WitWorldMismatch")
                .field("configured_byte_len", &configured.len())
                .field("manifest_byte_len", &manifest.len())
                .finish(),
            Self::UnsupportedWitWorld { wit_world } => formatter
                .debug_struct("UnsupportedWitWorld")
                .field("wit_world_byte_len", &wit_world.len())
                .finish(),
            Self::Disabled { identity } => formatter
                .debug_struct("Disabled")
                .field("identity", identity)
                .finish(),
            Self::InvalidComponentPath { identity, source } => formatter
                .debug_struct("InvalidComponentPath")
                .field("identity", identity)
                .field("source", source)
                .finish(),
            Self::InvalidRuntimeLimits { identity, source } => formatter
                .debug_struct("InvalidRuntimeLimits")
                .field("identity", identity)
                .field("source", source)
                .finish(),
        }
    }
}

impl Debug for PluginManifestOpenError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Read { source } => formatter
                .debug_struct("Read")
                .field("source", &FileReadErrorShape::from(source))
                .finish(),
            Self::Parse {
                display_path,
                source,
            } => formatter
                .debug_struct("Parse")
                .field("display_path_byte_len", &display_path.as_str().len())
                .field("source", &JsonErrorShape::from(source))
                .finish(),
        }
    }
}

impl Debug for PluginComponentOpenError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Read { identity, source } => formatter
                .debug_struct("Read")
                .field("identity", identity)
                .field("source", &FileReadErrorShape::from(source))
                .finish(),
        }
    }
}

impl Debug for PluginRegistryError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidIdentity { identity, source } => formatter
                .debug_struct("InvalidIdentity")
                .field("identity_byte_len", &identity.len())
                .field("source", source)
                .finish(),
            Self::DuplicateIdentity { identity } => formatter
                .debug_struct("DuplicateIdentity")
                .field("identity", identity)
                .finish(),
            Self::InvalidEnabledComponentPath { identity, source } => formatter
                .debug_struct("InvalidEnabledComponentPath")
                .field("identity", identity)
                .field("source", source)
                .finish(),
            Self::UnsupportedEnabledWitWorld {
                identity,
                wit_world,
            } => formatter
                .debug_struct("UnsupportedEnabledWitWorld")
                .field("identity", identity)
                .field("wit_world_byte_len", &wit_world.len())
                .finish(),
            Self::InvalidEnabledRuntimeLimits { identity, source } => formatter
                .debug_struct("InvalidEnabledRuntimeLimits")
                .field("identity", identity)
                .field("source", source)
                .finish(),
        }
    }
}

impl Display for PluginRegistryError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidIdentity { identity, source } => {
                write!(
                    formatter,
                    "plugin identity {identity:?} is invalid: {source}"
                )
            }
            Self::DuplicateIdentity { identity } => {
                let identity = identity.as_str();
                write!(
                    formatter,
                    "plugin identity {identity:?} is configured more than once"
                )
            }
            Self::InvalidEnabledComponentPath { identity, source } => {
                let identity = identity.as_str();
                write!(
                    formatter,
                    "enabled plugin {identity:?} has invalid component path: {source}"
                )
            }
            Self::UnsupportedEnabledWitWorld {
                identity,
                wit_world,
            } => {
                let identity = identity.as_str();
                write!(
                    formatter,
                    "enabled plugin {identity:?} uses unsupported WIT world {wit_world:?}"
                )
            }
            Self::InvalidEnabledRuntimeLimits { identity, source } => {
                let identity = identity.as_str();
                write!(
                    formatter,
                    "enabled plugin {identity:?} has invalid runtime limits: {source}"
                )
            }
        }
    }
}

impl Display for PluginLoadError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidIdentity { identity, source } => {
                write!(
                    formatter,
                    "plugin identity {identity:?} is invalid: {source}"
                )
            }
            Self::ManifestParse { path, source } => {
                if let Some(path) = path {
                    write!(
                        formatter,
                        "failed to parse plugin manifest {}: {source}",
                        display_path(path)
                    )
                } else {
                    write!(formatter, "failed to parse plugin manifest: {source}")
                }
            }
            Self::IdentityMismatch {
                configured,
                manifest,
            } => {
                let configured = configured.as_str();
                let manifest = manifest.as_str();
                write!(
                    formatter,
                    "plugin identity mismatch: configured {configured:?}, manifest {manifest:?}"
                )
            }
            Self::WitWorldMismatch {
                configured,
                manifest,
            } => write!(
                formatter,
                "plugin WIT world mismatch: configured {configured:?}, manifest {manifest:?}"
            ),
            Self::UnsupportedWitWorld { wit_world } => {
                write!(formatter, "plugin WIT world {wit_world:?} is not supported")
            }
            Self::Disabled { identity } => {
                let identity = identity.as_str();
                write!(formatter, "plugin {identity:?} is disabled")
            }
            Self::InvalidComponentPath { identity, source } => {
                let identity = identity.as_str();
                write!(
                    formatter,
                    "plugin {identity:?} has invalid component path: {source}"
                )
            }
            Self::InvalidRuntimeLimits { identity, source } => {
                let identity = identity.as_str();
                write!(
                    formatter,
                    "plugin {identity:?} has invalid runtime limits: {source}"
                )
            }
        }
    }
}

impl Display for PluginManifestOpenError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Read { source } => write!(formatter, "failed to open plugin manifest: {source}"),
            Self::Parse {
                display_path,
                source,
            } => write!(
                formatter,
                "failed to parse plugin manifest {}: {source}",
                display_path.as_str()
            ),
        }
    }
}

impl Display for PluginComponentOpenError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Read { identity, source } => {
                let identity = identity.as_str();
                write!(
                    formatter,
                    "failed to open component for plugin {identity:?}: {source}"
                )
            }
        }
    }
}

/// Errors returned while validating a stable plugin identity.
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PluginIdentityError {
    /// Identity was empty.
    Empty,
    /// Identity exceeded the supported length.
    TooLong,
    /// Identity did not start with an ASCII lowercase letter or digit.
    InvalidStart,
    /// Identity contained a byte outside the allowed ASCII grammar.
    InvalidCharacter,
}

impl Display for PluginIdentityError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Empty => formatter.write_str("plugin identity must not be empty"),
            Self::TooLong => formatter.write_str("plugin identity must be at most 128 bytes"),
            Self::InvalidStart => formatter
                .write_str("plugin identity must start with a lowercase ASCII letter or digit"),
            Self::InvalidCharacter => formatter.write_str(
                "plugin identity may contain only lowercase ASCII letters, digits, '.', '_' or '-'",
            ),
        }
    }
}

/// Runtime limit fields with stable diagnostic spellings.
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum PluginRuntimeLimitField {
    /// Maximum linear memory bytes per guest instance.
    MaxMemoryBytes,
    /// Maximum host-call payload bytes.
    MaxMessageBytes,
    /// Maximum fuel units per guest update.
    FuelPerUpdate,
    /// Maximum wall-clock milliseconds per guest update.
    TimeoutMs,
    /// Maximum sealed effect batches awaiting ECS publication.
    MaxIntentBatches,
}

impl PluginRuntimeLimitField {
    /// Stable field name used in diagnostics and schemas.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MaxMemoryBytes => "max_memory_bytes",
            Self::MaxMessageBytes => "max_message_bytes",
            Self::FuelPerUpdate => "fuel_per_update",
            Self::TimeoutMs => "timeout_ms",
            Self::MaxIntentBatches => "max_intent_batches",
        }
    }
}

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

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

/// Errors returned while validating configured runtime limits.
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PluginRuntimeLimitError {
    /// A limit was configured as zero.
    Zero {
        /// Runtime limit field name.
        field: PluginRuntimeLimitField,
    },
    /// A limit exceeded the host safety cap.
    TooLarge {
        /// Runtime limit field name.
        field: PluginRuntimeLimitField,
        /// Configured value.
        value: u64,
        /// Maximum accepted value.
        max: u64,
    },
}

impl Display for PluginRuntimeLimitError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Zero { field } => {
                write!(formatter, "plugin runtime limit {field} must be non-zero")
            }
            Self::TooLarge { field, value, max } => write!(
                formatter,
                "plugin runtime limit {field}={value} exceeds maximum {max}"
            ),
        }
    }
}

/// Errors returned while validating a configured component path.
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PluginComponentPathError {
    /// Component path was empty.
    Empty,
    /// Component path was absolute or platform-prefixed.
    Absolute,
    /// Component path contained `.` or `..`.
    DotComponent,
    /// Component path contained an empty component.
    EmptyComponent,
    /// Component path used platform-specific separators.
    PlatformSeparator,
    /// Component path used a Windows drive prefix.
    WindowsDrivePrefix,
}

impl Display for PluginComponentPathError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Empty => formatter.write_str("plugin component path must not be empty"),
            Self::Absolute => {
                formatter.write_str("plugin component path must be workspace-relative")
            }
            Self::DotComponent => {
                formatter.write_str("plugin component path must not contain . or .. components")
            }
            Self::EmptyComponent => {
                formatter.write_str("plugin component path must not contain empty components")
            }
            Self::PlatformSeparator => {
                formatter.write_str("plugin component path must use / separators")
            }
            Self::WindowsDrivePrefix => {
                formatter.write_str("plugin component path must not use Windows drive prefixes")
            }
        }
    }
}

/// Errors returned when a guest attempts a denied host import.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PluginAuthorizationError {
    /// Plugin has no grant for the requested capability.
    Denied {
        /// Stable plugin identity.
        identity: PluginIdentity,
        /// Redacted capability request shape.
        capability: PluginCapabilityShape,
    },
}

impl Display for PluginAuthorizationError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Denied {
                identity,
                capability,
            } => {
                let identity = identity.as_str();
                write!(
                    formatter,
                    "plugin {identity:?} is not authorized for {capability}"
                )
            }
        }
    }
}

/// Errors returned when converting WIT capability data into an authorization query.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum WitCapabilityRefError {
    /// Capability requires a workspace-relative path argument.
    MissingPath {
        /// Redacted capability shape.
        capability: PluginCapabilityShape,
    },
    /// Capability does not accept a workspace-relative path argument.
    UnexpectedPath {
        /// Redacted capability shape.
        capability: PluginCapabilityShape,
    },
    /// Capability was given a path argument that failed host validation.
    InvalidPath {
        /// Redacted capability shape.
        capability: PluginCapabilityShape,
        /// Path validation failure.
        source: WorkspacePathError,
    },
}

impl Display for WitCapabilityRefError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MissingPath { capability } => {
                write!(formatter, "{capability} requires a workspace-relative path")
            }
            Self::UnexpectedPath { capability } => {
                write!(
                    formatter,
                    "{capability} does not accept a workspace-relative path"
                )
            }
            Self::InvalidPath { capability, source } => {
                write!(formatter, "{capability} path is invalid: {source}")
            }
        }
    }
}

/// Redacted shape for a plugin capability request.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PluginCapabilityShape {
    /// `buffer.observe`.
    BufferObserve,
    /// `buffer.propose_edit`.
    BufferProposeEdit,
    /// `workspace.observe`, without the requested path.
    WorkspaceObserve,
    /// `workspace.artifact_write`, without the requested path.
    WorkspaceArtifactWrite,
    /// `status.publish`.
    StatusPublish,
}

impl Display for PluginCapabilityShape {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BufferObserve => formatter.write_str("buffer.observe"),
            Self::BufferProposeEdit => formatter.write_str("buffer.propose_edit"),
            Self::WorkspaceObserve => formatter.write_str("workspace.observe"),
            Self::WorkspaceArtifactWrite => formatter.write_str("workspace.artifact_write"),
            Self::StatusPublish => formatter.write_str("status.publish"),
        }
    }
}

/// Escapes a path for diagnostics.
fn display_path(path: &std::path::Path) -> String {
    EscapedDisplayText::from_path(path).as_str().to_owned()
}

/// Returns path display length without retaining path text.
fn path_byte_len(path: &Path) -> usize {
    path.to_string_lossy().len()
}

/// Redacted JSON parse shape.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct JsonErrorShape {
    /// Error category without document text.
    category: JsonErrorCategory,
    /// One-based line reported by `serde_json`.
    line: usize,
    /// One-based column reported by `serde_json`.
    column: usize,
}

impl From<&serde_json::Error> for JsonErrorShape {
    fn from(source: &serde_json::Error) -> Self {
        Self {
            category: JsonErrorCategory::from(source.classify()),
            line: source.line(),
            column: source.column(),
        }
    }
}

/// Stable JSON error class for redacted debug output.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum JsonErrorCategory {
    /// Input was not valid JSON.
    Syntax,
    /// Input had valid JSON syntax but did not match the expected shape.
    Data,
    /// End of file arrived before a complete value.
    Eof,
    /// I/O failed while parsing.
    Io,
}

impl From<serde_json::error::Category> for JsonErrorCategory {
    fn from(category: serde_json::error::Category) -> Self {
        match category {
            serde_json::error::Category::Syntax => Self::Syntax,
            serde_json::error::Category::Data => Self::Data,
            serde_json::error::Category::Eof => Self::Eof,
            serde_json::error::Category::Io => Self::Io,
        }
    }
}

/// Redacted filesystem-read failure shape.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum FileReadErrorShape {
    /// Path policy rejected the request.
    Policy(PathPolicyErrorShape),
    /// Path did not resolve to an existing file.
    Missing,
    /// Metadata could not be read.
    Metadata,
    /// File kind was not accepted.
    UnsupportedFileType,
    /// File exceeded the caller's byte cap.
    TooLarge {
        /// Observed bytes.
        size: u64,
        /// Accepted bytes.
        max_size: u64,
    },
    /// Opening the file failed.
    Open,
    /// Reading the file failed.
    Read,
}

impl From<&FileReadError> for FileReadErrorShape {
    fn from(source: &FileReadError) -> Self {
        match source {
            FileReadError::Policy(source) => Self::Policy(PathPolicyErrorShape::from(source)),
            FileReadError::Missing { .. } => Self::Missing,
            FileReadError::Metadata { .. } => Self::Metadata,
            FileReadError::UnsupportedFileType { .. } => Self::UnsupportedFileType,
            FileReadError::TooLarge { size, max_size, .. } => Self::TooLarge {
                size: *size,
                max_size: *max_size,
            },
            FileReadError::Open { .. } => Self::Open,
            FileReadError::Read { .. } => Self::Read,
        }
    }
}

/// Redacted path-policy failure shape.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PathPolicyErrorShape {
    /// Current directory lookup failed.
    CurrentDir,
    /// Requested path had no parent.
    MissingParent,
    /// Parent resolution failed.
    Parent,
    /// Target resolution failed.
    Unresolvable,
    /// Target escaped the workspace root.
    OutsideWorkspace,
}

impl From<&PathPolicyError> for PathPolicyErrorShape {
    fn from(source: &PathPolicyError) -> Self {
        match source {
            PathPolicyError::CurrentDir { .. } => Self::CurrentDir,
            PathPolicyError::MissingParent { .. } => Self::MissingParent,
            PathPolicyError::Parent { .. } => Self::Parent,
            PathPolicyError::Unresolvable { .. } => Self::Unresolvable,
            PathPolicyError::OutsideWorkspace { .. } => Self::OutsideWorkspace,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        PluginAuthorizationError, PluginCapabilityShape, PluginComponentOpenError, PluginLoadError,
        PluginManifestOpenError, PluginRegistryError, WitCapabilityRefError,
    };
    use crate::{
        fs_utils::{EscapedDisplayText, FileReadError, PathPolicyError},
        plugin::{
            PluginComponentPathError, PluginIdentity, PluginIdentityError, PluginRuntimeLimitError,
            PluginRuntimeLimitField, WorkspacePathError,
        },
    };
    use std::{io, path::PathBuf};

    #[test]
    fn manifest_parse_display_escapes_hostile_path_text() {
        let source = serde_json::from_slice::<serde_json::Value>(b"{")
            .expect_err("fixture should be invalid json");
        let error = PluginLoadError::ManifestParse {
            path: Some(PathBuf::from("plugins/evil\n\u{202E}manifest.json")),
            source,
        };

        let display = error.to_string();

        assert!(display.contains("\\n"));
        assert!(display.contains("\\u{202E}"));
        assert!(!display.contains('\n'));
        assert!(!display.contains('\u{202E}'));
    }

    #[test]
    fn authorization_display_uses_capability_shape_not_guest_path() {
        let error = PluginAuthorizationError::Denied {
            identity: PluginIdentity::try_new("formatter").expect("identity"),
            capability: PluginCapabilityShape::WorkspaceArtifactWrite,
        };

        let display = error.to_string();

        assert!(display.contains("workspace.artifact_write"));
        assert!(!display.contains("docs/private"));
        assert!(!display.contains("secret"));
    }

    #[test]
    fn wit_capability_path_errors_do_not_echo_malformed_guest_path() {
        let error = WitCapabilityRefError::InvalidPath {
            capability: PluginCapabilityShape::WorkspaceObserve,
            source: WorkspacePathError::DotComponent,
        };

        let display = error.to_string();

        assert_eq!(
            display,
            "workspace.observe path is invalid: workspace plugin paths must not contain . or .. components"
        );
        assert!(!display.contains("../secret"));
    }

    #[test]
    fn invalid_identity_display_reports_reason_without_raw_payload_context() {
        let error = PluginLoadError::InvalidIdentity {
            identity: String::from("Bad\nsecret"),
            source: PluginIdentityError::InvalidStart,
        };

        let display = error.to_string();

        assert!(display.contains("InvalidStart") || display.contains("must start"));
        assert!(display.contains("\\n"));
        assert!(!display.contains('\n'));
    }

    #[test]
    fn load_error_debug_redacts_untrusted_payloads() {
        let parse_error = serde_json::from_slice::<serde_json::Value>(b"{")
            .expect_err("fixture should be invalid json");
        let manifest_parse = PluginLoadError::ManifestParse {
            path: Some(PathBuf::from("plugins/secret-manifest.json")),
            source: parse_error,
        };
        let invalid_identity = PluginLoadError::InvalidIdentity {
            identity: String::from("Bad\nsecret-identity"),
            source: PluginIdentityError::InvalidCharacter,
        };
        let unsupported_world = PluginLoadError::UnsupportedWitWorld {
            wit_world: String::from("alma:secret/plugin@9.9.9"),
        };
        let world_mismatch = PluginLoadError::WitWorldMismatch {
            configured: String::from("alma:editor/plugin@0.2.0"),
            manifest: String::from("alma:secret/plugin@9.9.9"),
        };

        for debug in [
            format!("{manifest_parse:?}"),
            format!("{invalid_identity:?}"),
            format!("{unsupported_world:?}"),
            format!("{world_mismatch:?}"),
        ] {
            assert!(!debug.contains("secret"));
            assert!(!debug.contains("Bad\n"));
            assert!(!debug.contains("alma:secret"));
        }

        assert!(format!("{manifest_parse:?}").contains("path_byte_len"));
        assert!(format!("{invalid_identity:?}").contains("identity_byte_len"));
        assert!(format!("{unsupported_world:?}").contains("wit_world_byte_len"));
        assert!(format!("{world_mismatch:?}").contains("manifest_byte_len"));
    }

    #[test]
    fn registry_error_debug_redacts_untrusted_config_payloads() {
        let invalid_identity = PluginRegistryError::InvalidIdentity {
            identity: String::from("Bad\nsecret-registry-identity"),
            source: PluginIdentityError::InvalidCharacter,
        };
        let unsupported_world = PluginRegistryError::UnsupportedEnabledWitWorld {
            identity: PluginIdentity::try_new("formatter").expect("identity"),
            wit_world: String::from("alma:secret/plugin@9.9.9"),
        };
        let invalid_path = PluginRegistryError::InvalidEnabledComponentPath {
            identity: PluginIdentity::try_new("formatter").expect("identity"),
            source: PluginComponentPathError::DotComponent,
        };
        let invalid_limit = PluginRegistryError::InvalidEnabledRuntimeLimits {
            identity: PluginIdentity::try_new("formatter").expect("identity"),
            source: PluginRuntimeLimitError::TooLarge {
                field: PluginRuntimeLimitField::MaxMemoryBytes,
                value: 8,
                max: 4,
            },
        };

        let invalid_identity_debug = format!("{invalid_identity:?}");
        let unsupported_world_debug = format!("{unsupported_world:?}");
        let invalid_path_debug = format!("{invalid_path:?}");
        let invalid_limit_debug = format!("{invalid_limit:?}");

        assert!(invalid_identity_debug.contains("identity_byte_len"));
        assert!(!invalid_identity_debug.contains("secret-registry-identity"));
        assert!(!invalid_identity_debug.contains("Bad\n"));
        assert!(unsupported_world_debug.contains("wit_world_byte_len"));
        assert!(!unsupported_world_debug.contains("alma:secret"));
        assert!(invalid_path_debug.contains("DotComponent"));
        assert!(invalid_limit_debug.contains("max_memory_bytes"));
    }

    #[test]
    fn open_error_debug_redacts_filesystem_sources() {
        let manifest = PluginManifestOpenError::Read {
            source: FileReadError::Policy(PathPolicyError::OutsideWorkspace {
                path: PathBuf::from("/tmp/secret-manifest.json"),
                workspace_root: PathBuf::from("/tmp/secret-workspace"),
            }),
        };
        let component = PluginComponentOpenError::Read {
            identity: PluginIdentity::try_new("formatter").expect("identity"),
            source: FileReadError::Open {
                path: PathBuf::from("/tmp/secret-component.wasm"),
                source: io::Error::new(io::ErrorKind::PermissionDenied, "secret os detail"),
            },
        };
        let parse_error = serde_json::from_slice::<serde_json::Value>(b"{")
            .expect_err("fixture should be invalid json");
        let parse = PluginManifestOpenError::Parse {
            display_path: EscapedDisplayText::from_display_text("plugins/secret-manifest.json"),
            source: parse_error,
        };

        let manifest_debug = format!("{manifest:?}");
        let component_debug = format!("{component:?}");
        let parse_debug = format!("{parse:?}");

        assert!(manifest_debug.contains("OutsideWorkspace"));
        assert!(!manifest_debug.contains("secret-manifest"));
        assert!(!manifest_debug.contains("secret-workspace"));
        assert!(component_debug.contains("Open"));
        assert!(!component_debug.contains("secret-component"));
        assert!(!component_debug.contains("secret os detail"));
        assert!(parse_debug.contains("display_path_byte_len"));
        assert!(!parse_debug.contains("secret-manifest"));
    }
}