soma-som-core 0.1.0

Universal soma(som) structural primitives — Quad / Tree / Ring / Genesis / Fingerprint / TemporalLedger / CrossingRecord
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
// SPDX-License-Identifier: LGPL-3.0-only
#![allow(missing_docs)]

//! Extension: the structural contract for ring-external services.
//!
//! ## Five Ring Relationships
//!
//! Every service that interacts with the ring occupies one of five
//! structural positions (BEFORE/THROUGH/AFTER/AROUND/WITHIN), each
//! with a distinct lifecycle and contract.

use crate::crossing::CrossingRecord;
use crate::quad::Tree;

// ── Command Schema ──────────────────────────────────────────────

/// The type of a schema field value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SchemaFieldType {
    String,
    Number,
    Boolean,
    Object,
    Array,
}

impl SchemaFieldType {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::String => "string",
            Self::Number => "number",
            Self::Boolean => "boolean",
            Self::Object => "object",
            Self::Array => "array",
        }
    }

    /// Parse from a string value.
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "string" => Some(Self::String),
            "number" => Some(Self::Number),
            "boolean" => Some(Self::Boolean),
            "object" => Some(Self::Object),
            "array" => Some(Self::Array),
            _ => None,
        }
    }
}

impl std::fmt::Display for SchemaFieldType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// A single field in a command payload schema.
#[derive(Debug, Clone)]
pub struct SchemaField {
    /// Field name (e.g., `"username"`).
    pub name: String,
    /// Expected value type.
    pub field_type: SchemaFieldType,
    /// Whether this field must be present in the payload.
    pub required: bool,
    /// Optional S-FEEL validation expression.
    ///
    /// When set, the field value is bound to the field name in a FEEL context
    /// and the expression is evaluated. The expression must return a truthy value
    /// for the payload to pass validation.
    ///
    /// Examples: `"timeout <= 30000"`, `"string length(username) >= 3"`
    pub validation: Option<String>,
}

impl SchemaField {
    /// Create a required field.
    pub fn required(name: impl Into<String>, field_type: SchemaFieldType) -> Self {
        Self {
            name: name.into(),
            field_type,
            required: true,
            validation: None,
        }
    }

    /// Create an optional field.
    pub fn optional(name: impl Into<String>, field_type: SchemaFieldType) -> Self {
        Self {
            name: name.into(),
            field_type,
            required: false,
            validation: None,
        }
    }

    /// Add a FEEL validation expression to this field. Builder pattern.
    pub fn with_validation(mut self, expression: impl Into<String>) -> Self {
        self.validation = Some(expression.into());
        self
    }
}

/// Schema for a command payload — declares expected fields and types.
///
/// Schemas are additive: extra fields not listed in the schema are allowed.
/// Only required fields are enforced at validation time.
///
/// The schema type lives in `soma-som-core` because it is a structural spec
/// primitive. Concrete payload validation against the schema lives in
/// `soma-som-ring` where `serde_json` is in scope.
#[derive(Debug, Clone)]
pub struct CommandSchema {
    /// Command type this schema applies to (e.g., `"user.create"`).
    pub command_type: String,
    /// Fields expected in the JSON payload.
    pub fields: Vec<SchemaField>,
}

impl CommandSchema {
    pub fn new(command_type: impl Into<String>) -> Self {
        Self {
            command_type: command_type.into(),
            fields: Vec::new(),
        }
    }

    /// Add a field to this schema. Builder pattern.
    pub fn field(mut self, field: SchemaField) -> Self {
        self.fields.push(field);
        self
    }
}

/// The five structural positions an extension can occupy relative to the ring.
///
/// # Deprecated
///
/// `RingRelationship` is decorative only: the ring engine dispatches by registration
/// phase (via `register_before` / `register_through` etc.), never by calling
/// `.relationship()`. The structural phase boundary is encoded in the phase trait type
/// itself (BeforeRing / ThroughRing / …). This enum will be removed in a future release.
/// Existing impls should remove `fn relationship()` from their `Extension` impl block.
#[deprecated(
    since = "0.2.0",
    note = "Phase is encoded in the trait type; RingRelationship is decorative. \
            Remove fn relationship() from Extension impls."
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RingRelationship {
    Before,
    Through,
    After,
    Around,
    Within,
}

#[allow(deprecated)]
impl std::fmt::Display for RingRelationship {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Before => write!(f, "BEFORE"),
            Self::Through => write!(f, "THROUGH"),
            Self::After => write!(f, "AFTER"),
            Self::Around => write!(f, "AROUND"),
            Self::Within => write!(f, "WITHIN"),
        }
    }
}

/// Base trait for all ring extensions.
///
/// `name()` is used by the ring engine for registration-collision detection.
/// The `relationship()` method has been removed — phase is encoded in the
/// phase-specific trait type (BeforeRing / ThroughRing / …).
pub trait Extension: Send + Sync {
    fn name(&self) -> &str;
}

/// Error from a BEFORE gate rejection.
#[derive(Debug, Clone)]
pub struct GateRejection {
    pub source: String,
    pub reason: String,
}

impl std::fmt::Display for GateRejection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.source, self.reason)
    }
}

impl std::error::Error for GateRejection {}

/// BEFORE — pre-ring gate.
pub trait BeforeRing: Extension {
    fn evaluate(&self, context: &Tree) -> Result<(), GateRejection>;
    fn feedback(&self, _cycle_index: u64, _output: &Tree) {}
}

/// Error from a THROUGH delegation failure.
#[derive(Debug, Clone)]
pub struct DelegationError {
    pub source: String,
    pub reason: String,
}

impl std::fmt::Display for DelegationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.source, self.reason)
    }
}

impl std::error::Error for DelegationError {}

/// THROUGH — intra-ring delegation target.
///
/// Each organ implements this to self-register its command handlers.
/// OU iterates delegates: `handles()` → `dispatch()`. First match wins.
///
/// ## Security: ring-cycle evidence
///
/// `dispatch()` is called by OU **during ring traversal** — never directly
/// from the web layer or any external code. The input Tree carries ring-cycle
/// evidence keys (e.g. `command.request_id`) injected by `inject_command()`.
/// These keys are absent when a delegate is called outside the ring.
///
/// Delegates SHOULD call [`crate::evidence::verify_ring_cycle_evidence`] at the start of
/// `dispatch()` to reject calls that bypassed ring mediation. This is a
/// defense-in-depth tripwire — the structural prevention is that the engine
/// does not expose the dispatch surface externally.
pub trait ThroughRing: Extension {
    /// Returns true if this delegate handles the given command type.
    /// Convention: organs claim a prefix family (e.g. `namespace-a.*`, `namespace-b.*`).
    fn handles(&self, command_type: &str) -> bool;

    /// Dispatch a command. The input Tree carries `command.type`,
    /// `command.payload`, `command.request_id`. Returns a result Tree
    /// with `result.status`, `result.payload`, `result.error`, `result.request_id`.
    ///
    /// Implementors SHOULD call [`crate::evidence::verify_ring_cycle_evidence`] first.
    fn dispatch(&self, input: &Tree) -> Result<Tree, DelegationError>;

    /// Declare permission requirements for commands this extension handles.
    ///
    /// Each requirement maps a command type to a minimum role level and
    /// AEQ policy terms. The ring engine collects these during extension
    /// registration and passes them to CU for authorization.
    ///
    /// This is the ring-native replacement for hardcoded `required_permission()`
    /// entries in `soma-core/src/rbac.rs`. Organs own their policy — the ring
    /// provides the mechanism.
    ///
    /// Default: empty (backward compatible — uses hardcoded fallback in CU).
    fn permission_requirements(&self) -> Vec<PermissionRequirement> {
        Vec::new()
    }

    /// Declare the command-type prefixes this delegate claims.
    ///
    /// Used by `RingEngine::register_through()` for prefix-overlap collision
    /// detection at registration time. Each prefix should match the pattern
    /// used in `handles()` (e.g., `"user."`, `"store.artifact."`).
    ///
    /// Default: empty (backward compatible — no collision check performed).
    /// Delegates that return a non-empty list get compile-time-catchable
    /// collision detection via `cargo test`.
    fn claimed_prefixes(&self) -> Vec<String> {
        Vec::new()
    }

    /// Declare payload schemas for commands this delegate handles.
    ///
    /// Each schema maps a command type to its expected payload structure.
    /// The ring engine collects these during registration and validates
    /// payloads at FU.Data injection time — before ring traversal begins.
    ///
    /// Default: empty (backward compatible — no payload validation).
    fn command_schemas(&self) -> Vec<CommandSchema> {
        Vec::new()
    }
}

// Evidence-verification helpers (`verify_ring_cycle_evidence`,
// `verify_ring_cycle_evidence_with_key`, `verify_view_cycle_evidence`) and the
// §13.1 `EvidenceValidator` trait now live in [`crate::evidence`]. Re-exported
// here for compatibility with existing call-sites; the canonical location is
// [`crate::evidence`].
pub use crate::evidence::{
    verify_ring_cycle_evidence, verify_ring_cycle_evidence_with_key, verify_view_cycle_evidence,
};

/// VIEW — intra-ring projection target.
///
/// Symmetric to [`ThroughRing`] but for views: where `ThroughRing` dispatches
/// `RingCommand` envelopes, `ViewRing` projects `ViewIntent` envelopes. The
/// separation gives commands and views distinct envelope shapes (the alternative — a single envelope with a discriminator — was rejected because:
/// "distinct shape is the signal"). A single organ may register one
/// `ThroughRing` impl for commands and one `ViewRing` impl for views — each
/// stays narrow to its own concern (Solitaire isolation: own trait).
///
/// ## Cycle position
///
/// OU iterates registered view delegates when the input Tree carries a
/// `ViewIntent` (detected by the `view.id` key prefix). First `handles_view`
/// match wins; the delegate's `project` is called; the returned Tree's
/// `view.result.*` keys are merged into OU's server output and carried
/// forward to SU.
///
/// ## Security: ring-cycle evidence
///
/// `project()` is called by OU **during ring traversal** — never directly
/// from the web layer or any external code. The input Tree carries the
/// `view.id` / `view.scope` / `view.requestor_role` / `view.request_id`
/// keys injected by `inject_view_intent()` in the ring engine. Delegates SHOULD
/// call [`crate::evidence::verify_view_cycle_evidence`] at the start of `project()` to
/// reject calls that bypassed ring mediation.
///
/// ## Authorization scope
///
/// Scope filtering (what fields the requestor may see) is the delegate's
/// responsibility, informed by `view.scope` + `view.requestor_role`. The
/// ring mediates that the delegate sees the scope/role at all; the delegate
/// decides the projection slice.
pub trait ViewRing: Extension {
    /// Returns true if this delegate handles the given view id.
    /// Convention: organs claim a prefix family (e.g. `organ.status`,
    /// `term.info.`) and/or an exact id.
    fn handles_view(&self, view_id: &str) -> bool;

    /// Project data for the view request encoded in `input`. Input carries
    /// `view.id`, `view.scope`, `view.requestor_role`, `view.request_id`.
    /// Returns a result Tree with `view.result.status` (`success` | `error` |
    /// `denied`), `view.result.payload` (JSON bytes), `view.result.error`
    /// (UTF-8 message when status != success), `view.result.request_id`.
    ///
    /// Implementors SHOULD call [`crate::evidence::verify_view_cycle_evidence`] first.
    fn project(&self, input: &Tree) -> Result<Tree, DelegationError>;

    /// Declare the view-id prefixes this delegate claims.
    ///
    /// Used by `RingEngine::register_view()` for prefix-overlap collision
    /// detection at registration time. Each entry should match the pattern
    /// used in `handles_view()` (e.g. `"organ.status"` for exact, `"term.info."`
    /// for prefix).
    ///
    /// Default: empty (backward compatible — no collision check performed).
    fn claimed_view_prefixes(&self) -> Vec<String> {
        Vec::new()
    }
}

/// AFTER — post-cycle observation.
///
/// Implementors receive two notifications per cycle:
///
/// 1. `on_cycle_complete` — called with the OU output Tree. Suitable for
///    detecting anomalous values, entropy analysis, and feeding findings
///    back via analysis keys (e.g. `"analysis.finding.*"`).
///
/// 2. `on_crossings` — called with the full crossing record slice.
///    Suitable for timing side-channel detection (S8), per-crossing
///    duration analysis, and cross-cycle pattern correlation. Defaults
///    to a no-op so existing implementations require no change.
///
/// Both are called in Phase 5 of the cycle lifecycle, after ring traversal
/// and persistence (WITHIN) have completed.
pub trait AfterRing: Extension {
    fn on_cycle_complete(&self, cycle_index: u64, output: &Tree);

    /// Called with the crossing records produced by this cycle.
    /// Default implementation is a no-op.
    fn on_crossings(&self, _cycle_index: u64, _records: &[CrossingRecord]) {}
}

/// AROUND — the Two Doors (inject + observe).
pub trait AroundRing: Extension {
    fn inject(&self, fu_data: &mut Tree);
    fn observe(&self, cycle_index: u64, ou_output: &Tree, su_output: &Tree);
}

// WITHIN = RingStore (P1). No additional trait needed.

// Sibling extension types (`DomainRequest`, `SiblingManifest`,
// `RegistrationError`, `CapabilityDeclaration`, `SurfaceSection`,
// `RouteMount`, `HttpMethod`, `SiblingStatus`) live in [`crate::sibling`].
// They were previously also defined here with a divergent shape; the
// unified definition in [`crate::sibling`] is canonical. Re-exported here
// for compatibility with existing call-sites.
pub use crate::sibling::{
    CapabilityDeclaration, DomainRequest, HttpMethod, RegistrationError, RouteMount,
    SiblingManifest, SiblingStatus, SurfaceSection,
};

// Permission + authorization-table types (`PermissionRequirement`,
// `PermissionRegistry`, `AuthorizationTable*`, `Shared*`) and the §13.1
// `AuthorizationProvider` trait now live in [`crate::authorization`].
// Re-exported here for compatibility with existing call-sites; the canonical
// location is [`crate::authorization`].
pub use crate::authorization::{
    AuthorizationTable, AuthorizationTableEntry, AuthorizationTableResult, PermissionCollision,
    PermissionRegistry, PermissionRequirement, SharedAuthorizationTable, SharedPermissionRegistry,
};

// inline: exercises module-private items via super::*
#[cfg(test)]
mod tests {
    use super::*;
    use crate::evidence::{verify_ring_cycle_evidence, verify_ring_cycle_evidence_with_key};
    use std::sync::Arc;

    #[test]
    fn extension_is_object_safe() {
        fn _assert(_: &dyn Extension) {}
    }

    #[test]
    fn before_ring_is_object_safe() {
        fn _assert(_: &dyn BeforeRing) {}
    }

    #[test]
    fn through_ring_is_object_safe() {
        fn _assert(_: &dyn ThroughRing) {}
    }

    #[test]
    fn after_ring_is_object_safe() {
        fn _assert(_: &dyn AfterRing) {}
    }

    #[test]
    fn around_ring_is_object_safe() {
        fn _assert(_: &dyn AroundRing) {}
    }

    #[allow(deprecated)]
    #[test]
    fn relationship_display() {
        assert_eq!(RingRelationship::Before.to_string(), "BEFORE");
        assert_eq!(RingRelationship::Through.to_string(), "THROUGH");
        assert_eq!(RingRelationship::After.to_string(), "AFTER");
        assert_eq!(RingRelationship::Around.to_string(), "AROUND");
        assert_eq!(RingRelationship::Within.to_string(), "WITHIN");
    }

    #[allow(deprecated)]
    #[test]
    fn relationship_equality() {
        assert_eq!(RingRelationship::Before, RingRelationship::Before);
        assert_ne!(RingRelationship::Before, RingRelationship::After);
    }

    #[test]
    fn gate_rejection_display() {
        let r = GateRejection {
            source: "gate-a".into(),
            reason: "rate limit".into(),
        };
        assert_eq!(r.to_string(), "gate-a: rate limit");
    }

    #[test]
    fn delegation_error_display() {
        let e = DelegationError {
            source: "delegate-b".into(),
            reason: "not found".into(),
        };
        assert_eq!(e.to_string(), "delegate-b: not found");
    }

    #[test]
    fn sibling_manifest_is_object_safe() {
        fn _assert(_: &dyn SiblingManifest) {}
    }

    #[test]
    fn registration_error_display() {
        let e = RegistrationError::DuplicateId("qi".into());
        assert_eq!(e.to_string(), "sibling 'qi' already registered");

        let e = RegistrationError::NamespaceConflict {
            prefix: "sibling.qi.".into(),
            claimed_by: "qi-v1".into(),
        };
        assert!(e.to_string().contains("already claimed by"));

        let e = RegistrationError::IncompatibleVersion {
            required: "2.0.0".into(),
            running: "1.0.0".into(),
        };
        assert!(e.to_string().contains("requires ring"));

        let e = RegistrationError::ProvisionFailed("disk full".into());
        assert!(e.to_string().contains("disk full"));
    }

    #[test]
    fn ring_cycle_evidence_present() {
        let mut tree = Tree::new();
        tree.insert("command.request_id".into(), b"req-abc-123".to_vec());
        tree.insert("command.type".into(), b"sibling.qi.analyze".to_vec());
        assert!(verify_ring_cycle_evidence("qi", &tree).is_ok());
    }

    #[test]
    fn ring_cycle_evidence_missing_rejects() {
        let mut tree = Tree::new();
        tree.insert("command.type".into(), b"sibling.qi.analyze".to_vec());
        // No command.request_id — called outside the ring
        let err = verify_ring_cycle_evidence("qi", &tree).unwrap_err();
        assert!(err.to_string().contains("outside ring cycle"));
    }

    #[test]
    fn ring_cycle_evidence_empty_tree_rejects() {
        let tree = Tree::new();
        assert!(verify_ring_cycle_evidence("test", &tree).is_err());
    }

    #[test]
    fn ring_cycle_evidence_with_key_custom_marker() {
        let mut tree = Tree::new();
        tree.insert("command.operator".into(), b"alice".to_vec());
        tree.insert("command.type".into(), b"tenant.provision".to_vec());
        assert!(
            verify_ring_cycle_evidence_with_key("tenant-through", &tree, "command.operator")
                .is_ok()
        );
    }

    #[test]
    fn ring_cycle_evidence_with_key_missing_custom_marker_rejects() {
        let mut tree = Tree::new();
        tree.insert("command.type".into(), b"tenant.provision".to_vec());
        let err =
            verify_ring_cycle_evidence_with_key("tenant-through", &tree, "command.operator")
                .unwrap_err();
        assert!(err.to_string().contains("command.operator"));
    }

    // ── SiblingManifest permission_requirements ─────────────

    /// Test sibling through_handler with declared permissions.
    struct PermDeclThrough {
        perms: Vec<PermissionRequirement>,
    }
    impl Extension for PermDeclThrough {
        fn name(&self) -> &str {
            "perm-test"
        }
    }
    impl ThroughRing for PermDeclThrough {
        fn handles(&self, cmd: &str) -> bool {
            cmd.starts_with("sibling.test.")
        }
        fn dispatch(&self, _input: &Tree) -> Result<Tree, DelegationError> {
            Ok(Tree::new())
        }
        fn permission_requirements(&self) -> Vec<PermissionRequirement> {
            self.perms.clone()
        }
    }

    /// Manifest that delegates permission_requirements to through_handler.
    struct DelegatingManifest {
        through: Option<Arc<dyn ThroughRing>>,
    }
    impl SiblingManifest for DelegatingManifest {
        fn id(&self) -> &str {
            "test"
        }
        fn display_name(&self) -> &str {
            "Test"
        }
        fn version(&self) -> &str {
            "1.0.0"
        }
        fn min_ring_version(&self) -> &str {
            "0.1.0"
        }
        fn through_handler(&self) -> Option<Arc<dyn ThroughRing>> {
            self.through.clone()
        }
    }

    #[test]
    fn manifest_permission_requirements_delegates_to_through_handler() {
        let through = Arc::new(PermDeclThrough {
            perms: vec![PermissionRequirement::new(
                "sibling.test.analyze",
                "operator",
                "a3",
                "routine",
                "a3",
            )],
        });
        let manifest = DelegatingManifest {
            through: Some(through),
        };
        let reqs = manifest.permission_requirements();
        assert_eq!(reqs.len(), 1);
        assert_eq!(reqs[0].command, "sibling.test.analyze");
        assert_eq!(reqs[0].min_role_key, "operator");
    }

    #[test]
    fn manifest_permission_requirements_empty_without_through_handler() {
        let manifest = DelegatingManifest { through: None };
        assert!(manifest.permission_requirements().is_empty());
    }

    #[test]
    fn manifest_permission_requirements_empty_when_handler_declares_none() {
        let through = Arc::new(PermDeclThrough { perms: vec![] });
        let manifest = DelegatingManifest {
            through: Some(through),
        };
        assert!(manifest.permission_requirements().is_empty());
    }

    #[allow(deprecated)]
    #[test]
    fn five_relationships_exhaustive() {
        let all = [
            RingRelationship::Before,
            RingRelationship::Through,
            RingRelationship::After,
            RingRelationship::Around,
            RingRelationship::Within,
        ];
        assert_eq!(all.len(), 5);
        for (i, a) in all.iter().enumerate() {
            for (j, b) in all.iter().enumerate() {
                if i != j {
                    assert_ne!(a, b);
                }
            }
        }
    }

    // ── CommandSchema tests ───────────────────────────────────

    #[test]
    fn schema_field_type_display_and_parse_roundtrip() {
        let types = [
            SchemaFieldType::String,
            SchemaFieldType::Number,
            SchemaFieldType::Boolean,
            SchemaFieldType::Object,
            SchemaFieldType::Array,
        ];
        for ft in types {
            let s = ft.as_str();
            let parsed = SchemaFieldType::parse(s).unwrap();
            assert_eq!(parsed, ft);
            assert_eq!(ft.to_string(), s);
        }
    }

    #[test]
    fn schema_field_type_parse_unknown_returns_none() {
        assert!(SchemaFieldType::parse("unknown").is_none());
        assert!(SchemaFieldType::parse("").is_none());
    }

    #[test]
    fn schema_field_required_and_optional() {
        let req = SchemaField::required("username", SchemaFieldType::String);
        assert!(req.required);
        assert_eq!(req.name, "username");
        assert_eq!(req.field_type, SchemaFieldType::String);

        let opt = SchemaField::optional("timeout", SchemaFieldType::Number);
        assert!(!opt.required);
        assert_eq!(opt.name, "timeout");
    }

    #[test]
    fn command_schema_builder() {
        let schema = CommandSchema::new("user.create")
            .field(SchemaField::required("username", SchemaFieldType::String))
            .field(SchemaField::required("password", SchemaFieldType::String))
            .field(SchemaField::optional("role", SchemaFieldType::String));

        assert_eq!(schema.command_type, "user.create");
        assert_eq!(schema.fields.len(), 3);
        assert!(schema.fields[0].required);
        assert!(schema.fields[1].required);
        assert!(!schema.fields[2].required);
    }

    #[test]
    fn command_schema_empty_fields() {
        let schema = CommandSchema::new("user.list");
        assert_eq!(schema.command_type, "user.list");
        assert!(schema.fields.is_empty());
    }

    #[test]
    fn through_ring_command_schemas_default_empty() {
        let through = PermDeclThrough { perms: vec![] };
        assert!(through.command_schemas().is_empty());
    }

    #[test]
    fn schema_field_with_validation() {
        let field = SchemaField::required("timeout", SchemaFieldType::Number)
            .with_validation("timeout <= 30000");
        assert!(field.required);
        assert_eq!(field.validation.as_deref(), Some("timeout <= 30000"));

        let plain = SchemaField::optional("debug", SchemaFieldType::Boolean);
        assert!(plain.validation.is_none());
    }
}