meerkat-contracts 0.6.21

Wire format contracts and generated surface schemas for Meerkat
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
//! Wire types for `comms/*`.
//!
//! The public wire owns its request/result contract and projects into the
//! core comms command envelope only after serde has closed over intent,
//! params, and result shape.
//!
//! The `comms/send` command payload remains flat:
//! `{ "session_id": "...", "kind": "<variant>", ... }`.

pub use meerkat_core::comms::{
    CommsCommandError, InputSource, InputStreamMode, PeerAddress, PeerCapabilitySet,
    PeerDirectoryEntry, PeerDirectoryListing, PeerDirectorySource, PeerId, PeerLifecycleKind,
    PeerName, PeerReachability, PeerReachabilityReason, PeerSendability, PeerTransport,
};
pub use meerkat_core::interaction::ResponseStatus;
pub use meerkat_core::types::HandlingMode;

use super::supervisor_bridge::{
    BridgeCommand, BridgePeerSpec, BridgeReply, SUPERVISOR_BRIDGE_INTENT,
};
use serde::{Deserialize, Serialize};

/// Typed params for one-way peer lifecycle notifications.
///
/// This is the public wire projection of the topology-update payloads that
/// used to travel as arbitrary JSON. `peer_spec` is the canonical typed
/// identity when the sender has it; `peer`, `role`, and `description` remain
/// inert presentation metadata for older projections.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CommsPeerLifecycleParams {
    pub peer: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub peer_spec: Option<BridgePeerSpec>,
}

impl CommsPeerLifecycleParams {
    fn into_json_value(self) -> Result<serde_json::Value, serde_json::Error> {
        serde_json::to_value(self)
    }
}

/// Closed public request-intent contract for `peer_request`.
///
/// Unknown strings fail during deserialization and cannot fall through to a
/// local match/default path.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum CommsPeerRequestIntent {
    #[serde(rename = "supervisor.bridge")]
    SupervisorBridge,
    #[serde(rename = "checksum_token")]
    ChecksumToken,
}

impl CommsPeerRequestIntent {
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::SupervisorBridge => SUPERVISOR_BRIDGE_INTENT,
            Self::ChecksumToken => "checksum_token",
        }
    }
}

/// Typed params for the actionable checksum-token request used by peer
/// request/response terminal-flow fixtures.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CommsChecksumTokenParams {
    pub subject: String,
}

/// Closed discriminator carried in [`CommsChecksumTokenResult`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum CommsChecksumTokenResultIntent {
    #[serde(rename = "checksum_token")]
    ChecksumToken,
}

/// Typed result for a checksum-token peer response.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CommsChecksumTokenResult {
    pub request_intent: CommsChecksumTokenResultIntent,
    pub request_subject: String,
    pub token: String,
}

/// Typed params for public `peer_request`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(untagged)]
pub enum CommsPeerRequestParams {
    SupervisorBridge(Box<BridgeCommand>),
    ChecksumToken(CommsChecksumTokenParams),
}

impl CommsPeerRequestParams {
    fn matches_intent(&self, intent: &CommsPeerRequestIntent) -> bool {
        matches!(
            (intent, self),
            (
                CommsPeerRequestIntent::SupervisorBridge,
                Self::SupervisorBridge(_)
            ) | (
                CommsPeerRequestIntent::ChecksumToken,
                Self::ChecksumToken(_)
            )
        )
    }

    fn into_json_value(self) -> Result<serde_json::Value, serde_json::Error> {
        match self {
            Self::SupervisorBridge(params) => serde_json::to_value(params),
            Self::ChecksumToken(params) => serde_json::to_value(params),
        }
    }
}

/// Typed result payload for public `peer_response`.
///
/// Compatibility JSON is intentionally not accepted here. Callers that include
/// a `result` field must provide a typed bridge reply shape.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(untagged)]
pub enum CommsPeerResponseResult {
    SupervisorBridge(BridgeReply),
    ChecksumToken(CommsChecksumTokenResult),
}

impl CommsPeerResponseResult {
    fn into_json_value(self) -> Result<serde_json::Value, serde_json::Error> {
        match self {
            Self::SupervisorBridge(result) => serde_json::to_value(result),
            Self::ChecksumToken(result) => serde_json::to_value(result),
        }
    }
}

impl From<BridgeReply> for CommsPeerResponseResult {
    fn from(reply: BridgeReply) -> Self {
        Self::SupervisorBridge(reply)
    }
}

/// Failure projecting the typed public comms contract into the core
/// compatibility command envelope.
#[derive(Debug, thiserror::Error)]
pub enum CommsCommandProjectionError {
    #[error(transparent)]
    Command(#[from] CommsCommandError),
    #[error("peer_request params do not match typed intent {intent}")]
    IntentParamsMismatch { intent: &'static str },
    #[error("failed to project typed comms {field} to compatibility JSON: {source}")]
    CompatibilityJson {
        field: &'static str,
        #[source]
        source: serde_json::Error,
    },
}

impl CommsCommandProjectionError {
    fn compatibility_json(field: &'static str, source: serde_json::Error) -> Self {
        Self::CompatibilityJson { field, source }
    }
}

/// Request command carried inside public `comms/send` surfaces.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum CommsCommandRequest {
    Input {
        body: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        blocks: Option<Vec<meerkat_core::ContentBlock>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        source: Option<InputSource>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        stream: Option<InputStreamMode>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        handling_mode: Option<HandlingMode>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        allow_self_session: Option<bool>,
    },
    PeerMessage {
        to: PeerId,
        body: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        blocks: Option<Vec<meerkat_core::ContentBlock>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        handling_mode: Option<HandlingMode>,
    },
    PeerLifecycle {
        to: PeerId,
        lifecycle_kind: PeerLifecycleKind,
        params: CommsPeerLifecycleParams,
    },
    PeerRequest {
        to: PeerId,
        intent: CommsPeerRequestIntent,
        params: CommsPeerRequestParams,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        blocks: Option<Vec<meerkat_core::ContentBlock>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        handling_mode: Option<HandlingMode>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        stream: Option<InputStreamMode>,
    },
    PeerResponse {
        to: PeerId,
        in_reply_to: meerkat_core::interaction::InteractionId,
        status: ResponseStatus,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        result: Option<CommsPeerResponseResult>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        blocks: Option<Vec<meerkat_core::ContentBlock>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        handling_mode: Option<HandlingMode>,
    },
}

impl CommsCommandRequest {
    pub fn peer_label(&self) -> Option<String> {
        match self {
            Self::Input { .. } => None,
            Self::PeerMessage { to, .. }
            | Self::PeerLifecycle { to, .. }
            | Self::PeerRequest { to, .. }
            | Self::PeerResponse { to, .. } => Some(to.to_string()),
        }
    }

    pub fn into_core_request(
        self,
    ) -> Result<meerkat_core::comms::CommsCommandRequest, CommsCommandProjectionError> {
        Ok(match self {
            Self::Input {
                body,
                blocks,
                source,
                stream,
                handling_mode,
                allow_self_session,
            } => meerkat_core::comms::CommsCommandRequest::Input {
                body,
                blocks,
                source,
                stream,
                handling_mode,
                allow_self_session,
            },
            Self::PeerMessage {
                to,
                body,
                blocks,
                handling_mode,
            } => meerkat_core::comms::CommsCommandRequest::PeerMessage {
                to,
                body,
                blocks,
                handling_mode,
            },
            Self::PeerLifecycle {
                to,
                lifecycle_kind,
                params,
            } => meerkat_core::comms::CommsCommandRequest::PeerLifecycle {
                to,
                lifecycle_kind,
                params: params.into_json_value().map_err(|source| {
                    CommsCommandProjectionError::compatibility_json("peer_lifecycle.params", source)
                })?,
            },
            Self::PeerRequest {
                to,
                intent,
                params,
                blocks,
                handling_mode,
                stream,
            } => {
                if !params.matches_intent(&intent) {
                    return Err(CommsCommandProjectionError::IntentParamsMismatch {
                        intent: intent.as_str(),
                    });
                }
                meerkat_core::comms::CommsCommandRequest::PeerRequest {
                    to,
                    intent: intent.as_str().to_string(),
                    params: params.into_json_value().map_err(|source| {
                        CommsCommandProjectionError::compatibility_json(
                            "peer_request.params",
                            source,
                        )
                    })?,
                    blocks,
                    handling_mode,
                    stream,
                }
            }
            Self::PeerResponse {
                to,
                in_reply_to,
                status,
                result,
                blocks,
                handling_mode,
            } => meerkat_core::comms::CommsCommandRequest::PeerResponse {
                to,
                in_reply_to,
                status,
                result: match result {
                    Some(result) => result.into_json_value().map_err(|source| {
                        CommsCommandProjectionError::compatibility_json(
                            "peer_response.result",
                            source,
                        )
                    })?,
                    None => serde_json::Value::Null,
                },
                blocks,
                handling_mode,
            },
        })
    }

    pub fn into_command(
        self,
        session_id: &meerkat_core::types::SessionId,
    ) -> Result<meerkat_core::comms::CommsCommand, CommsCommandProjectionError> {
        Ok(self.into_core_request()?.into_command(session_id)?)
    }
}

/// Request payload for `comms/send`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum CommsSendParams {
    Input {
        session_id: String,
        body: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        blocks: Option<Vec<meerkat_core::ContentBlock>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        source: Option<InputSource>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        stream: Option<InputStreamMode>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        handling_mode: Option<HandlingMode>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        allow_self_session: Option<bool>,
    },
    PeerMessage {
        session_id: String,
        to: PeerId,
        body: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        blocks: Option<Vec<meerkat_core::ContentBlock>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        handling_mode: Option<HandlingMode>,
    },
    PeerLifecycle {
        session_id: String,
        to: PeerId,
        lifecycle_kind: PeerLifecycleKind,
        params: CommsPeerLifecycleParams,
    },
    PeerRequest {
        session_id: String,
        to: PeerId,
        intent: CommsPeerRequestIntent,
        params: CommsPeerRequestParams,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        blocks: Option<Vec<meerkat_core::ContentBlock>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        handling_mode: Option<HandlingMode>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        stream: Option<InputStreamMode>,
    },
    PeerResponse {
        session_id: String,
        to: PeerId,
        in_reply_to: meerkat_core::interaction::InteractionId,
        status: ResponseStatus,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        result: Option<CommsPeerResponseResult>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        blocks: Option<Vec<meerkat_core::ContentBlock>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        handling_mode: Option<HandlingMode>,
    },
}

impl CommsSendParams {
    pub fn session_id(&self) -> &str {
        match self {
            Self::Input { session_id, .. }
            | Self::PeerMessage { session_id, .. }
            | Self::PeerLifecycle { session_id, .. }
            | Self::PeerRequest { session_id, .. }
            | Self::PeerResponse { session_id, .. } => session_id,
        }
    }

    /// Recipient peer id for error normalization, if the command targets one.
    pub fn peer_label(&self) -> Option<String> {
        match self {
            Self::Input { .. } => None,
            Self::PeerMessage { to, .. }
            | Self::PeerLifecycle { to, .. }
            | Self::PeerRequest { to, .. }
            | Self::PeerResponse { to, .. } => Some(to.to_string()),
        }
    }

    pub fn into_command(self) -> CommsCommandRequest {
        match self {
            Self::Input {
                body,
                blocks,
                source,
                stream,
                handling_mode,
                allow_self_session,
                ..
            } => CommsCommandRequest::Input {
                body,
                blocks,
                source,
                stream,
                handling_mode,
                allow_self_session,
            },
            Self::PeerMessage {
                to,
                body,
                blocks,
                handling_mode,
                ..
            } => CommsCommandRequest::PeerMessage {
                to,
                body,
                blocks,
                handling_mode,
            },
            Self::PeerLifecycle {
                to,
                lifecycle_kind,
                params,
                ..
            } => CommsCommandRequest::PeerLifecycle {
                to,
                lifecycle_kind,
                params,
            },
            Self::PeerRequest {
                to,
                intent,
                params,
                blocks,
                handling_mode,
                stream,
                ..
            } => CommsCommandRequest::PeerRequest {
                to,
                intent,
                params,
                blocks,
                handling_mode,
                stream,
            },
            Self::PeerResponse {
                to,
                in_reply_to,
                status,
                result,
                blocks,
                handling_mode,
                ..
            } => CommsCommandRequest::PeerResponse {
                to,
                in_reply_to,
                status,
                result,
                blocks,
                handling_mode,
            },
        }
    }
}

/// Request payload for `comms/peers`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CommsPeersParams {
    pub session_id: String,
}

/// Response payload for `comms/send`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum CommsSendResult {
    InputAccepted {
        interaction_id: String,
        stream_reserved: bool,
    },
    PeerMessageSent {
        envelope_id: String,
        acked: bool,
    },
    PeerLifecycleSent {
        envelope_id: String,
    },
    PeerRequestSent {
        envelope_id: String,
        interaction_id: String,
        request_id: String,
        stream_reserved: bool,
    },
    PeerResponseSent {
        envelope_id: String,
        in_reply_to: String,
    },
}

impl From<meerkat_core::comms::SendReceipt> for CommsSendResult {
    fn from(receipt: meerkat_core::comms::SendReceipt) -> Self {
        match receipt {
            meerkat_core::comms::SendReceipt::InputAccepted {
                interaction_id,
                stream_reserved,
            } => Self::InputAccepted {
                interaction_id: interaction_id.0.to_string(),
                stream_reserved,
            },
            meerkat_core::comms::SendReceipt::PeerMessageSent { envelope_id, acked } => {
                Self::PeerMessageSent {
                    envelope_id: envelope_id.to_string(),
                    acked,
                }
            }
            meerkat_core::comms::SendReceipt::PeerLifecycleSent { envelope_id } => {
                Self::PeerLifecycleSent {
                    envelope_id: envelope_id.to_string(),
                }
            }
            meerkat_core::comms::SendReceipt::PeerRequestSent {
                envelope_id,
                interaction_id,
                stream_reserved,
            } => {
                let envelope_id = envelope_id.to_string();
                Self::PeerRequestSent {
                    request_id: envelope_id.clone(),
                    envelope_id,
                    interaction_id: interaction_id.0.to_string(),
                    stream_reserved,
                }
            }
            meerkat_core::comms::SendReceipt::PeerResponseSent {
                envelope_id,
                in_reply_to,
            } => Self::PeerResponseSent {
                envelope_id: envelope_id.to_string(),
                in_reply_to: in_reply_to.0.to_string(),
            },
        }
    }
}

pub type CommsPeerEntry = PeerDirectoryEntry;

/// Response payload for `comms/peers`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CommsPeersResult {
    pub peers: Vec<PeerDirectoryEntry>,
}

impl CommsPeersResult {
    pub fn from_entries(entries: &[meerkat_core::comms::PeerDirectoryEntry]) -> Self {
        Self {
            peers: entries.to_vec(),
        }
    }
}

impl From<PeerDirectoryListing> for CommsPeersResult {
    fn from(listing: PeerDirectoryListing) -> Self {
        Self {
            peers: listing.peers,
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;
    use serde_json::json;

    fn peer_id() -> PeerId {
        PeerId::new()
    }

    fn bridge_peer_spec() -> serde_json::Value {
        let pubkey = [7u8; 32];
        json!({
            "name": "supervisor",
            "peer_id": PeerId::from_ed25519_pubkey(&pubkey).to_string(),
            "address": "inproc://supervisor",
            "pubkey": pubkey,
        })
    }

    fn supervisor_bridge_params() -> serde_json::Value {
        json!({
            "command": "observe_member",
            "supervisor": bridge_peer_spec(),
            "epoch": 1,
            "protocol_version": 2,
        })
    }

    #[test]
    fn peer_request_unknown_intent_fails_closed() {
        let err = serde_json::from_value::<CommsSendParams>(json!({
            "session_id": "sid_1",
            "kind": "peer_request",
            "to": peer_id().to_string(),
            "intent": "local.default",
            "params": {}
        }))
        .expect_err("unknown public comms intent must fail at serde boundary");

        let message = err.to_string();
        assert!(
            message.contains("local.default") || message.contains("variant"),
            "error should mention the rejected intent, got: {message}"
        );
    }

    #[test]
    fn peer_request_malformed_params_cannot_be_typed_success() {
        let err = serde_json::from_value::<CommsSendParams>(json!({
            "session_id": "sid_1",
            "kind": "peer_request",
            "to": peer_id().to_string(),
            "intent": "supervisor.bridge",
            "params": "not-an-object"
        }))
        .expect_err("malformed supervisor bridge params must not deserialize");

        let message = err.to_string();
        assert!(
            message.contains("invalid type")
                || message.contains("params")
                || message.contains("did not match any variant"),
            "expected typed params error, got: {message}"
        );
    }

    #[test]
    fn peer_response_malformed_result_cannot_be_typed_success() {
        let err = serde_json::from_value::<CommsSendParams>(json!({
            "session_id": "sid_1",
            "kind": "peer_response",
            "to": peer_id().to_string(),
            "in_reply_to": uuid::Uuid::new_v4().to_string(),
            "status": "completed",
            "result": {
                "result": "ack",
                "ok": "yes"
            }
        }))
        .expect_err("malformed typed result must not deserialize");

        let message = err.to_string();
        assert!(
            message.contains("ok")
                || message.contains("invalid type")
                || message.contains("did not match any variant"),
            "expected typed result error, got: {message}"
        );
    }

    #[test]
    fn comms_send_result_unknown_field_fails_closed() {
        let err = serde_json::from_value::<CommsSendResult>(json!({
            "kind": "peer_request_sent",
            "envelope_id": uuid::Uuid::new_v4().to_string(),
            "interaction_id": uuid::Uuid::new_v4().to_string(),
            "request_id": uuid::Uuid::new_v4().to_string(),
            "stream_reserved": true,
            "extra_behavior": true
        }))
        .expect_err("unknown result fields must fail at serde boundary");

        let message = err.to_string();
        assert!(
            message.contains("extra_behavior") || message.contains("unknown field"),
            "expected unknown result field error, got: {message}"
        );
    }

    #[test]
    fn public_peer_request_projects_typed_intent_and_params_to_core() {
        let params = serde_json::from_value::<CommsSendParams>(json!({
            "session_id": "sid_1",
            "kind": "peer_request",
            "to": peer_id().to_string(),
            "intent": "supervisor.bridge",
            "params": supervisor_bridge_params(),
            "handling_mode": "queue",
            "stream": "reserve_interaction"
        }))
        .expect("typed supervisor bridge request should deserialize");

        let session_id = meerkat_core::types::SessionId::new();
        let command = params
            .into_command()
            .into_command(&session_id)
            .expect("typed comms request should project to core command");

        let meerkat_core::comms::CommsCommand::PeerRequest {
            intent,
            params,
            handling_mode,
            stream,
            ..
        } = command
        else {
            panic!("expected core peer request");
        };

        assert_eq!(intent, SUPERVISOR_BRIDGE_INTENT);
        assert_eq!(params["command"], "observe_member");
        assert_eq!(handling_mode, HandlingMode::Queue);
        assert_eq!(stream, InputStreamMode::ReserveInteraction);
    }

    #[test]
    fn public_checksum_token_request_projects_typed_intent_and_params_to_core() {
        let params = serde_json::from_value::<CommsSendParams>(json!({
            "session_id": "sid_1",
            "kind": "peer_request",
            "to": peer_id().to_string(),
            "intent": "checksum_token",
            "params": {
                "subject": "alpha beta gamma"
            },
            "handling_mode": "steer",
            "stream": "reserve_interaction"
        }))
        .expect("typed checksum token request should deserialize");

        let session_id = meerkat_core::types::SessionId::new();
        let command = params
            .into_command()
            .into_command(&session_id)
            .expect("typed checksum token request should project to core command");

        let meerkat_core::comms::CommsCommand::PeerRequest {
            intent,
            params,
            handling_mode,
            stream,
            ..
        } = command
        else {
            panic!("expected core peer request");
        };

        assert_eq!(intent, "checksum_token");
        assert_eq!(params["subject"], "alpha beta gamma");
        assert_eq!(handling_mode, HandlingMode::Steer);
        assert_eq!(stream, InputStreamMode::ReserveInteraction);
    }

    #[test]
    fn public_peer_request_rejects_intent_params_mismatch_before_dispatch() {
        let params = serde_json::from_value::<CommsSendParams>(json!({
            "session_id": "sid_1",
            "kind": "peer_request",
            "to": peer_id().to_string(),
            "intent": "checksum_token",
            "params": supervisor_bridge_params()
        }))
        .expect("mismatched typed params can deserialize but must not project");

        let session_id = meerkat_core::types::SessionId::new();
        let err = params
            .into_command()
            .into_command(&session_id)
            .expect_err("intent/params mismatch must not become a core command");

        assert!(
            err.to_string().contains("checksum_token"),
            "expected mismatch error to name intent, got: {err}"
        );
    }

    #[test]
    fn public_peer_response_result_projects_typed_bridge_reply_to_core() {
        let params = serde_json::from_value::<CommsSendParams>(json!({
            "session_id": "sid_1",
            "kind": "peer_response",
            "to": peer_id().to_string(),
            "in_reply_to": uuid::Uuid::new_v4().to_string(),
            "status": "completed",
            "result": {
                "result": "ack",
                "ok": true
            }
        }))
        .expect("typed bridge reply should deserialize");

        let session_id = meerkat_core::types::SessionId::new();
        let command = params
            .into_command()
            .into_command(&session_id)
            .expect("typed comms response should project to core command");

        let meerkat_core::comms::CommsCommand::PeerResponse { result, .. } = command else {
            panic!("expected core peer response");
        };

        assert_eq!(result["result"], "ack");
        assert_eq!(result["ok"], true);
    }

    #[test]
    fn public_peer_response_result_projects_typed_checksum_token_to_core() {
        let params = serde_json::from_value::<CommsSendParams>(json!({
            "session_id": "sid_1",
            "kind": "peer_response",
            "to": peer_id().to_string(),
            "in_reply_to": uuid::Uuid::new_v4().to_string(),
            "status": "completed",
            "result": {
                "request_intent": "checksum_token",
                "request_subject": "alpha beta gamma",
                "token": "birch seventeen"
            }
        }))
        .expect("typed checksum token reply should deserialize");

        let session_id = meerkat_core::types::SessionId::new();
        let command = params
            .into_command()
            .into_command(&session_id)
            .expect("typed checksum token reply should project to core command");

        let meerkat_core::comms::CommsCommand::PeerResponse { result, .. } = command else {
            panic!("expected core peer response");
        };

        assert_eq!(result["request_intent"], "checksum_token");
        assert_eq!(result["request_subject"], "alpha beta gamma");
        assert_eq!(result["token"], "birch seventeen");
    }

    #[test]
    fn public_peer_response_result_rejects_checksum_token_without_subject() {
        serde_json::from_value::<CommsSendParams>(json!({
            "session_id": "sid_1",
            "kind": "peer_response",
            "to": peer_id().to_string(),
            "in_reply_to": uuid::Uuid::new_v4().to_string(),
            "status": "completed",
            "result": {
                "request_intent": "checksum_token",
                "token": "birch seventeen"
            }
        }))
        .expect_err("checksum token replies must carry the request subject discriminator");
    }
}