soma-som-ring 0.1.0

Standalone ring execution engine for soma(som): cycle lifecycle, extension registration, boundary mediation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
// SPDX-License-Identifier: LGPL-3.0-only
#![allow(missing_docs, clippy::should_implement_trait)]

//! Ring-mediated command protocol — types, injection, and extraction.
//!
//! ## Spec traceability
//! - 3-domain persistence: OU is the sole persistence boundary
//! - Ring command payload shape: type + payload (JSON-serializable) + actor
//!
//! ## Design
//!
//! Commands are encoded as `command.*` key-value entries in FU.Data.
//! Results are encoded as `result.*` entries in OU/SU output.
//! This module is transport-agnostic: it defines the ring protocol shape,
//! not application-layer routing logic.
//!
//! ## Key namespace
//!
//! | Key                  | Written by | Description                              |
//! |----------------------|------------|------------------------------------------|
//! | `command.type`       | Web → FU   | Command identifier (e.g. `user.create`)  |
//! | `command.payload`    | Web → FU   | JSON-serialized command parameters       |
//! | `command.request_id` | Web → FU   | Correlation ID for request tracking      |
//! | `result.status`      | OU → SU    | `success` or `error`                     |
//! | `result.command_type` | OU → SU   | Echo of the processed command type       |
//! | `result.payload`     | OU → SU    | JSON-serialized result data              |
//! | `result.error`       | OU → SU    | Error message (if status = error)        |
//! | `view.id`            | Web → FU   | View identifier (e.g. `organ.mirror`) |
//! | `view.request_id`    | Web → FU   | Correlation ID for view-request tracking |

use serde::{Deserialize, Serialize};
use soma_som_core::quad::{Quad, Tree};

// ── Command type constants ───────────────────────────────────────────────

/// Key prefix for all command entries in FU.Data.
pub const COMMAND_PREFIX: &str = "command.";

/// Key prefix for all result entries in OU/SU output.
pub const RESULT_PREFIX: &str = "result.";


// ── Command envelope ─────────────────────────────────────────────────────

/// A ring command injected into FU.Data for mediated processing.
///
/// The command envelope carries the operation type, a JSON payload,
/// the requesting actor identity, their role key, and a correlation ID.
/// All fields serialize to `command.*` Tree entries via [`RingCommand::inject_into`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RingCommand {
    /// Command type identifier (e.g. `user.create`).
    pub command_type: String,

    /// JSON-serialized command parameters.
    pub payload: String,

    /// Identity of the actor making the request (application-defined label).
    ///
    /// CU uses this for authorization decisions. Injected into the Tree
    /// as `command.admin` by convention; applications may interpret this
    /// field according to their own identity model.
    pub actor: String,

    /// Role key of the requesting actor (application-defined label).
    ///
    /// CU evaluates permissions based on this role key. Injected into
    /// the Tree as `command.role` by convention.
    pub role_key: String,

    /// Request correlation ID for tracing.
    ///
    /// Generated by the web layer, carried through all 6 units,
    /// returned in the result for response correlation.
    pub request_id: String,
}

impl RingCommand {
    /// Create a new ring command.
    pub fn new(
        command_type: impl Into<String>,
        payload: impl Into<String>,
        actor: impl Into<String>,
        role_key: impl Into<String>,
        request_id: impl Into<String>,
    ) -> Self {
        Self {
            command_type: command_type.into(),
            payload: payload.into(),
            actor: actor.into(),
            role_key: role_key.into(),
            request_id: request_id.into(),
        }
    }

    /// Inject this command into a Tree as `command.*` entries.
    pub fn inject_into(&self, tree: &mut Tree) {
        tree.insert("command.type".into(), self.command_type.as_bytes().to_vec());
        tree.insert("command.payload".into(), self.payload.as_bytes().to_vec());
        tree.insert("command.admin".into(), self.actor.as_bytes().to_vec());
        tree.insert("command.role".into(), self.role_key.as_bytes().to_vec());
        tree.insert(
            "command.request_id".into(),
            self.request_id.as_bytes().to_vec(),
        );
    }

    /// Extract a command from a Tree's `command.*` entries.
    ///
    /// Returns `None` if `command.type` is absent (not a command cycle).
    pub fn extract_from(tree: &Tree) -> Option<Self> {
        let command_type = tree
            .get("command.type")
            .map(|v| String::from_utf8_lossy(v).into_owned())?;

        let payload = tree
            .get("command.payload")
            .map(|v| String::from_utf8_lossy(v).into_owned())
            .unwrap_or_default();

        let actor = tree
            .get("command.admin")
            .map(|v| String::from_utf8_lossy(v).into_owned())
            .unwrap_or_default();

        let role_key = tree
            .get("command.role")
            .map(|v| String::from_utf8_lossy(v).into_owned())
            .unwrap_or_default();

        let request_id = tree
            .get("command.request_id")
            .map(|v| String::from_utf8_lossy(v).into_owned())
            .unwrap_or_default();

        Some(Self {
            command_type,
            payload,
            actor,
            role_key,
            request_id,
        })
    }

    /// Check if a Tree contains a command (has `command.type`).
    pub fn is_command(tree: &Tree) -> bool {
        tree.contains_key("command.type")
    }
}

// ── Result envelope ──────────────────────────────────────────────────────

/// Result status values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum CommandStatus {
    /// Command executed successfully.
    Success,
    /// Command was denied by CU (authorization failure).
    Denied,
    /// Command execution failed (DIRECTOR error, validation, etc.).
    Error,
}

impl CommandStatus {
    pub fn as_str(&self) -> &'static str {
        match self {
            CommandStatus::Success => "success",
            CommandStatus::Denied => "denied",
            CommandStatus::Error => "error",
        }
    }

    /// Parse from a string value.
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "success" => Some(CommandStatus::Success),
            "denied" => Some(CommandStatus::Denied),
            "error" => Some(CommandStatus::Error),
            _ => None,
        }
    }
}

/// A command result written by OU into the ring output.
///
/// SU reads this to produce the final result descriptor.
/// The web layer reads the descriptor from SU's output.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CommandResult {
    /// Execution status.
    pub status: CommandStatus,

    /// Echo of the command type that was processed.
    pub command_type: String,

    /// JSON-serialized result data (on success).
    pub payload: String,

    /// Error message (on error/denied).
    pub error: String,

    /// Correlation ID from the original command.
    pub request_id: String,
}

impl CommandResult {
    /// Create a success result.
    pub fn success(
        command_type: impl Into<String>,
        payload: impl Into<String>,
        request_id: impl Into<String>,
    ) -> Self {
        Self {
            status: CommandStatus::Success,
            command_type: command_type.into(),
            payload: payload.into(),
            error: String::new(),
            request_id: request_id.into(),
        }
    }

    /// Create a denied result (CU rejected authorization).
    pub fn denied(
        command_type: impl Into<String>,
        reason: impl Into<String>,
        request_id: impl Into<String>,
    ) -> Self {
        Self {
            status: CommandStatus::Denied,
            command_type: command_type.into(),
            payload: String::new(),
            error: reason.into(),
            request_id: request_id.into(),
        }
    }

    /// Create an error result (execution failure).
    pub fn error(
        command_type: impl Into<String>,
        error: impl Into<String>,
        request_id: impl Into<String>,
    ) -> Self {
        Self {
            status: CommandStatus::Error,
            command_type: command_type.into(),
            payload: String::new(),
            error: error.into(),
            request_id: request_id.into(),
        }
    }

    /// Write this result into a Tree as `result.*` entries.
    pub fn inject_into(&self, tree: &mut Tree) {
        tree.insert(
            "result.status".into(),
            self.status.as_str().as_bytes().to_vec(),
        );
        tree.insert(
            "result.command_type".into(),
            self.command_type.as_bytes().to_vec(),
        );
        tree.insert("result.payload".into(), self.payload.as_bytes().to_vec());
        tree.insert("result.error".into(), self.error.as_bytes().to_vec());
        tree.insert(
            "result.request_id".into(),
            self.request_id.as_bytes().to_vec(),
        );
    }

    /// Extract a result from a Tree's `result.*` entries.
    ///
    /// Returns `None` if `result.status` is absent (not a result cycle).
    pub fn extract_from(tree: &Tree) -> Option<Self> {
        let status_str = tree
            .get("result.status")
            .map(|v| String::from_utf8_lossy(v).into_owned())?;
        let status = CommandStatus::from_str(&status_str)?;

        let command_type = tree
            .get("result.command_type")
            .map(|v| String::from_utf8_lossy(v).into_owned())
            .unwrap_or_default();

        let payload = tree
            .get("result.payload")
            .map(|v| String::from_utf8_lossy(v).into_owned())
            .unwrap_or_default();

        let error = tree
            .get("result.error")
            .map(|v| String::from_utf8_lossy(v).into_owned())
            .unwrap_or_default();

        let request_id = tree
            .get("result.request_id")
            .map(|v| String::from_utf8_lossy(v).into_owned())
            .unwrap_or_default();

        Some(Self {
            status,
            command_type,
            payload,
            error,
            request_id,
        })
    }

    /// Check if a Tree contains a result (has `result.status`).
    pub fn is_result(tree: &Tree) -> bool {
        tree.contains_key("result.status")
    }
}

// ── Quad-level injection helper ──────────────────────────────────────────

/// Inject a ring command into a Quad's Tree, producing a new Quad.
///
/// Follows the same pattern as `inject_login_event()`: preserves
/// existing Tree entries, adds `command.*` entries, recomputes Root.
///
/// ## Usage
///
/// ```rust
/// use soma_som_ring::command::{RingCommand, inject_command};
/// use soma_som_core::quad::Quad;
///
/// let quad = Quad::from_strings("root", "ptr", soma_som_core::quad::Tree::new());
/// let cmd = RingCommand::new("user.create", "{}", "admin", "admin", "req-001");
/// let injected = inject_command(&quad, &cmd);
/// assert!(injected.tree.contains_key("command.type"));
/// ```
pub fn inject_command(quad: &Quad, command: &RingCommand) -> Quad {
    let mut tree = quad.tree.clone();
    command.inject_into(&mut tree);

    // Recompute root to reflect the new tree content
    let root = {
        let mut hasher = blake3::Hasher::new();
        hasher.update(b"command_injection");
        hasher.update(&quad.root);
        hasher.update(command.command_type.as_bytes());
        hasher.update(command.request_id.as_bytes());
        *hasher.finalize().as_bytes()
    };

    Quad::new(root, quad.pointer, tree)
}

// ── Schema Validation ──────────────────────────────────────────────────────
//
// Foundation-tier validation is structural only: required-field check + JSON
// type check. The `field.validation` S-FEEL expression on CommandSchema is
// retained as data but NOT evaluated here — evaluator choice is a §13.2
// implementation-variable and lives in the ring application via its registered
// validator (OPUS §13-agnostic).

/// Validate a command payload against a schema.
///
/// Returns `Ok(())` if no schema exists for this command type (open by default)
/// or if the payload conforms to the schema. Returns `Err` with a description
/// of all validation failures otherwise.
///
/// Validation happens at the injection boundary — before the command enters
/// the ring. Invalid payloads never cross the Two Doors threshold.
pub fn validate_payload(
    schema: &soma_som_core::extension::CommandSchema,
    payload: &str,
) -> Result<(), String> {
    // Empty payload with no required fields is valid
    if payload.is_empty() || payload == "{}" {
        let has_required = schema.fields.iter().any(|f| f.required);
        if has_required {
            let missing: Vec<&str> = schema
                .fields
                .iter()
                .filter(|f| f.required)
                .map(|f| f.name.as_str())
                .collect();
            return Err(format!(
                "payload validation failed for '{}': missing required fields: {}",
                schema.command_type,
                missing.join(", ")
            ));
        }
        return Ok(());
    }

    let value: serde_json::Value = serde_json::from_str(payload).map_err(|e| {
        format!(
            "payload validation failed for '{}': invalid JSON: {e}",
            schema.command_type
        )
    })?;

    let obj = match value.as_object() {
        Some(o) => o,
        None => {
            return Err(format!(
                "payload validation failed for '{}': payload must be a JSON object",
                schema.command_type
            ));
        }
    };

    let mut errors = Vec::new();

    for field in &schema.fields {
        match obj.get(&field.name) {
            None if field.required => {
                errors.push(format!("missing required field '{}'", field.name));
            }
            None => {} // optional absent — ok (FEEL validation skipped)
            Some(val) => {
                use soma_som_core::extension::SchemaFieldType;
                let type_ok = match field.field_type {
                    SchemaFieldType::String => val.is_string(),
                    SchemaFieldType::Number => val.is_number(),
                    SchemaFieldType::Boolean => val.is_boolean(),
                    SchemaFieldType::Object => val.is_object(),
                    SchemaFieldType::Array => val.is_array(),
                    // SchemaFieldType is #[non_exhaustive]: a future variant
                    // we do not yet know how to validate fails closed.
                    _ => false,
                };
                if !type_ok {
                    let actual = match val {
                        serde_json::Value::Null => "null",
                        serde_json::Value::Bool(_) => "boolean",
                        serde_json::Value::Number(_) => "number",
                        serde_json::Value::String(_) => "string",
                        serde_json::Value::Array(_) => "array",
                        serde_json::Value::Object(_) => "object",
                    };
                    errors.push(format!(
                        "field '{}' expected type '{}', got '{}'",
                        field.name, field.field_type, actual,
                    ));
                }
                // S-FEEL validation expression evaluation is a §13.2
                // implementation-variable (OPUS §13). The `field.validation`
                // expression stays on the schema as data; ring applications
                // evaluate it via their own registered validator.
            }
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(format!(
            "payload validation failed for '{}': {}",
            schema.command_type,
            errors.join("; ")
        ))
    }
}

// ── View envelope ────────────────────────────────────────────────────

/// Key prefix for all view-intent entries in FU.Data.
///
/// Disjoint from [`COMMAND_PREFIX`] and [`RESULT_PREFIX`] so a single Tree
/// may carry a view intent alongside a command or event without collision.
pub const VIEW_PREFIX: &str = "view.";

/// A ring view intent injected into FU.Data for mediated view projection.
///
/// `ViewIntent` is to views what [`RingCommand`] is to commands: the
/// input envelope that starts a ring cycle. A view cycle produces
/// projected output in SU (shape governed by C3's route and the
/// organ's AROUND extension).
///
/// The envelope is shorter than [`RingCommand`] because views have no
/// free-form parameters at this layer — everything needed to select
/// data comes from `view_id` (resolved via the `ViewRegistry` in
/// `soma-interface`) and GUARD's scope evaluation over `scope` +
/// `role_key`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ViewIntent {
    /// View identifier — e.g. `organ.mirror`, `term.fu.data.tree`,
    /// `ext.git.commit.viewer`. Resolves through `ViewRegistry`.
    pub view_id: String,

    /// GUARD scope the requestor is asking under. CU uses this to
    /// decide which projection slice is visible.
    pub scope: String,

    /// Role key of the requestor (application-defined label).
    ///
    /// CU uses this for authorization scope evaluation. Injected into
    /// the Tree as `view.requestor_role` by convention.
    pub role_key: String,

    /// Request correlation ID for tracing. Generated by the web layer,
    /// carried through the cycle.
    pub request_id: String,
}

impl ViewIntent {
    /// Create a new view intent.
    pub fn new(
        view_id: impl Into<String>,
        scope: impl Into<String>,
        role_key: impl Into<String>,
        request_id: impl Into<String>,
    ) -> Self {
        Self {
            view_id: view_id.into(),
            scope: scope.into(),
            role_key: role_key.into(),
            request_id: request_id.into(),
        }
    }

    /// Inject this view intent into a Tree as `view.*` entries.
    pub fn inject_into(&self, tree: &mut Tree) {
        tree.insert("view.id".into(), self.view_id.as_bytes().to_vec());
        tree.insert("view.scope".into(), self.scope.as_bytes().to_vec());
        tree.insert(
            "view.requestor_role".into(),
            self.role_key.as_bytes().to_vec(),
        );
        tree.insert(
            "view.request_id".into(),
            self.request_id.as_bytes().to_vec(),
        );
    }

    /// Extract a view intent from a Tree's `view.*` entries.
    ///
    /// Returns `None` if `view.id` is absent (not a view cycle).
    pub fn extract_from(tree: &Tree) -> Option<Self> {
        let view_id = tree
            .get("view.id")
            .map(|v| String::from_utf8_lossy(v).into_owned())?;

        let scope = tree
            .get("view.scope")
            .map(|v| String::from_utf8_lossy(v).into_owned())
            .unwrap_or_default();

        let role_key = tree
            .get("view.requestor_role")
            .map(|v| String::from_utf8_lossy(v).into_owned())
            .unwrap_or_default();

        let request_id = tree
            .get("view.request_id")
            .map(|v| String::from_utf8_lossy(v).into_owned())
            .unwrap_or_default();

        Some(Self {
            view_id,
            scope,
            role_key,
            request_id,
        })
    }

    /// Check if a Tree contains a view intent (has `view.id`).
    pub fn is_view_intent(tree: &Tree) -> bool {
        tree.contains_key("view.id")
    }
}

/// Inject a view intent into a Quad's Tree, producing a new Quad.
///
/// Mirrors [`inject_command`] — preserves existing Tree entries, adds
/// `view.*` entries, recomputes Root. Pointer is preserved.
///
/// ## Usage
///
/// ```rust
/// use soma_som_ring::command::{ViewIntent, inject_view_intent};
/// use soma_som_core::quad::Quad;
///
/// let quad = Quad::from_strings("root", "ptr", soma_som_core::quad::Tree::new());
/// let intent = ViewIntent::new("organ.mirror", "health", "admin", "req-001");
/// let injected = inject_view_intent(&quad, &intent);
/// assert!(injected.tree.contains_key("view.id"));
/// ```
pub fn inject_view_intent(quad: &Quad, intent: &ViewIntent) -> Quad {
    let mut tree = quad.tree.clone();
    intent.inject_into(&mut tree);

    let root = {
        let mut hasher = blake3::Hasher::new();
        hasher.update(b"view_intent_injection");
        hasher.update(&quad.root);
        hasher.update(intent.view_id.as_bytes());
        hasher.update(intent.request_id.as_bytes());
        *hasher.finalize().as_bytes()
    };

    Quad::new(root, quad.pointer, tree)
}

// ── Tests ────────────────────────────────────────────────────────────────

// inline: exercises module-private items via super::*
#[cfg(test)]
mod tests {
    use super::*;
    use soma_som_core::quad::Quad;

    // ── RingCommand construction ─────────────────────────────────────

    #[test]
    fn ring_command_new() {
        let cmd = RingCommand::new(
            "user.create",
            "{\"username\":\"alice\"}",
            "admin",
            "admin",
            "req-001",
        );
        assert_eq!(cmd.command_type, "user.create");
        assert_eq!(cmd.actor, "admin");
        assert_eq!(cmd.role_key, "admin");
        assert_eq!(cmd.request_id, "req-001");
    }

    // ── Tree injection / extraction roundtrip ────────────────────────

    #[test]
    fn command_inject_extract_roundtrip() {
        let cmd = RingCommand::new(
            "user.delete",
            "{\"username\":\"bob\"}",
            "admin",
            "admin",
            "req-002",
        );
        let mut tree = Tree::new();
        cmd.inject_into(&mut tree);

        let extracted = RingCommand::extract_from(&tree).expect("should extract");
        assert_eq!(extracted, cmd);
    }

    #[test]
    fn command_extract_returns_none_without_type() {
        let tree = Tree::new();
        assert!(RingCommand::extract_from(&tree).is_none());
    }

    #[test]
    fn command_is_command_detection() {
        let mut tree = Tree::new();
        assert!(!RingCommand::is_command(&tree));
        tree.insert("command.type".into(), b"user.list".to_vec());
        assert!(RingCommand::is_command(&tree));
    }

    // ── Quad-level injection ─────────────────────────────────────────

    #[test]
    fn inject_command_preserves_existing_tree() {
        let mut tree = Tree::new();
        tree.insert("existing.key".into(), b"value".to_vec());
        let quad = Quad::from_strings("root", "ptr", tree);

        let cmd = RingCommand::new("user.list", "{}", "admin", "admin", "req-003");
        let injected = inject_command(&quad, &cmd);

        assert_eq!(
            injected.tree.get("existing.key"),
            Some(&b"value".to_vec()),
            "existing keys must be preserved"
        );
        assert!(injected.tree.contains_key("command.type"));
    }

    #[test]
    fn inject_command_recomputes_root() {
        let quad = Quad::from_strings("root", "ptr", Tree::new());
        let cmd = RingCommand::new("user.create", "{}", "admin", "admin", "req-004");
        let injected = inject_command(&quad, &cmd);

        assert_ne!(
            injected.root, quad.root,
            "root must change after command injection"
        );
    }

    #[test]
    fn inject_command_different_commands_different_roots() {
        let quad = Quad::from_strings("root", "ptr", Tree::new());
        let cmd_a = RingCommand::new("user.create", "{}", "admin", "admin", "req-a");
        let cmd_b = RingCommand::new("user.delete", "{}", "admin", "admin", "req-b");

        let injected_a = inject_command(&quad, &cmd_a);
        let injected_b = inject_command(&quad, &cmd_b);

        assert_ne!(
            injected_a.root, injected_b.root,
            "different commands must produce different roots"
        );
    }

    #[test]
    fn inject_command_preserves_pointer() {
        let quad = Quad::from_strings("root", "ptr", Tree::new());
        let cmd = RingCommand::new("user.list", "{}", "admin", "admin", "req-005");
        let injected = inject_command(&quad, &cmd);

        assert_eq!(injected.pointer, quad.pointer, "pointer must be preserved");
    }

    // ── CommandResult construction ───────────────────────────────────

    #[test]
    fn result_success() {
        let r = CommandResult::success("user.create", "{\"username\":\"alice\"}", "req-001");
        assert_eq!(r.status, CommandStatus::Success);
        assert_eq!(r.command_type, "user.create");
        assert!(!r.payload.is_empty());
        assert!(r.error.is_empty());
    }

    #[test]
    fn result_denied() {
        let r = CommandResult::denied("user.delete", "insufficient privileges", "req-002");
        assert_eq!(r.status, CommandStatus::Denied);
        assert!(r.payload.is_empty());
        assert_eq!(r.error, "insufficient privileges");
    }

    #[test]
    fn result_error() {
        let r = CommandResult::error("user.create", "username already exists", "req-003");
        assert_eq!(r.status, CommandStatus::Error);
        assert_eq!(r.error, "username already exists");
    }

    // ── Result Tree injection / extraction roundtrip ─────────────────

    #[test]
    fn result_inject_extract_roundtrip() {
        let r = CommandResult::success("user.list", "[{\"username\":\"admin\"}]", "req-004");
        let mut tree = Tree::new();
        r.inject_into(&mut tree);

        let extracted = CommandResult::extract_from(&tree).expect("should extract");
        assert_eq!(extracted, r);
    }

    #[test]
    fn result_extract_returns_none_without_status() {
        let tree = Tree::new();
        assert!(CommandResult::extract_from(&tree).is_none());
    }

    #[test]
    fn result_is_result_detection() {
        let mut tree = Tree::new();
        assert!(!CommandResult::is_result(&tree));
        tree.insert("result.status".into(), b"success".to_vec());
        assert!(CommandResult::is_result(&tree));
    }

    #[test]
    fn result_denied_roundtrip() {
        let r = CommandResult::denied("user.delete", "not authorized", "req-005");
        let mut tree = Tree::new();
        r.inject_into(&mut tree);

        let extracted = CommandResult::extract_from(&tree).unwrap();
        assert_eq!(extracted.status, CommandStatus::Denied);
        assert_eq!(extracted.error, "not authorized");
    }

    #[test]
    fn result_error_roundtrip() {
        let r = CommandResult::error("user.create", "db write failed", "req-006");
        let mut tree = Tree::new();
        r.inject_into(&mut tree);

        let extracted = CommandResult::extract_from(&tree).unwrap();
        assert_eq!(extracted.status, CommandStatus::Error);
        assert_eq!(extracted.error, "db write failed");
    }

    // ── CommandStatus parsing ────────────────────────────────────────

    #[test]
    fn command_status_roundtrip() {
        for status in [
            CommandStatus::Success,
            CommandStatus::Denied,
            CommandStatus::Error,
        ] {
            let parsed = CommandStatus::from_str(status.as_str()).unwrap();
            assert_eq!(parsed, status);
        }
    }

    #[test]
    fn command_status_unknown_returns_none() {
        assert!(CommandStatus::from_str("unknown").is_none());
        assert!(CommandStatus::from_str("").is_none());
    }

    // ── Serde roundtrip ──────────────────────────────────────────────

    #[test]
    fn ring_command_serde_roundtrip() {
        let cmd = RingCommand::new(
            "user.create",
            "{\"username\":\"carol\"}",
            "admin",
            "admin",
            "req-007",
        );
        let json = serde_json::to_string(&cmd).unwrap();
        let decoded: RingCommand = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded, cmd);
    }

    #[test]
    fn command_result_serde_roundtrip() {
        let r = CommandResult::success("user.list", "[]", "req-008");
        let json = serde_json::to_string(&r).unwrap();
        let decoded: CommandResult = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded, r);
    }

    // ── Key namespace isolation ──────────────────────────────────────

    #[test]
    fn command_keys_use_command_prefix() {
        let cmd = RingCommand::new("user.create", "{}", "admin", "admin", "req-009");
        let mut tree = Tree::new();
        cmd.inject_into(&mut tree);

        for key in tree.keys() {
            assert!(
                key.starts_with(COMMAND_PREFIX),
                "command key '{key}' must start with '{COMMAND_PREFIX}'"
            );
        }
    }

    #[test]
    fn result_keys_use_result_prefix() {
        let r = CommandResult::success("user.create", "{}", "req-010");
        let mut tree = Tree::new();
        r.inject_into(&mut tree);

        for key in tree.keys() {
            assert!(
                key.starts_with(RESULT_PREFIX),
                "result key '{key}' must start with '{RESULT_PREFIX}'"
            );
        }
    }

    // ── Coexistence with event.* namespace ───────────────────────────

    #[test]
    fn command_and_event_namespaces_do_not_collide() {
        let mut tree = Tree::new();

        // Inject a login event
        tree.insert("event.type".into(), b"login_attempt".to_vec());
        tree.insert("event.source".into(), b"web".to_vec());

        // Inject a command
        let cmd = RingCommand::new("user.list", "{}", "admin", "admin", "req-011");
        cmd.inject_into(&mut tree);

        // Both coexist
        assert_eq!(tree.get("event.type"), Some(&b"login_attempt".to_vec()),);
        assert_eq!(tree.get("command.type"), Some(&b"user.list".to_vec()),);

        // Extraction works independently
        assert!(RingCommand::extract_from(&tree).is_some());
    }

    // ── Payload validation tests ────────────────────────────────────

    use soma_som_core::extension::{CommandSchema, SchemaField, SchemaFieldType};

    fn user_create_schema() -> CommandSchema {
        CommandSchema::new("user.create")
            .field(SchemaField::required("username", SchemaFieldType::String))
            .field(SchemaField::required("password", SchemaFieldType::String))
            .field(SchemaField::optional("role", SchemaFieldType::String))
    }

    #[test]
    fn validate_valid_payload() {
        let schema = user_create_schema();
        let payload = r#"{"username":"alice","password":"secret"}"#;
        assert!(super::validate_payload(&schema, payload).is_ok());
    }

    #[test]
    fn validate_valid_payload_with_extra_fields() {
        let schema = user_create_schema();
        let payload = r#"{"username":"alice","password":"secret","extra":"ignored"}"#;
        assert!(super::validate_payload(&schema, payload).is_ok());
    }

    #[test]
    fn validate_missing_required_field() {
        let schema = user_create_schema();
        let payload = r#"{"password":"secret"}"#;
        let err = super::validate_payload(&schema, payload).unwrap_err();
        assert!(err.contains("missing required field 'username'"));
    }

    #[test]
    fn validate_wrong_field_type() {
        let schema = CommandSchema::new("test.cmd")
            .field(SchemaField::required("timeout", SchemaFieldType::Number));
        let payload = r#"{"timeout":"not-a-number"}"#;
        let err = super::validate_payload(&schema, payload).unwrap_err();
        assert!(err.contains("expected type 'number'"));
        assert!(err.contains("got 'string'"));
    }

    #[test]
    fn validate_no_schema_fields_accepts_anything() {
        let schema = CommandSchema::new("user.list");
        assert!(super::validate_payload(&schema, "{}").is_ok());
        assert!(super::validate_payload(&schema, r#"{"any":"thing"}"#).is_ok());
    }

    #[test]
    fn validate_empty_payload_with_no_required_fields() {
        let schema = CommandSchema::new("test.cmd")
            .field(SchemaField::optional("debug", SchemaFieldType::Boolean));
        assert!(super::validate_payload(&schema, "{}").is_ok());
        assert!(super::validate_payload(&schema, "").is_ok());
    }

    #[test]
    fn validate_empty_payload_with_required_fields_fails() {
        let schema = user_create_schema();
        let err = super::validate_payload(&schema, "{}").unwrap_err();
        assert!(err.contains("missing required fields"));
    }

    #[test]
    fn validate_invalid_json_fails() {
        let schema = user_create_schema();
        let err = super::validate_payload(&schema, "not json").unwrap_err();
        assert!(err.contains("invalid JSON"));
    }

    #[test]
    fn validate_non_object_json_fails() {
        let schema = user_create_schema();
        let err = super::validate_payload(&schema, r#""just a string""#).unwrap_err();
        assert!(err.contains("must be a JSON object"));
    }

    #[test]
    fn validate_optional_field_type_checked_when_present() {
        let schema = CommandSchema::new("test.cmd")
            .field(SchemaField::optional("count", SchemaFieldType::Number));
        // Optional absent — ok.
        assert!(super::validate_payload(&schema, "{}").is_ok());
        // Optional present with correct type — ok.
        assert!(super::validate_payload(&schema, r#"{"count":42}"#).is_ok());
        // Optional present with wrong type — error.
        let err = super::validate_payload(&schema, r#"{"count":"nope"}"#).unwrap_err();
        assert!(err.contains("expected type 'number'"));
    }

    #[test]
    fn validate_all_field_types() {
        let schema = CommandSchema::new("test.types")
            .field(SchemaField::required("s", SchemaFieldType::String))
            .field(SchemaField::required("n", SchemaFieldType::Number))
            .field(SchemaField::required("b", SchemaFieldType::Boolean))
            .field(SchemaField::required("o", SchemaFieldType::Object))
            .field(SchemaField::required("a", SchemaFieldType::Array));

        let payload = r#"{"s":"x","n":1,"b":true,"o":{},"a":[]}"#;
        assert!(super::validate_payload(&schema, payload).is_ok());
    }

    // ── ViewIntent envelope ─────────────────────────────────────────

    #[test]
    fn view_intent_new() {
        let intent = ViewIntent::new("organ.mirror", "health", "admin", "req-001");
        assert_eq!(intent.view_id, "organ.mirror");
        assert_eq!(intent.scope, "health");
        assert_eq!(intent.role_key, "admin");
        assert_eq!(intent.request_id, "req-001");
    }

    #[test]
    fn view_intent_inject_extract_roundtrip() {
        let intent = ViewIntent::new(
            "term.fu.data.tree",
            "identity",
            "viewer",
            "req-002",
        );
        let mut tree = Tree::new();
        intent.inject_into(&mut tree);

        let extracted = ViewIntent::extract_from(&tree).expect("should extract");
        assert_eq!(extracted, intent);
    }

    #[test]
    fn view_intent_extract_returns_none_without_id() {
        let tree = Tree::new();
        assert!(ViewIntent::extract_from(&tree).is_none());
    }

    #[test]
    fn view_intent_is_view_intent_detection() {
        let mut tree = Tree::new();
        assert!(!ViewIntent::is_view_intent(&tree));
        tree.insert("view.id".into(), b"organ.mirror".to_vec());
        assert!(ViewIntent::is_view_intent(&tree));
    }

    #[test]
    fn inject_view_intent_preserves_existing_tree() {
        let mut tree = Tree::new();
        tree.insert("existing.key".into(), b"value".to_vec());
        let quad = Quad::from_strings("root", "ptr", tree);

        let intent = ViewIntent::new("organ.guard", "policy", "admin", "req-003");
        let injected = inject_view_intent(&quad, &intent);

        assert_eq!(
            injected.tree.get("existing.key"),
            Some(&b"value".to_vec()),
            "existing keys must be preserved"
        );
        assert!(injected.tree.contains_key("view.id"));
    }

    #[test]
    fn inject_view_intent_recomputes_root() {
        let quad = Quad::from_strings("root", "ptr", Tree::new());
        let intent = ViewIntent::new("organ.store", "data", "admin", "req-004");
        let injected = inject_view_intent(&quad, &intent);

        assert_ne!(
            injected.root, quad.root,
            "root must change after view intent injection"
        );
    }

    #[test]
    fn inject_view_intent_different_intents_different_roots() {
        let quad = Quad::from_strings("root", "ptr", Tree::new());
        let intent_a = ViewIntent::new("organ.mirror", "health", "admin", "req-a");
        let intent_b = ViewIntent::new("organ.guard", "policy", "admin", "req-b");

        let injected_a = inject_view_intent(&quad, &intent_a);
        let injected_b = inject_view_intent(&quad, &intent_b);

        assert_ne!(
            injected_a.root, injected_b.root,
            "different view intents must produce different roots"
        );
    }

    #[test]
    fn inject_view_intent_preserves_pointer() {
        let quad = Quad::from_strings("root", "ptr", Tree::new());
        let intent = ViewIntent::new("organ.wall", "perimeter", "admin", "req-005");
        let injected = inject_view_intent(&quad, &intent);
        assert_eq!(injected.pointer, quad.pointer, "pointer must be preserved");
    }

    #[test]
    fn view_intent_serde_roundtrip() {
        let intent = ViewIntent::new(
            "term.mu.data.tree",
            "observability",
            "operator",
            "req-006",
        );
        let json = serde_json::to_string(&intent).unwrap();
        let decoded: ViewIntent = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded, intent);
    }

    #[test]
    fn view_intent_keys_use_view_prefix() {
        let intent = ViewIntent::new("organ.mirror", "health", "admin", "req-007");
        let mut tree = Tree::new();
        intent.inject_into(&mut tree);

        for key in tree.keys() {
            assert!(
                key.starts_with(VIEW_PREFIX),
                "view key '{key}' must start with '{VIEW_PREFIX}'"
            );
        }
    }

    // ── Namespace disjointness: view / command / event / result ─────

    #[test]
    fn view_and_command_namespaces_do_not_collide() {
        let mut tree = Tree::new();

        // Inject a login event
        tree.insert("event.type".into(), b"login_attempt".to_vec());

        // Inject a command
        let cmd = RingCommand::new("user.list", "{}", "admin", "admin", "req-cmd");
        cmd.inject_into(&mut tree);

        // Inject a result (pretend OU has written back already)
        let r = CommandResult::success("user.list", "[]", "req-cmd");
        r.inject_into(&mut tree);

        // Now inject a view intent
        let intent = ViewIntent::new("organ.mirror", "health", "admin", "req-view");
        intent.inject_into(&mut tree);

        // All four envelope types coexist
        assert_eq!(tree.get("event.type"), Some(&b"login_attempt".to_vec()));
        assert_eq!(tree.get("command.type"), Some(&b"user.list".to_vec()));
        assert_eq!(tree.get("result.status"), Some(&b"success".to_vec()));
        assert_eq!(tree.get("view.id"), Some(&b"organ.mirror".to_vec()));

        // Each selector is-envelope function finds only its own envelope
        assert!(RingCommand::is_command(&tree));
        assert!(CommandResult::is_result(&tree));
        assert!(ViewIntent::is_view_intent(&tree));

        // Each extract function returns the correct envelope
        let xcmd = RingCommand::extract_from(&tree).expect("cmd");
        let xres = CommandResult::extract_from(&tree).expect("res");
        let xview = ViewIntent::extract_from(&tree).expect("view");

        assert_eq!(xcmd.command_type, "user.list");
        assert_eq!(xres.command_type, "user.list");
        assert_eq!(xview.view_id, "organ.mirror");

        // The three request_ids stay distinct
        assert_eq!(xcmd.request_id, "req-cmd");
        assert_eq!(xres.request_id, "req-cmd");
        assert_eq!(xview.request_id, "req-view");
    }

    #[test]
    fn view_intent_does_not_appear_as_command() {
        let mut tree = Tree::new();
        let intent = ViewIntent::new("organ.mirror", "health", "admin", "req-only-view");
        intent.inject_into(&mut tree);

        // Pure view tree — not a command, not a result
        assert!(!RingCommand::is_command(&tree));
        assert!(!CommandResult::is_result(&tree));
        assert!(ViewIntent::is_view_intent(&tree));

        assert!(RingCommand::extract_from(&tree).is_none());
        assert!(CommandResult::extract_from(&tree).is_none());
        assert!(ViewIntent::extract_from(&tree).is_some());
    }

    #[test]
    fn view_prefix_constant_matches_key_layout() {
        // Guards against VIEW_PREFIX drifting out of sync with inject_into().
        assert_eq!(VIEW_PREFIX, "view.");
        let intent = ViewIntent::new("organ.mirror", "s", "r", "i");
        let mut tree = Tree::new();
        intent.inject_into(&mut tree);

        for key in tree.keys() {
            assert!(
                key.starts_with(VIEW_PREFIX),
                "expected prefix '{VIEW_PREFIX}' on key '{key}'"
            );
        }
        // Disjoint from the other two prefixes defined in this module.
        assert_ne!(VIEW_PREFIX, COMMAND_PREFIX);
        assert_ne!(VIEW_PREFIX, RESULT_PREFIX);
    }
}