cbcl-core 0.3.1

CBCL pure core: types, verification, and serialization
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
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
//! Message types and core performatives.
//!
//! Mirrors `Message.lean` from the Lean 4 proof library.

#![forbid(unsafe_code)]

use crate::protocol::BEGIN_KEYWORD;
use crate::sexpr::{Atom, SExpr};
use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;

/// Causal predecessor reference for a message (REQ-202).
///
/// Encodes the `:caused-by` keyword parameter:
/// - `Begin` — this message starts a new causal chain (`:caused-by "begin"`)
/// - `Single(hash)` — single predecessor (`:caused-by <hash>`)
/// - `Multiple(hashes)` — multiple predecessors (`:caused-by (<h1> <h2> ...)`)
///
/// For the `Multiple` variant, hashes are stored in canonical (sorted) order
/// to ensure deterministic hashing.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CausedBy {
    /// This message begins a new causal chain.
    Begin,
    /// Single causal predecessor, identified by content hash.
    Single(String),
    /// Multiple causal predecessors, sorted lexicographically for canonical ordering.
    Multiple(Vec<String>),
}

/// The 8 core performatives (REQ-010).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CorePerformative {
    Tell,
    Ask,
    Reply,
    Error,
    Ok,
    Cancel,
    Hello,
    Bye,
}

impl CorePerformative {
    /// Returns the string name of this core performative.
    pub fn as_str(&self) -> &'static str {
        match self {
            CorePerformative::Tell => "tell",
            CorePerformative::Ask => "ask",
            CorePerformative::Reply => "reply",
            CorePerformative::Error => "error",
            CorePerformative::Ok => "ok",
            CorePerformative::Cancel => "cancel",
            CorePerformative::Hello => "hello",
            CorePerformative::Bye => "bye",
        }
    }

    /// Parse a string into a core performative, if valid.
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "tell" => Some(CorePerformative::Tell),
            "ask" => Some(CorePerformative::Ask),
            "reply" => Some(CorePerformative::Reply),
            "error" => Some(CorePerformative::Error),
            "ok" => Some(CorePerformative::Ok),
            "cancel" => Some(CorePerformative::Cancel),
            "hello" => Some(CorePerformative::Hello),
            "bye" => Some(CorePerformative::Bye),
            _ => None,
        }
    }
}

/// Core performative names (REQ-014).
pub const CORE_PERFORMATIVE_NAMES: &[&str] = &[
    "tell", "ask", "reply", "error", "ok", "cancel", "hello", "bye",
];

/// Check if a string is a core performative name (REQ-014).
pub fn is_core_performative_name(s: &str) -> bool {
    CORE_PERFORMATIVE_NAMES.contains(&s)
}

/// Either a core or custom performative (REQ-011).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Performative {
    Core(CorePerformative),
    Custom(String),
}

impl Performative {
    /// Returns the string name of this performative.
    pub fn name(&self) -> &str {
        match self {
            Performative::Core(c) => c.as_str(),
            Performative::Custom(s) => s.as_str(),
        }
    }

    /// Returns true if this is a core performative.
    pub fn is_core(&self) -> bool {
        matches!(self, Performative::Core(_))
    }
}

/// Recipient position of a Simple message (SPEC-014 REQ-622).
///
/// A bare `@key` symbol is a single recipient (the pre-SPEC-014 form,
/// byte-identical on re-serialisation); a non-empty list of `@key` symbols
/// is a multicast, serialised in canonical (sorted) order. A performative
/// whose `:to` annotation is the empty set simply carries no recipient
/// position.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Recipients {
    /// Single recipient: `(perf @r …)`.
    One(String),
    /// Multicast: `(perf (@r1 @r2) …)`; canonical order via `BTreeSet`.
    Set(alloc::collections::BTreeSet<String>),
}

impl Recipients {
    /// The single recipient, if this is the `One` form.
    pub fn as_single(&self) -> Option<&str> {
        match self {
            Recipients::One(r) => Some(r.as_str()),
            Recipients::Set(_) => None,
        }
    }

    /// All recipients as a normalized sorted set.
    pub fn as_set(&self) -> alloc::collections::BTreeSet<&str> {
        match self {
            Recipients::One(r) => {
                let mut s = alloc::collections::BTreeSet::new();
                s.insert(r.as_str());
                s
            }
            Recipients::Set(rs) => rs.iter().map(|r| r.as_str()).collect(),
        }
    }
}

impl From<String> for Recipients {
    fn from(r: String) -> Self {
        Recipients::One(r)
    }
}

impl From<&str> for Recipients {
    fn from(r: &str) -> Self {
        Recipients::One(String::from(r))
    }
}

/// Message type classification (REQ-012).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum MessageType {
    Simple,
    Meta,
    Dialect,
    Wrapped,
}

/// Wrapper type for wrapped messages (REQ-012).
///
/// Four wrapper forms: `envelope`, `signed`, `with-limits`, and the
/// cast-bearing `with-roles` thread root (SPEC-014 REQ-625).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum WrapperType {
    Envelope,
    Signed,
    WithLimits,
    /// `(with-roles (<bindings>) <signed-message>)` — the cast nomination
    /// wrapper at a thread's causal root (SPEC-014 REQ-611/625, CON-601).
    /// The bindings list travels in `params`; the inner signed message is
    /// carried unchanged.
    WithRoles,
}

impl WrapperType {
    /// Returns the canonical string name of this wrapper type.
    pub fn as_str(&self) -> &'static str {
        match self {
            WrapperType::Envelope => "envelope",
            WrapperType::Signed => "signed",
            WrapperType::WithLimits => "with-limits",
            WrapperType::WithRoles => "with-roles",
        }
    }

    /// Parse a string into a wrapper type, if valid.
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "envelope" => Some(WrapperType::Envelope),
            "signed" => Some(WrapperType::Signed),
            "with-limits" => Some(WrapperType::WithLimits),
            "with-roles" => Some(WrapperType::WithRoles),
            _ => None,
        }
    }
}

/// A CBCL message (REQ-013).
///
/// Four variants matching the CBCL grammar:
/// - `Simple`: `(performative [recipient] content [:key val ...])`
/// - `Meta`: `(meta <operation>)`
/// - `Dialect`: `(lang <dialect-name> <inner-message>)`
/// - `Wrapped`: `(envelope|signed|with-limits <params...> <inner-message>)`
///
/// Mirrors `CBCL.Message` in `Message.lean:41–47` and
/// `CBCL.MessageType` in `Message.lean:33–37`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Message {
    /// Simple message: `(performative [recipient] content [:key val ...])`
    Simple {
        performative: Performative,
        recipient: Option<Recipients>,
        content: SExpr,
        params: Vec<SExpr>,
        thread: Option<String>,
        sender: Option<String>,
        caused_by: Option<CausedBy>,
    },
    /// Meta message: `(meta <dialect_def>)`
    Meta { dialect_def: SExpr },
    /// Dialect-scoped message: `(lang <dialect_name> <inner>)`
    Dialect {
        dialect_name: String,
        inner: Box<Message>,
    },
    /// Wrapped message: `(envelope|signed|with-limits <params...> <content>)`
    Wrapped {
        wrapper: WrapperType,
        params: Vec<SExpr>,
        content: Box<Message>,
    },
}

// ---------------------------------------------------------------------------
// Typed extraction methods
// ---------------------------------------------------------------------------

impl Message {
    /// Recognise a message as [`TryFrom<&SExpr>`] does, except that a custom
    /// performative outside a `(lang …)` wrapper is accepted as a bare
    /// `Performative::Custom` instead of being refused under the scoping rule.
    ///
    /// For hosts that dispatch such a frame by its head name themselves and
    /// accept only the names they know — the chat hub's control plane
    /// (`adddialect`, `fetchdialect`, `addagent`, …), which its lax parser
    /// gates with a performative allow-list. Content messages go through
    /// `TryFrom`, where the scoping rule stands: nothing in a bare custom head
    /// says which dialect defines it.
    pub fn parse_lax(sexpr: &SExpr) -> Result<Self, MessageParseError> {
        parse_message_scoped(sexpr, LangScope::Lax)
    }

    /// Returns the message type classification.
    pub fn message_type(&self) -> MessageType {
        match self {
            Message::Simple { .. } => MessageType::Simple,
            Message::Meta { .. } => MessageType::Meta,
            Message::Dialect { .. } => MessageType::Dialect,
            Message::Wrapped { .. } => MessageType::Wrapped,
        }
    }

    /// Returns the performative if this is a Simple message.
    pub fn performative(&self) -> Option<&Performative> {
        match self {
            Message::Simple { performative, .. } => Some(performative),
            _ => None,
        }
    }

    /// Returns the recipient if this is a Simple message with exactly one.
    pub fn recipient(&self) -> Option<&str> {
        match self {
            Message::Simple {
                recipient: Some(r), ..
            } => r.as_single(),
            _ => None,
        }
    }

    /// Canonical signed-envelope audience, retaining the `@` sigil.
    /// Descends wrappers to the act. An outermost envelope routes a non-empty
    /// recipient position through its single symbol `:to` (cbcl-bus SPEC-100
    /// CON-009). Recipient-less, ambiguous and un-enveloped multicast frames
    /// fail closed. Meta operations have no message recipient.
    pub fn canonical_recipient(&self) -> Result<&str, &'static str> {
        let simple = self.innermost_simple().ok_or("message has no recipient")?;
        if simple.recipient_set().is_empty() {
            return Err("message has no recipient");
        }
        if let Message::Wrapped {
            wrapper: WrapperType::Envelope,
            params,
            ..
        } = self
        {
            let mut audience = None;
            let mut iter = params.iter();
            while let Some(param) = iter.next() {
                if let SExpr::Atom(Atom::Keyword(key)) = param {
                    let value = iter.next();
                    if key == "to" {
                        if audience.is_some() {
                            return Err("ambiguous envelope recipient");
                        }
                        audience = Some(match value {
                            Some(SExpr::Atom(Atom::Symbol(s))) if s.starts_with('@') => s.as_str(),
                            _ => return Err("envelope :to must be a recipient symbol"),
                        });
                    }
                }
            }
            return audience.ok_or("envelope requires :to");
        }
        simple
            .recipient()
            .ok_or("message must have exactly one recipient")
    }

    /// Returns all recipients of a Simple message as a normalized set
    /// (empty when the recipient position is absent) — SPEC-014 REQ-622.
    pub fn recipient_set(&self) -> alloc::collections::BTreeSet<&str> {
        match self {
            Message::Simple {
                recipient: Some(r), ..
            } => r.as_set(),
            _ => alloc::collections::BTreeSet::new(),
        }
    }

    /// Returns the content if this is a Simple message.
    pub fn content(&self) -> Option<&SExpr> {
        match self {
            Message::Simple { content, .. } => Some(content),
            _ => None,
        }
    }

    /// Returns the thread if this is a Simple message with one.
    pub fn thread(&self) -> Option<&str> {
        match self {
            Message::Simple {
                thread: Some(t), ..
            } => Some(t.as_str()),
            _ => None,
        }
    }

    /// Returns the sender if this is a Simple message with one.
    pub fn sender(&self) -> Option<&str> {
        match self {
            Message::Simple {
                sender: Some(s), ..
            } => Some(s.as_str()),
            _ => None,
        }
    }

    /// Returns the caused-by reference if this is a Simple message with one.
    pub fn caused_by(&self) -> Option<&CausedBy> {
        match self {
            Message::Simple {
                caused_by: Some(cb),
                ..
            } => Some(cb),
            _ => None,
        }
    }

    /// Returns the dialect definition if this is a Meta message.
    pub fn dialect_def(&self) -> Option<&SExpr> {
        match self {
            Message::Meta { dialect_def } => Some(dialect_def),
            _ => None,
        }
    }

    /// Returns the dialect name if this is a Dialect message.
    pub fn dialect_name(&self) -> Option<&str> {
        match self {
            Message::Dialect { dialect_name, .. } => Some(dialect_name.as_str()),
            _ => None,
        }
    }

    /// Returns the inner message for Dialect or Wrapped messages.
    pub fn inner_message(&self) -> Option<&Message> {
        match self {
            Message::Dialect { inner, .. } => Some(inner),
            Message::Wrapped { content, .. } => Some(content),
            _ => None,
        }
    }

    /// Walk through `Wrapped` and `Dialect` envelopes to the innermost
    /// `Message::Simple`. Returns `None` if no Simple is found (e.g. a `Meta`
    /// message). Used by the parser pipeline and the agent to ensure
    /// wrappers cannot be used to bypass causal/shape verification.
    pub fn innermost_simple(&self) -> Option<&Message> {
        let mut cur = self;
        loop {
            match cur {
                Message::Simple { .. } => return Some(cur),
                Message::Wrapped { content, .. } => cur = content,
                Message::Dialect { inner, .. } => cur = inner,
                Message::Meta { .. } => return None,
            }
        }
    }

    /// Returns the wrapper type if this is a Wrapped message.
    pub fn wrapper_type(&self) -> Option<WrapperType> {
        match self {
            Message::Wrapped { wrapper, .. } => Some(*wrapper),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// From<Message> for SExpr
// ---------------------------------------------------------------------------

impl From<Message> for SExpr {
    fn from(msg: Message) -> SExpr {
        match msg {
            Message::Simple {
                performative,
                recipient,
                content,
                params,
                thread,
                sender,
                caused_by,
            } => {
                let mut items = vec![SExpr::Atom(Atom::Symbol(String::from(performative.name())))];
                match recipient {
                    Some(Recipients::One(r)) => {
                        items.push(SExpr::Atom(Atom::Symbol(r)));
                    }
                    Some(Recipients::Set(rs)) => {
                        items.push(SExpr::List(
                            rs.into_iter()
                                .map(|r| SExpr::Atom(Atom::Symbol(r)))
                                .collect(),
                        ));
                    }
                    None => {}
                }
                items.push(content);
                items.extend(crate::canonical::canonical_params(&params));
                if let Some(t) = thread {
                    items.push(SExpr::Atom(Atom::Keyword(String::from("thread"))));
                    items.push(SExpr::Atom(Atom::Str(t)));
                }
                if let Some(s) = sender {
                    items.push(SExpr::Atom(Atom::Keyword(String::from("sender"))));
                    items.push(SExpr::Atom(Atom::Str(s)));
                }
                if let Some(cb) = caused_by {
                    items.push(SExpr::Atom(Atom::Keyword(String::from("caused-by"))));
                    match cb {
                        CausedBy::Begin => {
                            items.push(SExpr::Atom(Atom::Symbol(String::from(BEGIN_KEYWORD))));
                        }
                        CausedBy::Single(h) => {
                            items.push(SExpr::Atom(Atom::Symbol(h)));
                        }
                        CausedBy::Multiple(hs) => {
                            let hash_exprs = hs
                                .iter()
                                .map(|h| SExpr::Atom(Atom::Symbol(h.clone())))
                                .collect();
                            items.push(SExpr::List(hash_exprs));
                        }
                    }
                }
                SExpr::List(items)
            }
            Message::Meta { dialect_def } => SExpr::List(vec![
                SExpr::Atom(Atom::Symbol(String::from("meta"))),
                dialect_def,
            ]),
            Message::Dialect {
                dialect_name,
                inner,
            } => SExpr::List(vec![
                SExpr::Atom(Atom::Symbol(String::from("lang"))),
                SExpr::Atom(Atom::Symbol(dialect_name)),
                SExpr::from(*inner),
            ]),
            Message::Wrapped {
                wrapper,
                params,
                content,
            } => {
                let mut items = vec![SExpr::Atom(Atom::Symbol(String::from(wrapper.as_str())))];
                items.extend(crate::canonical::canonical_params(&params));
                items.push(SExpr::from(*content));
                SExpr::List(items)
            }
        }
    }
}

impl From<&Message> for SExpr {
    fn from(msg: &Message) -> SExpr {
        SExpr::from(msg.clone())
    }
}

// ---------------------------------------------------------------------------
// TryFrom<&SExpr> for Message
// ---------------------------------------------------------------------------

/// Error returned when converting an SExpr to a Message fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MessageParseError(pub String);

impl fmt::Display for MessageParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<&SExpr> for Message {
    type Error = MessageParseError;

    fn try_from(sexpr: &SExpr) -> Result<Self, Self::Error> {
        parse_message_scoped(sexpr, LangScope::Unscoped)
    }
}

/// Whether the message being recognised sits inside a `(lang …)` wrapper
/// (REQ-033).
///
/// This is the only context a *custom* performative may appear in. The `lang`
/// tag plus the dialect name is the deterministic dispatch token that selects
/// which dialect's subgrammar applies; without it the head symbol alone would
/// have to select it, and which dialect that names is a property of the
/// receiver's installed set rather than of the message. Two agents holding
/// different dialects would then read the same bytes differently, which is the
/// parser-equivalence failure the whole design exists to exclude.
///
/// Because dispatch goes through `lang`, two dialects defining the same
/// performative name is not a conflict at all — the wrapper says which one is
/// meant. That coexistence is the feature the scoping rule buys.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LangScope {
    /// No enclosing `(lang …)`: only core performatives may head a message.
    Unscoped,
    /// Inside a `(lang <dialect> …)`, possibly through wrappers.
    Scoped,
    /// No enclosing `(lang …)`, but the caller dispatches a bare custom head
    /// by name itself and asked for it ([`Message::parse_lax`]): a control
    /// frame of a host whose control plane predates the scoping rule. Never a
    /// content message.
    Lax,
}

/// Recognise a message, tracking whether a `(lang …)` wrapper encloses it.
///
/// Wrappers propagate the scope they were found in, so
/// `(lang d (signed "…" (offer …)))` recognises `offer` as scoped, while
/// `(signed "…" (offer …))` does not.
fn parse_message_scoped(sexpr: &SExpr, scope: LangScope) -> Result<Message, MessageParseError> {
    let items = match sexpr {
        SExpr::List(items) if !items.is_empty() => items,
        SExpr::List(_) => return Err(MessageParseError(String::from("empty message"))),
        _ => return Err(MessageParseError(String::from("message must be a list"))),
    };

    let head = match &items[0] {
        SExpr::Atom(Atom::Symbol(s)) => s.as_str(),
        _ => {
            return Err(MessageParseError(String::from(
                "message head must be a symbol",
            )))
        }
    };

    match head {
        "meta" => parse_meta(&items[1..]),
        "lang" => parse_dialect_msg(&items[1..]),
        w if WrapperType::parse(w).is_some() => {
            parse_wrapped(WrapperType::parse(w).unwrap(), &items[1..], scope)
        }
        _ => parse_simple(head, &items[1..], scope),
    }
}

fn parse_meta(tail: &[SExpr]) -> Result<Message, MessageParseError> {
    if tail.is_empty() {
        return Err(MessageParseError(String::from(
            "meta message requires an operation",
        )));
    }
    Ok(Message::Meta {
        dialect_def: tail[0].clone(),
    })
}

fn parse_dialect_msg(tail: &[SExpr]) -> Result<Message, MessageParseError> {
    if tail.len() < 2 {
        return Err(MessageParseError(String::from(
            "dialect message requires dialect name and inner message",
        )));
    }
    let dialect_name = match &tail[0] {
        SExpr::Atom(Atom::Symbol(s)) => s.clone(),
        _ => {
            return Err(MessageParseError(String::from(
                "dialect name must be a symbol",
            )))
        }
    };
    // Entering a `lang` wrapper is what puts the inner message in scope: the
    // dialect name is now fixed by the message itself (REQ-033).
    let inner = parse_message_scoped(&tail[1], LangScope::Scoped)?;
    Ok(Message::Dialect {
        dialect_name,
        inner: Box::new(inner),
    })
}

fn parse_wrapped(
    wrapper: WrapperType,
    tail: &[SExpr],
    scope: LangScope,
) -> Result<Message, MessageParseError> {
    // The last list element is the inner message; everything before it is params.
    let inner_idx = tail.iter().rposition(|item| matches!(item, SExpr::List(_)));
    match inner_idx {
        Some(idx) => {
            if idx + 1 != tail.len() {
                return Err(MessageParseError(String::from(
                    "wrapper inner message must be last",
                )));
            }
            // A wrapper neither establishes nor discards a lang scope; it
            // carries through whatever it was found in.
            let inner = parse_message_scoped(&tail[idx], scope)?;
            let params = &tail[..idx];
            validate_param_keywords(params)?;
            let params = crate::canonical::canonical_params(params);
            Ok(Message::Wrapped {
                wrapper,
                params,
                content: Box::new(inner),
            })
        }
        None => Err(MessageParseError(String::from(
            "wrapped message requires an inner message",
        ))),
    }
}

/// Whether an S-expression is a single address token (`@key`).
fn is_address(s: &SExpr) -> bool {
    matches!(s, SExpr::Atom(Atom::Symbol(sym)) if sym.starts_with('@'))
}

/// Recognise parameter structure before normalising it (SPEC-042 REQ-4201).
fn validate_param_keywords(params: &[SExpr]) -> Result<(), MessageParseError> {
    let mut seen = alloc::collections::BTreeSet::new();
    let mut i = 0;
    while i < params.len() {
        if let SExpr::Atom(Atom::Keyword(key)) = &params[i] {
            if i + 1 == params.len() {
                return Err(MessageParseError(alloc::format!(
                    "keyword :{key} missing value"
                )));
            }
            if !seen.insert(key) {
                return Err(MessageParseError(alloc::format!(
                    "duplicate keyword :{key}"
                )));
            }
            i += 2;
        } else {
            i += 1;
        }
    }
    Ok(())
}

/// Whether an S-expression is an *address group*: a single address `@x` or a
/// non-empty list of addresses `(@a @b)`. These are exactly the forms the
/// recipient position accepts, so they are forbidden as positional content
/// (which is what keeps `@` sigil-disciplined and serialise ∘ parse injective).
/// A mixed list like `(introduce @bob)` is not an address group — it is
/// ordinary content with a nested address.
fn is_address_group(s: &SExpr) -> bool {
    match s {
        SExpr::Atom(Atom::Symbol(sym)) => sym.starts_with('@'),
        SExpr::List(items) => !items.is_empty() && items.iter().all(is_address),
        _ => false,
    }
}

fn parse_simple(
    head: &str,
    tail: &[SExpr],
    scope: LangScope,
) -> Result<Message, MessageParseError> {
    validate_param_keywords(tail)?;
    let performative = match CorePerformative::parse(head) {
        Some(cp) => Performative::Core(cp),
        // A custom performative outside a `(lang …)` wrapper has no
        // deterministic dispatch: nothing in the message says which dialect
        // defines it. Reject rather than resolve against the installed set
        // (REQ-033) — see `LangScope`.
        None if scope == LangScope::Unscoped => {
            return Err(MessageParseError(alloc::format!(
                "'{head}' is not a core performative; a dialect performative must be \
                 invoked inside (lang <dialect> ...) so the message names the dialect \
                 that defines it"
            )))
        }
        None => Performative::Custom(String::from(head)),
    };

    let mut recipient = None;
    let mut content = None;
    let mut thread = None;
    let mut sender_val = None;
    let mut caused_by = None;
    let mut params = Vec::new();
    let mut i = 0;

    // Check for a recipient as the first arg: an @-prefixed symbol
    // (single) or a non-empty list of @-prefixed symbols (multicast,
    // SPEC-014 REQ-622). An empty list stays content (pre-SPEC-014 form).
    if i < tail.len() {
        match &tail[i] {
            SExpr::Atom(Atom::Symbol(s)) if s.starts_with('@') => {
                recipient = Some(Recipients::One(s.clone()));
                i += 1;
            }
            SExpr::List(items) if !items.is_empty() && items.iter().all(is_address) => {
                let set: alloc::collections::BTreeSet<String> = items
                    .iter()
                    .map(|it| match it {
                        SExpr::Atom(Atom::Symbol(s)) => s.clone(),
                        _ => unreachable!("guarded by the match arm"),
                    })
                    .collect();
                recipient = Some(Recipients::Set(set));
                i += 1;
            }
            _ => {}
        }
    }

    // Parse remaining args: first non-keyword is content, rest are params.
    while i < tail.len() {
        match &tail[i] {
            SExpr::Atom(Atom::Keyword(k)) => {
                if i + 1 >= tail.len() {
                    return Err(MessageParseError(alloc::format!(
                        "keyword :{k} missing value"
                    )));
                }
                let val = &tail[i + 1];
                if k == "thread" {
                    thread = Some(extract_string_or_symbol(val));
                } else if k == "sender" {
                    sender_val = Some(extract_string_or_symbol(val));
                } else if k == "caused-by" {
                    caused_by = Some(parse_caused_by(val)?);
                } else {
                    params.push(tail[i].clone());
                    params.push(val.clone());
                }
                i += 2;
            }
            // An address group — a bare `@x` or an all-`@` list `(@a @b)` —
            // is not data. These are exactly the forms the recipient parser
            // accepts above, so admitting them as content would overload the
            // surface syntax and break serialise ∘ parse (a content address
            // group re-parses as the recipient). Reject them in the positional
            // slot; addresses belong in the recipient slot or a keyword value.
            // A *mixed* list (e.g. `(introduce @bob)`) is ordinary content —
            // nested addresses are fine — as are `@`-runs inside a string.
            positional if is_address_group(positional) => {
                return Err(MessageParseError(alloc::format!(
                    "address(es) '{positional}' in content position; addresses \
                     go in the recipient slot or a keyword value"
                )));
            }
            _ => {
                if content.is_none() {
                    content = Some(tail[i].clone());
                } else {
                    params.push(tail[i].clone());
                }
                i += 1;
            }
        }
    }

    Ok(Message::Simple {
        performative,
        recipient,
        content: content.unwrap_or(SExpr::List(Vec::new())),
        params: crate::canonical::canonical_params(&params),
        thread,
        sender: sender_val,
        caused_by,
    })
}

/// Parse the value of a `:caused-by` keyword parameter.
///
/// Accepts three forms:
/// - `"begin"` or `begin` symbol → `CausedBy::Begin`
/// - Single atom (hash) → `CausedBy::Single(hash)`
/// - List of atoms (hashes) → `CausedBy::Multiple(sorted_hashes)`
fn parse_caused_by(val: &SExpr) -> Result<CausedBy, MessageParseError> {
    match val {
        SExpr::Atom(Atom::Symbol(s)) if s == BEGIN_KEYWORD => Ok(CausedBy::Begin),
        SExpr::Atom(Atom::Str(s)) if s == BEGIN_KEYWORD => Ok(CausedBy::Begin),
        SExpr::Atom(Atom::Symbol(s)) => Ok(CausedBy::Single(s.clone())),
        SExpr::Atom(Atom::Str(s)) => Ok(CausedBy::Single(s.clone())),
        SExpr::List(items) => {
            if items.is_empty() {
                return Err(MessageParseError(String::from(
                    ":caused-by list must not be empty",
                )));
            }
            let mut hashes = Vec::with_capacity(items.len());
            for item in items {
                match item {
                    SExpr::Atom(Atom::Symbol(s)) | SExpr::Atom(Atom::Str(s)) => {
                        hashes.push(s.clone());
                    }
                    _ => {
                        return Err(MessageParseError(String::from(
                            ":caused-by list elements must be symbols or strings",
                        )));
                    }
                }
            }
            // Canonical ordering: sort lexicographically (REQ-202)
            hashes.sort();
            Ok(CausedBy::Multiple(hashes))
        }
        _ => Err(MessageParseError(String::from(
            ":caused-by value must be a symbol, string, or list of hashes",
        ))),
    }
}

fn extract_string_or_symbol(sexpr: &SExpr) -> String {
    match sexpr {
        SExpr::Atom(Atom::Str(s)) | SExpr::Atom(Atom::Symbol(s)) => s.clone(),
        other => alloc::format!("{other}"),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::ToString;

    #[test]
    fn core_performative_names_count() {
        assert_eq!(CORE_PERFORMATIVE_NAMES.len(), 8);
    }

    #[test]
    fn is_core_performative() {
        assert!(is_core_performative_name("tell"));
        assert!(is_core_performative_name("bye"));
        assert!(!is_core_performative_name("custom-perf"));
    }

    #[test]
    fn core_performative_roundtrip() {
        for name in CORE_PERFORMATIVE_NAMES {
            let cp = CorePerformative::parse(name).unwrap();
            assert_eq!(cp.as_str(), *name);
        }
    }

    #[test]
    fn performative_name() {
        assert_eq!(Performative::Core(CorePerformative::Tell).name(), "tell");
        assert_eq!(
            Performative::Custom(String::from("propose-step")).name(),
            "propose-step"
        );
    }

    #[test]
    fn wrapper_type_roundtrip() {
        for (s, w) in [
            ("envelope", WrapperType::Envelope),
            ("signed", WrapperType::Signed),
            ("with-limits", WrapperType::WithLimits),
        ] {
            assert_eq!(WrapperType::parse(s), Some(w));
            assert_eq!(w.as_str(), s);
        }
        assert_eq!(WrapperType::parse("unknown"), None);
    }

    #[test]
    fn message_type_classification() {
        let simple = Message::Simple {
            performative: Performative::Core(CorePerformative::Tell),
            recipient: None,
            content: SExpr::Atom(Atom::Str("hi".into())),
            params: vec![],
            thread: None,
            sender: None,
            caused_by: None,
        };
        assert_eq!(simple.message_type(), MessageType::Simple);

        let meta = Message::Meta {
            dialect_def: SExpr::List(vec![]),
        };
        assert_eq!(meta.message_type(), MessageType::Meta);

        let dialect = Message::Dialect {
            dialect_name: "test".into(),
            inner: Box::new(simple.clone()),
        };
        assert_eq!(dialect.message_type(), MessageType::Dialect);

        let wrapped = Message::Wrapped {
            wrapper: WrapperType::Envelope,
            params: vec![],
            content: Box::new(simple),
        };
        assert_eq!(wrapped.message_type(), MessageType::Wrapped);
    }

    // -- Typed extraction --

    #[test]
    fn simple_extraction_methods() {
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Tell),
            recipient: Some("@bob".into()),
            content: SExpr::Atom(Atom::Str("hello".into())),
            params: vec![],
            thread: Some("conv-1".into()),
            sender: Some("@alice".into()),
            caused_by: None,
        };
        assert_eq!(msg.performative().unwrap().name(), "tell");
        assert_eq!(msg.recipient(), Some("@bob"));
        assert_eq!(msg.content(), Some(&SExpr::Atom(Atom::Str("hello".into()))));
        assert_eq!(msg.thread(), Some("conv-1"));
        assert_eq!(msg.sender(), Some("@alice"));
        assert!(msg.dialect_def().is_none());
        assert!(msg.inner_message().is_none());
        assert!(msg.wrapper_type().is_none());
    }

    #[test]
    fn meta_extraction_methods() {
        let def = SExpr::List(vec![
            SExpr::Atom(Atom::Symbol("define".into())),
            SExpr::Atom(Atom::Symbol("test-dialect".into())),
        ]);
        let msg = Message::Meta {
            dialect_def: def.clone(),
        };
        assert_eq!(msg.dialect_def(), Some(&def));
        assert!(msg.performative().is_none());
    }

    #[test]
    fn dialect_extraction_methods() {
        let inner = Message::Simple {
            performative: Performative::Core(CorePerformative::Tell),
            recipient: None,
            content: SExpr::Atom(Atom::Str("hi".into())),
            params: vec![],
            thread: None,
            sender: None,
            caused_by: None,
        };
        let msg = Message::Dialect {
            dialect_name: "logistics".into(),
            inner: Box::new(inner.clone()),
        };
        assert_eq!(msg.dialect_name(), Some("logistics"));
        assert_eq!(msg.inner_message(), Some(&inner));
    }

    #[test]
    fn wrapped_extraction_methods() {
        let inner = Message::Simple {
            performative: Performative::Core(CorePerformative::Tell),
            recipient: None,
            content: SExpr::Atom(Atom::Str("hi".into())),
            params: vec![],
            thread: None,
            sender: None,
            caused_by: None,
        };
        let msg = Message::Wrapped {
            wrapper: WrapperType::Signed,
            params: vec![SExpr::Atom(Atom::Str("sig".into()))],
            content: Box::new(inner.clone()),
        };
        assert_eq!(msg.wrapper_type(), Some(WrapperType::Signed));
        assert_eq!(msg.inner_message(), Some(&inner));
    }

    // -- TryFrom<&SExpr> for Message --

    fn sym(s: &str) -> SExpr {
        SExpr::Atom(Atom::Symbol(String::from(s)))
    }

    fn str_expr(s: &str) -> SExpr {
        SExpr::Atom(Atom::Str(String::from(s)))
    }

    fn kw(s: &str) -> SExpr {
        SExpr::Atom(Atom::Keyword(String::from(s)))
    }

    fn list(items: Vec<SExpr>) -> SExpr {
        SExpr::List(items)
    }

    #[test]
    fn try_from_simple_tell() {
        let sexpr = list(vec![sym("tell"), sym("@bob"), str_expr("hello")]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(msg.message_type(), MessageType::Simple);
        assert_eq!(msg.performative().unwrap().name(), "tell");
        assert_eq!(msg.recipient(), Some("@bob"));
        assert_eq!(msg.content(), Some(&str_expr("hello")));
    }

    #[test]
    fn try_from_simple_no_recipient() {
        let sexpr = list(vec![sym("reply"), str_expr("done")]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert!(msg.recipient().is_none());
        assert_eq!(msg.content(), Some(&str_expr("done")));
    }

    #[test]
    fn try_from_simple_with_thread() {
        let sexpr = list(vec![
            sym("tell"),
            str_expr("hello"),
            kw("thread"),
            sym("conv-17"),
        ]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(msg.thread(), Some("conv-17"));
    }

    #[test]
    fn try_from_simple_with_keyword_params() {
        let sexpr = list(vec![
            sym("ask"),
            sym("@alice"),
            str_expr("What?"),
            kw("timeout"),
            SExpr::Atom(Atom::Num(30)),
        ]);
        let msg = Message::try_from(&sexpr).unwrap();
        if let Message::Simple { params, .. } = &msg {
            assert_eq!(params.len(), 2); // :timeout and 30
        } else {
            panic!("expected Simple");
        }
    }

    #[test]
    fn try_from_meta() {
        let op = list(vec![sym("define"), sym("test-dialect")]);
        let sexpr = list(vec![sym("meta"), op.clone()]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(msg.message_type(), MessageType::Meta);
        assert_eq!(msg.dialect_def(), Some(&op));
    }

    #[test]
    fn try_from_dialect() {
        let inner = list(vec![sym("tell"), sym("@system"), str_expr("PKG-123")]);
        let sexpr = list(vec![sym("lang"), sym("logistics"), inner]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(msg.message_type(), MessageType::Dialect);
        assert_eq!(msg.dialect_name(), Some("logistics"));
        let inner_msg = msg.inner_message().unwrap();
        assert_eq!(inner_msg.message_type(), MessageType::Simple);
        assert_eq!(inner_msg.performative().unwrap().name(), "tell");
    }

    #[test]
    fn try_from_wrapped_envelope() {
        let inner = list(vec![sym("tell"), sym("@bob"), str_expr("Hello")]);
        let sexpr = list(vec![
            sym("envelope"),
            kw("from"),
            sym("@alice"),
            kw("to"),
            sym("@bob"),
            inner,
        ]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(msg.message_type(), MessageType::Wrapped);
        assert_eq!(msg.wrapper_type(), Some(WrapperType::Envelope));
        if let Message::Wrapped { params, .. } = &msg {
            assert_eq!(params.len(), 4); // :from @alice :to @bob
        }
    }

    #[test]
    fn try_from_wrapped_signed() {
        let inner = list(vec![sym("tell"), sym("@bob"), str_expr("Verified")]);
        let sexpr = list(vec![sym("signed"), str_expr("base64sig"), inner]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(msg.wrapper_type(), Some(WrapperType::Signed));
        if let Message::Wrapped { params, .. } = &msg {
            assert_eq!(params, &[str_expr("base64sig")]);
        }
    }

    #[test]
    fn try_from_wrapped_with_limits() {
        let inner = list(vec![sym("tell"), sym("@bob"), str_expr("Constrained")]);
        let sexpr = list(vec![
            sym("with-limits"),
            kw("depth"),
            SExpr::Atom(Atom::Num(10)),
            kw("cpu"),
            SExpr::Atom(Atom::Num(100)),
            inner,
        ]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(msg.wrapper_type(), Some(WrapperType::WithLimits));
    }

    #[test]
    fn try_from_errors() {
        // Empty list
        assert!(Message::try_from(&list(vec![])).is_err());
        // Non-list
        assert!(Message::try_from(&sym("hello")).is_err());
        // Non-symbol head
        assert!(Message::try_from(&list(vec![str_expr("tell")])).is_err());
        // Meta without operation
        assert!(Message::try_from(&list(vec![sym("meta")])).is_err());
        // Dialect without inner
        assert!(Message::try_from(&list(vec![sym("lang"), sym("d")])).is_err());
    }

    #[test]
    fn message_parse_error_display() {
        let err = MessageParseError(String::from("test error"));
        assert_eq!(err.to_string(), "test error");
    }

    // -- From<Message> for SExpr --

    #[test]
    fn simple_to_sexpr() {
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Tell),
            recipient: Some("@bob".into()),
            content: str_expr("hello"),
            params: vec![],
            thread: None,
            sender: None,
            caused_by: None,
        };
        let sexpr = SExpr::from(msg);
        assert_eq!(sexpr.to_string(), "(tell @bob \"hello\")");
    }

    #[test]
    fn simple_with_thread_to_sexpr() {
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Reply),
            recipient: None,
            content: str_expr("done"),
            params: vec![],
            thread: Some("conv-17".into()),
            sender: None,
            caused_by: None,
        };
        let sexpr = SExpr::from(msg);
        assert_eq!(sexpr.to_string(), "(reply \"done\" :thread \"conv-17\")");
    }

    #[test]
    fn meta_to_sexpr() {
        let msg = Message::Meta {
            dialect_def: list(vec![sym("define"), sym("test-dialect")]),
        };
        let sexpr = SExpr::from(msg);
        assert_eq!(sexpr.to_string(), "(meta (define test-dialect))");
    }

    #[test]
    fn dialect_to_sexpr() {
        let msg = Message::Dialect {
            dialect_name: "logistics".into(),
            inner: Box::new(Message::Simple {
                performative: Performative::Core(CorePerformative::Tell),
                recipient: Some("@system".into()),
                content: str_expr("PKG-123"),
                params: vec![],
                thread: None,
                sender: None,
                caused_by: None,
            }),
        };
        let sexpr = SExpr::from(msg);
        assert_eq!(
            sexpr.to_string(),
            "(lang logistics (tell @system \"PKG-123\"))"
        );
    }

    #[test]
    fn wrapped_to_sexpr() {
        let msg = Message::Wrapped {
            wrapper: WrapperType::Signed,
            params: vec![str_expr("base64sig")],
            content: Box::new(Message::Simple {
                performative: Performative::Core(CorePerformative::Tell),
                recipient: Some("@bob".into()),
                content: str_expr("Verified"),
                params: vec![],
                thread: None,
                sender: None,
                caused_by: None,
            }),
        };
        let sexpr = SExpr::from(msg);
        assert_eq!(
            sexpr.to_string(),
            "(signed \"base64sig\" (tell @bob \"Verified\"))"
        );
    }

    // -- Round-trip tests --

    #[test]
    fn roundtrip_simple() {
        let original = list(vec![sym("tell"), sym("@bob"), str_expr("hello")]);
        let msg = Message::try_from(&original).unwrap();
        let back = SExpr::from(msg);
        assert_eq!(back, original);
    }

    #[test]
    fn roundtrip_meta() {
        let original = list(vec![
            sym("meta"),
            list(vec![sym("query"), list(vec![sym("speak?"), sym("cbcl")])]),
        ]);
        let msg = Message::try_from(&original).unwrap();
        let back = SExpr::from(msg);
        assert_eq!(back, original);
    }

    #[test]
    fn roundtrip_dialect() {
        let original = list(vec![
            sym("lang"),
            sym("logistics"),
            list(vec![sym("tell"), sym("@system"), str_expr("PKG-123")]),
        ]);
        let msg = Message::try_from(&original).unwrap();
        let back = SExpr::from(msg);
        assert_eq!(back, original);
    }

    #[test]
    fn roundtrip_wrapped() {
        let original = list(vec![
            sym("signed"),
            str_expr("base64sig"),
            list(vec![sym("tell"), sym("@bob"), str_expr("Verified")]),
        ]);
        let msg = Message::try_from(&original).unwrap();
        let back = SExpr::from(msg);
        assert_eq!(back, original);
    }

    #[test]
    fn custom_performative() {
        let sexpr = list(vec![sym("propose-step"), sym("s1"), sym("pickup")]);
        assert!(Message::try_from(&sexpr).is_err());
        let sexpr = list(vec![sym("lang"), sym("cbcl-planning"), sexpr]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(
            msg.innermost_simple().unwrap().performative(),
            Some(&Performative::Custom(String::from("propose-step")))
        );
    }

    // -- CausedBy (REQ-202, TEST-202) --

    #[test]
    fn caused_by_begin_symbol() {
        let sexpr = list(vec![
            sym("tell"),
            str_expr("hello"),
            kw("caused-by"),
            sym("begin"),
        ]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(msg.caused_by(), Some(&CausedBy::Begin));
    }

    #[test]
    fn caused_by_begin_string() {
        let sexpr = list(vec![
            sym("tell"),
            str_expr("hello"),
            kw("caused-by"),
            str_expr("begin"),
        ]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(msg.caused_by(), Some(&CausedBy::Begin));
    }

    #[test]
    fn caused_by_single_hash() {
        let sexpr = list(vec![
            sym("reply"),
            str_expr("done"),
            kw("caused-by"),
            sym("f1220abc123"),
        ]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(
            msg.caused_by(),
            Some(&CausedBy::Single(String::from("f1220abc123")))
        );
    }

    #[test]
    fn caused_by_single_hash_string() {
        let sexpr = list(vec![
            sym("reply"),
            str_expr("done"),
            kw("caused-by"),
            str_expr("f1220abc123"),
        ]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(
            msg.caused_by(),
            Some(&CausedBy::Single(String::from("f1220abc123")))
        );
    }

    #[test]
    fn caused_by_multiple_hashes() {
        let sexpr = list(vec![
            sym("ok"),
            str_expr("ack"),
            kw("caused-by"),
            list(vec![sym("f1220bbb"), sym("f1220aaa")]),
        ]);
        let msg = Message::try_from(&sexpr).unwrap();
        // Multiple hashes are sorted lexicographically
        assert_eq!(
            msg.caused_by(),
            Some(&CausedBy::Multiple(vec![
                String::from("f1220aaa"),
                String::from("f1220bbb"),
            ]))
        );
    }

    #[test]
    fn caused_by_multiple_canonical_sort() {
        // Verify that different input orderings produce the same canonical form
        let sexpr1 = list(vec![
            sym("ok"),
            str_expr("ack"),
            kw("caused-by"),
            list(vec![sym("c"), sym("a"), sym("b")]),
        ]);
        let sexpr2 = list(vec![
            sym("ok"),
            str_expr("ack"),
            kw("caused-by"),
            list(vec![sym("b"), sym("c"), sym("a")]),
        ]);
        let msg1 = Message::try_from(&sexpr1).unwrap();
        let msg2 = Message::try_from(&sexpr2).unwrap();
        assert_eq!(msg1.caused_by(), msg2.caused_by());
        assert_eq!(
            msg1.caused_by(),
            Some(&CausedBy::Multiple(vec![
                String::from("a"),
                String::from("b"),
                String::from("c"),
            ]))
        );
    }

    #[test]
    fn caused_by_none_when_absent() {
        let sexpr = list(vec![sym("tell"), str_expr("hello")]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert!(msg.caused_by().is_none());
    }

    #[test]
    fn caused_by_empty_list_error() {
        let sexpr = list(vec![
            sym("tell"),
            str_expr("hello"),
            kw("caused-by"),
            list(vec![]),
        ]);
        assert!(Message::try_from(&sexpr).is_err());
    }

    #[test]
    fn caused_by_invalid_type_error() {
        let sexpr = list(vec![
            sym("tell"),
            str_expr("hello"),
            kw("caused-by"),
            SExpr::Atom(Atom::Num(42)),
        ]);
        assert!(Message::try_from(&sexpr).is_err());
    }

    #[test]
    fn caused_by_roundtrip_begin() {
        let original = list(vec![
            sym("tell"),
            str_expr("hello"),
            kw("caused-by"),
            sym("begin"),
        ]);
        let msg = Message::try_from(&original).unwrap();
        let back = SExpr::from(msg);
        assert_eq!(back, original);
    }

    #[test]
    fn caused_by_roundtrip_single() {
        let original = list(vec![
            sym("reply"),
            str_expr("done"),
            kw("caused-by"),
            sym("f1220abc"),
        ]);
        let msg = Message::try_from(&original).unwrap();
        let back = SExpr::from(msg);
        assert_eq!(back, original);
    }

    #[test]
    fn caused_by_roundtrip_multiple_sorted() {
        // Input already sorted → roundtrip exact match
        let original = list(vec![
            sym("ok"),
            str_expr("ack"),
            kw("caused-by"),
            list(vec![sym("aaa"), sym("bbb"), sym("ccc")]),
        ]);
        let msg = Message::try_from(&original).unwrap();
        let back = SExpr::from(msg);
        assert_eq!(back, original);
    }

    #[test]
    fn caused_by_roundtrip_multiple_canonicalized() {
        // Input unsorted → extract canonicalizes → roundtrip produces sorted form
        let input = list(vec![
            sym("ok"),
            str_expr("ack"),
            kw("caused-by"),
            list(vec![sym("ccc"), sym("aaa"), sym("bbb")]),
        ]);
        let msg = Message::try_from(&input).unwrap();
        let back = SExpr::from(msg);
        let expected = list(vec![
            sym("ok"),
            str_expr("ack"),
            kw("caused-by"),
            list(vec![sym("aaa"), sym("bbb"), sym("ccc")]),
        ]);
        assert_eq!(back, expected);
    }

    #[test]
    fn caused_by_with_thread_and_sender() {
        let sexpr = list(vec![
            sym("tell"),
            sym("@bob"),
            str_expr("hello"),
            kw("thread"),
            sym("conv-1"),
            kw("sender"),
            sym("@alice"),
            kw("caused-by"),
            sym("f1220xyz"),
        ]);
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(msg.thread(), Some("conv-1"));
        assert_eq!(msg.sender(), Some("@alice"));
        assert_eq!(
            msg.caused_by(),
            Some(&CausedBy::Single(String::from("f1220xyz")))
        );
    }

    #[test]
    fn caused_by_extract_hash_deterministic() {
        // REQ-202: extract → canonical → hash is deterministic
        use crate::canonical::canonical_encode;

        let sexpr1 = list(vec![
            sym("ok"),
            str_expr("ack"),
            kw("caused-by"),
            list(vec![sym("z"), sym("a"), sym("m")]),
        ]);
        let sexpr2 = list(vec![
            sym("ok"),
            str_expr("ack"),
            kw("caused-by"),
            list(vec![sym("m"), sym("z"), sym("a")]),
        ]);
        let msg1 = Message::try_from(&sexpr1).unwrap();
        let msg2 = Message::try_from(&sexpr2).unwrap();
        let bytes1 = canonical_encode(&SExpr::from(msg1));
        let bytes2 = canonical_encode(&SExpr::from(msg2));
        assert_eq!(
            bytes1, bytes2,
            "canonical encoding must be deterministic after sorting"
        );
    }

    // ---- SPEC-014 REQ-622: recipient sets ----

    #[test]
    fn multicast_recipient_parses_and_roundtrips() {
        let sexpr: SExpr = "(lang oauth (login (@cli @as) \"n-42\" :caused-by h0))"
            .parse()
            .unwrap();
        let msg = Message::try_from(&sexpr).unwrap();
        let set = msg.innermost_simple().unwrap().recipient_set();
        assert_eq!(set.len(), 2);
        assert!(set.contains("@cli") && set.contains("@as"));
        // round-trip: serialise and re-parse preserves the set
        let back = SExpr::from(&msg);
        let msg2 = Message::try_from(&back).unwrap();
        assert_eq!(msg, msg2);
    }

    #[test]
    fn multicast_serialisation_is_canonical_sorted() {
        let a: SExpr = "(lang oauth (login (@b @a) \"x\"))".parse().unwrap();
        let b: SExpr = "(lang oauth (login (@a @b) \"x\"))".parse().unwrap();
        let ma = Message::try_from(&a).unwrap();
        let mb = Message::try_from(&b).unwrap();
        assert_eq!(SExpr::from(&ma), SExpr::from(&mb));
    }

    #[test]
    fn single_recipient_form_is_unchanged() {
        let sexpr: SExpr = "(tell @bob \"hi\")".parse().unwrap();
        let msg = Message::try_from(&sexpr).unwrap();
        assert_eq!(msg.recipient(), Some("@bob"));
        assert_eq!(SExpr::from(&msg), sexpr);
    }

    #[test]
    fn empty_list_stays_content_not_recipient() {
        let sexpr: SExpr = "(tell () :thread \"t\")".parse().unwrap();
        let msg = Message::try_from(&sexpr).unwrap();
        assert!(msg.recipient_set().is_empty());
        assert_eq!(msg.content(), Some(&SExpr::List(Vec::new())));
    }

    #[test]
    fn non_recipient_list_stays_content() {
        let sexpr: SExpr = "(tell (a b) \"x\")".parse().unwrap();
        let msg = Message::try_from(&sexpr).unwrap();
        assert!(msg.recipient_set().is_empty());
    }

    // ---- Addresses are sigil-disciplined: a bare `@`-symbol is an address,
    // never positional content. Found by the role_layer round-trip fuzzer. ----

    fn parses(src: &str) -> bool {
        let sexpr: SExpr = src.parse().unwrap();
        Message::try_from(&sexpr).is_ok()
    }

    fn round_trips(src: &str) {
        let sexpr: SExpr = src.parse().unwrap();
        let msg = Message::try_from(&sexpr).unwrap();
        let back = SExpr::from(&msg);
        let msg2 = Message::try_from(&back).unwrap();
        assert_eq!(msg, msg2, "round-trip must be identity for {src}");
    }

    #[test]
    fn address_group_in_content_position_is_rejected() {
        // Bare address after keyword params, no recipient (fuzzer find #1).
        assert!(!parses("(tell :session \"foo\" @key)"));
        // A second bare address after the recipient.
        assert!(!parses("(reply @alice @bob)"));
        // A bare address in a positional param slot (after content).
        assert!(!parses("(tell @client \"msg\" @extra)"));
        // An all-`@` *list* in the content position collides with the
        // recipient set form `(@a @b)` (fuzzer find #2).
        assert!(!parses("(tell :kw \"v\" (@a @b))"));
        assert!(!parses("(reply @dest (@a @b))"));
        // ...but the same list *leading* is a legitimate recipient set.
        assert!(parses("(tell (@@@))"));
        assert!(parses("(tell (@a @b) \"content\")"));
    }

    #[test]
    fn addresses_in_content_are_fine_when_tagged_or_wrapped() {
        // Keyword value.
        assert!(parses("(tell @client :ref @bob :action \"review\")"));
        round_trips("(tell @client :ref @bob :action \"review\")");
        // Nested inside a structured (list) content.
        assert!(parses("(tell @client (introduce @bob))"));
        round_trips("(tell @client (introduce @bob))");
        // Inside a string literal — just text, not an address token.
        assert!(parses("(tell @client \"ping @bob\")"));
        round_trips("(tell @client \"ping @bob\")");
        // Multicast recipient set + string content (the paper's OAuth trace).
        assert!(parses(
            "(lang oauth (login (@cli @as) \"n-42\" \"profile\"))"
        ));
        round_trips("(lang oauth (login (@cli @as) \"n-42\" \"profile\"))");
    }

    #[test]
    fn two_recipients_must_use_the_set_form() {
        // The nudge: `(@a @b)` is unambiguous; `@a @b` is not (and is rejected).
        assert!(parses("(reply (@alice @bob) \"ok\")"));
        assert!(!parses("(reply @alice @bob \"ok\")"));
    }

    // ---- SPEC-014 REQ-625: with-roles typed wrapper ----

    #[test]
    fn with_roles_parses_as_typed_wrapper() {
        let sexpr: SExpr =
            "(with-roles ((auctioneer @auc) (bidder @b1 @b2)) (signed @auc \"sig\" (hello :thread \"conv-7\" :caused-by begin)))"
                .parse()
                .unwrap();
        let msg = Message::try_from(&sexpr).unwrap();
        let Message::Wrapped {
            wrapper,
            params,
            content,
        } = &msg
        else {
            panic!("with-roles must parse as Wrapped, got {msg:?}");
        };
        assert_eq!(*wrapper, WrapperType::WithRoles);
        assert_eq!(params.len(), 1, "bindings list travels in params");
        // inner signed message carried unchanged
        let Message::Wrapped {
            wrapper: inner_w, ..
        } = content.as_ref()
        else {
            panic!("inner must be the signed wrapper");
        };
        assert_eq!(*inner_w, WrapperType::Signed);
        // round-trip
        let back = SExpr::from(&msg);
        assert_eq!(Message::try_from(&back).unwrap(), msg);
    }

    #[test]
    fn with_roles_bindings_parse_into_cast() {
        use crate::role::{parse_cast, parse_roles};
        let sexpr: SExpr =
            "(with-roles ((auctioneer @auc) (bidder @b1 @b2)) (signed @auc \"sig\" (hello :caused-by begin)))"
                .parse()
                .unwrap();
        let msg = Message::try_from(&sexpr).unwrap();
        let Message::Wrapped { params, .. } = &msg else {
            unreachable!()
        };
        let roles = parse_roles(&"(auctioneer (* bidder))".parse().unwrap()).unwrap();
        let cast = parse_cast(&params[0], &roles).unwrap();
        assert_eq!(cast.indexed.get("bidder").unwrap().len(), 2);
    }

    #[test]
    fn with_roles_dialect_pin_parses_into_cast() {
        // SPEC-014 REQ-628: the optional `:dialect f1220<hex64>` field
        // travels in the wrapper params and lands on `Cast::dialect_pin`.
        use crate::role::{parse_roles, parse_wrapper_cast};
        let pin = alloc::format!("f1220{}", "a".repeat(64));
        let sexpr: SExpr = alloc::format!(
            "(with-roles ((auctioneer @auc) (bidder @b1 @b2)) :dialect {pin} (signed @auc \"sig\" (hello :caused-by begin)))"
        )
        .parse()
        .unwrap();
        let msg = Message::try_from(&sexpr).unwrap();
        let Message::Wrapped { params, .. } = &msg else {
            unreachable!()
        };
        assert_eq!(params.len(), 3, "bindings + :dialect keyword + pin");
        let roles = parse_roles(&"(auctioneer (* bidder))".parse().unwrap()).unwrap();
        let cast = parse_wrapper_cast(params, &roles).unwrap();
        assert_eq!(cast.dialect_pin.as_deref(), Some(pin.as_str()));
        // round-trip preserves the pin
        let back = SExpr::from(&msg);
        assert_eq!(Message::try_from(&back).unwrap(), msg);
    }
}