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
//! Message evaluator: dispatch, template expansion, effect interpretation, thread tracking.
//!
//! The evaluator is a pure function that takes a message and a dialect registry,
//! and returns a result containing the expanded effect form and a list of
//! concrete effects to be applied by the caller (typically an Agent).
//!
//! Evaluation flow by message type:
//! - **Simple**: look up performative → expand template → interpret effect form
//! - **Meta**: produce an `InstallDialect` effect with the dialect definition
//! - **Dialect**: resolve named dialect → evaluate inner message in that scope
//! - **Wrapped**: unwrap and evaluate the inner message

#![forbid(unsafe_code)]

use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;

use crate::dialect::{Dialect, DialectRegistry};
use crate::message::{Message, MessageType, Performative};
use crate::r2::ResourceState;
use crate::sexpr::{Atom, SExpr};
use crate::shape::ShapeViolation;
use crate::template::expand_template;

// ---------------------------------------------------------------------------
// Effect
// ---------------------------------------------------------------------------

/// A concrete effect produced by message evaluation.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Effect {
    /// Send a message to a recipient.
    SendMessage {
        recipient: Option<String>,
        content: SExpr,
    },
    /// Send a query to a recipient.
    SendQuery {
        recipient: Option<String>,
        content: SExpr,
    },
    /// Send a reply.
    SendReply {
        recipient: Option<String>,
        content: SExpr,
    },
    /// Signal an error.
    SignalError { content: SExpr },
    /// Acknowledge receipt.
    Acknowledge,
    /// Cancel a conversation.
    CancelConversation,
    /// Announce agent presence.
    AnnouncePresence,
    /// Announce agent departure.
    AnnounceDeparture,
    /// Store a belief (content of a tell message).
    StoreBelief(SExpr),
    /// Remove a belief.
    RemoveBelief(SExpr),
    /// Install a dialect from a meta message (carries the raw S-expression definition).
    InstallDialect(SExpr),
    /// A custom effect from a dialect-defined performative.
    Custom(SExpr),
}

// ---------------------------------------------------------------------------
// EvalError
// ---------------------------------------------------------------------------

/// Errors that can occur during message evaluation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EvalError {
    /// The performative is not defined in any installed dialect.
    UnknownPerformative(String),
    /// A custom performative was invoked outside any `(lang …)` wrapper, so
    /// the message does not name the dialect that defines it (REQ-033).
    ///
    /// Normally unreachable from parsed input — the recogniser rejects the
    /// form — so this fires for messages built programmatically.
    UnscopedDialectPerformative(String),
    /// Template expansion failed (e.g. resource bounds exceeded, no matching cond branch).
    TemplateExpansionFailed { performative: String },
    /// The named dialect is not installed.
    UnknownDialect(String),
    /// The message is malformed.
    MalformedMessage(String),
    /// The expanded message violates a shape constraint (REQ-223).
    ShapeViolation(ShapeViolation),
}

impl fmt::Display for EvalError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EvalError::UnknownPerformative(name) => {
                write!(f, "unknown performative: {name}")
            }
            EvalError::UnscopedDialectPerformative(name) => {
                write!(
                    f,
                    "dialect performative '{name}' invoked outside (lang <dialect> ...); \
                     the message must name the dialect that defines it"
                )
            }
            EvalError::TemplateExpansionFailed { performative } => {
                write!(
                    f,
                    "template expansion failed for performative: {performative}"
                )
            }
            EvalError::UnknownDialect(name) => {
                write!(f, "unknown dialect: {name}")
            }
            EvalError::MalformedMessage(msg) => {
                write!(f, "malformed message: {msg}")
            }
            EvalError::ShapeViolation(v) => {
                write!(f, "{v}")
            }
        }
    }
}

// ---------------------------------------------------------------------------
// EvalResult
// ---------------------------------------------------------------------------

/// The result of evaluating a message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EvalResult {
    /// The expanded effect form (S-expression from template expansion).
    pub expanded: SExpr,
    /// Concrete effects to be applied.
    pub effects: Vec<Effect>,
    /// Thread ID for conversation tracking, if present on the source message.
    pub thread: Option<String>,
}

// ---------------------------------------------------------------------------
// Core evaluation
// ---------------------------------------------------------------------------

/// Evaluate a message against a dialect registry.
///
/// This is a pure function: it inspects the message, expands templates using
/// the registry, and returns the resulting effects without mutating any state.
/// Performs shape checking inline; for a no-shape variant (used by callers
/// that run shape validation separately with richer blame), see
/// [`evaluate_without_shape_check`].
pub fn evaluate(msg: &Message, registry: &DialectRegistry) -> Result<EvalResult, EvalError> {
    evaluate_with_scope(msg, registry, None, /*check_shape=*/ true)
}

/// Evaluate a message without performing shape validation.
///
/// Used by callers (e.g. the pipeline) that run their own shape check step
/// against the expanded form so they can attach richer blame evidence.
pub fn evaluate_without_shape_check(
    msg: &Message,
    registry: &DialectRegistry,
) -> Result<EvalResult, EvalError> {
    evaluate_with_scope(msg, registry, None, /*check_shape=*/ false)
}

fn evaluate_with_scope(
    msg: &Message,
    registry: &DialectRegistry,
    scope: Option<&Dialect>,
    check_shape: bool,
) -> Result<EvalResult, EvalError> {
    match msg.message_type() {
        MessageType::Simple => evaluate_simple(msg, registry, scope, check_shape),
        MessageType::Meta => evaluate_meta(msg),
        MessageType::Dialect => evaluate_dialect(msg, registry, check_shape),
        MessageType::Wrapped => evaluate_wrapped(msg, registry, scope, check_shape),
    }
}

/// Evaluate a simple message: look up performative, expand template, interpret effects.
fn evaluate_simple(
    msg: &Message,
    registry: &DialectRegistry,
    scope: Option<&Dialect>,
    check_shape: bool,
) -> Result<EvalResult, EvalError> {
    let performative = msg
        .performative()
        .ok_or_else(|| EvalError::MalformedMessage(String::from("missing performative")))?;

    let perf_name = performative.name();

    let dialect = resolve_performative_dialect(performative, registry, scope)?;

    let def = dialect
        .find_performative(perf_name)
        .ok_or_else(|| EvalError::UnknownPerformative(String::from(perf_name)))?;

    // Build arguments from the message content and params.
    let mut args = Vec::new();
    if let Some(content) = msg.content() {
        args.push(content.clone());
    }
    if let Message::Simple { params, .. } = msg {
        args.extend(params.iter().cloned());
    }

    // Expand the template with resource bounds from the dialect.
    let mut rs = ResourceState::initial(&dialect.resources);
    let expanded =
        expand_template(def, &args, &mut rs).ok_or_else(|| EvalError::TemplateExpansionFailed {
            performative: String::from(perf_name),
        })?;

    // Shape checking on expanded message (REQ-223, REQ-224).
    // All shape constraints matching the performative compose via conjunction:
    // every matching constraint must pass.
    if check_shape {
        check_shapes(perf_name, &expanded, registry)?;
    }

    // Interpret the expanded form into concrete effects. A message may now
    // carry a *set* of recipients (SPEC-014 REQ-622); send effects fan out
    // over the set so a multicast is not silently narrowed to one or none.
    let recipients: Vec<String> = msg.recipient_set().into_iter().map(String::from).collect();
    let content = msg.content().cloned().unwrap_or(SExpr::List(Vec::new()));
    let effects = interpret_effects(&expanded, recipients, content, performative);

    Ok(EvalResult {
        expanded,
        effects,
        thread: msg.thread().map(String::from),
    })
}

/// Evaluate a meta message: produce an InstallDialect effect.
fn evaluate_meta(msg: &Message) -> Result<EvalResult, EvalError> {
    let dialect_def = msg.dialect_def().ok_or_else(|| {
        EvalError::MalformedMessage(String::from("meta message missing dialect definition"))
    })?;

    let expanded = SExpr::List(vec![
        SExpr::Atom(Atom::Symbol(String::from("effect"))),
        SExpr::Atom(Atom::Symbol(String::from("install-dialect"))),
    ]);

    Ok(EvalResult {
        expanded: expanded.clone(),
        effects: vec![Effect::InstallDialect(dialect_def.clone())],
        thread: None,
    })
}

/// Evaluate a dialect-scoped message: resolve dialect, then evaluate inner message.
fn evaluate_dialect(
    msg: &Message,
    registry: &DialectRegistry,
    check_shape: bool,
) -> Result<EvalResult, EvalError> {
    let dialect_name = msg
        .dialect_name()
        .ok_or_else(|| EvalError::MalformedMessage(String::from("dialect message missing name")))?;

    let dialect = registry
        .find_by_name(dialect_name)
        .ok_or_else(|| EvalError::UnknownDialect(String::from(dialect_name)))?;

    // Evaluate the inner message (which may use performatives from the named dialect).
    let inner = msg.inner_message().ok_or_else(|| {
        EvalError::MalformedMessage(String::from("dialect message missing inner"))
    })?;

    evaluate_with_scope(inner, registry, Some(dialect), check_shape)
}

/// Evaluate a wrapped message: unwrap and evaluate the inner message.
fn evaluate_wrapped(
    msg: &Message,
    registry: &DialectRegistry,
    scope: Option<&Dialect>,
    check_shape: bool,
) -> Result<EvalResult, EvalError> {
    let inner = msg.inner_message().ok_or_else(|| {
        EvalError::MalformedMessage(String::from("wrapped message missing inner"))
    })?;

    evaluate_with_scope(inner, registry, scope, check_shape)
}

/// Resolve the dialect that defines `performative` (REQ-033).
///
/// A **custom** performative is resolved *only* against the dialect named by
/// its enclosing `(lang …)` wrapper. There is deliberately no fallback to the
/// registry: the dialect is chosen by the message, never by the receiver's
/// installed set, so the same bytes expand identically on every agent that
/// holds the named dialect. This is also what lets two dialects define the
/// same performative name without conflict — the wrapper disambiguates.
///
/// A **core** performative is resolved against the base dialect, which R3
/// guarantees is its only definer.
///
/// The unscoped-custom case is rejected by the recogniser before evaluation
/// (`message.rs`, `LangScope`); it is re-checked here so that programmatically
/// constructed messages, which never passed through the parser, cannot bypass
/// the rule.
fn resolve_performative_dialect<'a>(
    performative: &Performative,
    registry: &'a DialectRegistry,
    scope: Option<&'a Dialect>,
) -> Result<&'a Dialect, EvalError> {
    let name = performative.name();

    if !performative.is_core() {
        let Some(dialect) = scope else {
            return Err(EvalError::UnscopedDialectPerformative(String::from(name)));
        };
        return if dialect.defines_performative(name) {
            Ok(dialect)
        } else {
            Err(EvalError::UnknownPerformative(String::from(name)))
        };
    }

    registry
        .base_definer_of(name)
        .ok_or_else(|| EvalError::UnknownPerformative(String::from(name)))
}

// ---------------------------------------------------------------------------
// Shape checking (REQ-223, REQ-224)
// ---------------------------------------------------------------------------

/// Check all shape constraints for a performative across all installed dialects.
///
/// Multiple constraints compose via conjunction (REQ-224): every matching
/// constraint must pass. This is a VPL tree-walking operation and trivially
/// preserves DCFL membership (REQ-225).
fn check_shapes(
    performative: &str,
    expanded: &SExpr,
    registry: &DialectRegistry,
) -> Result<(), EvalError> {
    for dialect in registry.iter() {
        for shape in &dialect.shapes {
            if shape.performative == performative {
                shape.check(expanded).map_err(EvalError::ShapeViolation)?;
            }
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Effect interpretation
// ---------------------------------------------------------------------------

/// Interpret an expanded template form into concrete effects.
///
/// The base dialect templates expand to `(effect <action>)`. Custom dialect
/// templates may expand to arbitrary S-expressions, which become `Custom` effects.
fn interpret_effects(
    expanded: &SExpr,
    recipients: Vec<String>,
    content: SExpr,
    _performative: &Performative,
) -> Vec<Effect> {
    // One `Option<String>` recipient per addressed target; an empty set
    // yields a single `None` (unaddressed) effect, preserving the
    // pre-SPEC-014 no-recipient behaviour. A multicast fans out into one
    // send effect per recipient (canonical sorted order via `recipient_set`).
    let targets: Vec<Option<String>> = if recipients.is_empty() {
        vec![None]
    } else {
        recipients.into_iter().map(Some).collect()
    };

    // Check for (effect <action>) form.
    if let Some(action) = extract_effect_action(expanded) {
        return match action.as_str() {
            "send-message" => {
                // A tell sends to each recipient and stores the content as a
                // belief once (the belief is about the content, not a target).
                let mut effects: Vec<Effect> = targets
                    .into_iter()
                    .map(|recipient| Effect::SendMessage {
                        recipient,
                        content: content.clone(),
                    })
                    .collect();
                effects.push(Effect::StoreBelief(content));
                effects
            }
            "send-query" => targets
                .into_iter()
                .map(|recipient| Effect::SendQuery {
                    recipient,
                    content: content.clone(),
                })
                .collect(),
            "send-reply" => targets
                .into_iter()
                .map(|recipient| Effect::SendReply {
                    recipient,
                    content: content.clone(),
                })
                .collect(),
            "signal-error" => vec![Effect::SignalError { content }],
            "acknowledge" => vec![Effect::Acknowledge],
            "cancel-conversation" => vec![Effect::CancelConversation],
            "announce-presence" => vec![Effect::AnnouncePresence],
            "announce-departure" => vec![Effect::AnnounceDeparture],
            _ => vec![Effect::Custom(expanded.clone())],
        };
    }

    // Not an (effect ...) form — treat as a custom effect from a dialect template.
    vec![Effect::Custom(expanded.clone())]
}

/// Extract the action name from an `(effect <action>)` form.
fn extract_effect_action(expr: &SExpr) -> Option<String> {
    if let SExpr::List(items) = expr {
        if items.len() == 2 && items[0].is_symbol("effect") {
            if let SExpr::Atom(Atom::Symbol(action)) = &items[1] {
                return Some(action.clone());
            }
        }
    }
    None
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dialect::{Dialect, PerformativeDef, ResourceBounds};
    use crate::message::{CorePerformative, WrapperType};
    use alloc::boxed::Box;

    fn make_registry() -> DialectRegistry {
        DialectRegistry::new()
    }

    fn make_registry_with_custom() -> DialectRegistry {
        let mut reg = DialectRegistry::new();
        reg.install(Dialect {
            types: Default::default(),
            roles: Vec::new(),
            state: None,
            state_bounds: None,
            causal_locality: Default::default(),
            name: String::from("logistics"),
            extends: vec![String::from("cbcl")],
            author: None,
            performatives: vec![PerformativeDef {
                role: None,
                name: String::from("ship"),
                params: vec![
                    SExpr::Atom(Atom::Symbol(String::from("package"))),
                    SExpr::Atom(Atom::Symbol(String::from("destination"))),
                ],
                template: SExpr::List(vec![
                    SExpr::Atom(Atom::Symbol(String::from("effect"))),
                    SExpr::Atom(Atom::Symbol(String::from("dispatch-shipment"))),
                ]),
            }],
            resources: ResourceBounds {
                max_depth: 8,
                max_expansion_size: 512,
            },
            examples: Vec::new(),
            signature: None,
            hash: None,
            protocol: None,
            causal_protocol: None,
            shapes: Vec::new(),
        })
        .unwrap();
        reg
    }

    fn make_registry_with_duplicate_customs() -> DialectRegistry {
        let mut reg = make_registry_with_custom();
        reg.install(Dialect {
            types: Default::default(),
            roles: Vec::new(),
            state: None,
            state_bounds: None,
            causal_locality: Default::default(),
            name: String::from("warehouse"),
            extends: vec![String::from("cbcl")],
            author: None,
            performatives: vec![PerformativeDef {
                role: None,
                name: String::from("ship"),
                params: vec![
                    SExpr::Atom(Atom::Symbol(String::from("package"))),
                    SExpr::Atom(Atom::Symbol(String::from("destination"))),
                ],
                template: SExpr::List(vec![
                    SExpr::Atom(Atom::Symbol(String::from("effect"))),
                    SExpr::Atom(Atom::Symbol(String::from("warehouse-dispatch"))),
                ]),
            }],
            resources: ResourceBounds {
                max_depth: 8,
                max_expansion_size: 512,
            },
            examples: Vec::new(),
            signature: None,
            hash: None,
            protocol: None,
            causal_protocol: None,
            shapes: Vec::new(),
        })
        .unwrap();
        reg
    }

    // -- Simple message evaluation --

    #[test]
    fn eval_tell_produces_send_message_and_store_belief() {
        let reg = make_registry();
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Tell),
            recipient: Some("@bob".into()),
            content: SExpr::Atom(Atom::Str(String::from("hello"))),
            params: Vec::new(),
            thread: None,
            sender: None,
            caused_by: None,
        };
        let result = evaluate(&msg, &reg).unwrap();
        assert_eq!(result.effects.len(), 2);
        assert_eq!(
            result.effects[0],
            Effect::SendMessage {
                recipient: Some("@bob".into()),
                content: SExpr::Atom(Atom::Str(String::from("hello"))),
            }
        );
        assert_eq!(
            result.effects[1],
            Effect::StoreBelief(SExpr::Atom(Atom::Str(String::from("hello")))),
        );
        // Expanded form is (effect send-message)
        assert!(!result.expanded.is_symbol("effect"));
        assert!(extract_effect_action(&result.expanded) == Some(String::from("send-message")));
    }

    #[test]
    fn eval_multicast_tell_fans_out_to_every_recipient() {
        // SPEC-014 REQ-622: a recipient set must not be silently dropped.
        let reg = make_registry();
        let msg = Message::try_from(
            &"(tell (@a @b) \"hi\")"
                .parse::<crate::sexpr::SExpr>()
                .unwrap(),
        )
        .unwrap();
        let result = evaluate(&msg, &reg).unwrap();
        // one SendMessage per recipient (canonical sorted) + one StoreBelief
        let sends: Vec<&Effect> = result
            .effects
            .iter()
            .filter(|e| matches!(e, Effect::SendMessage { .. }))
            .collect();
        assert_eq!(sends.len(), 2, "multicast fans out to both recipients");
        let recipients: alloc::collections::BTreeSet<String> = result
            .effects
            .iter()
            .filter_map(|e| match e {
                Effect::SendMessage {
                    recipient: Some(r), ..
                } => Some(r.clone()),
                _ => None,
            })
            .collect();
        assert!(recipients.contains("@a") && recipients.contains("@b"));
        assert_eq!(
            result
                .effects
                .iter()
                .filter(|e| matches!(e, Effect::StoreBelief(_)))
                .count(),
            1,
            "content stored as a belief once"
        );
    }

    #[test]
    fn eval_ask_produces_send_query() {
        let reg = make_registry();
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Ask),
            recipient: Some("@alice".into()),
            content: SExpr::Atom(Atom::Str(String::from("what time?"))),
            params: Vec::new(),
            thread: None,
            sender: None,
            caused_by: None,
        };
        let result = evaluate(&msg, &reg).unwrap();
        assert_eq!(result.effects.len(), 1);
        assert_eq!(
            result.effects[0],
            Effect::SendQuery {
                recipient: Some("@alice".into()),
                content: SExpr::Atom(Atom::Str(String::from("what time?"))),
            }
        );
    }

    #[test]
    fn eval_reply_produces_send_reply() {
        let reg = make_registry();
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Reply),
            recipient: None,
            content: SExpr::Atom(Atom::Str(String::from("done"))),
            params: Vec::new(),
            thread: Some(String::from("conv-1")),
            sender: None,
            caused_by: None,
        };
        let result = evaluate(&msg, &reg).unwrap();
        assert_eq!(result.effects.len(), 1);
        assert_eq!(
            result.effects[0],
            Effect::SendReply {
                recipient: None,
                content: SExpr::Atom(Atom::Str(String::from("done"))),
            }
        );
        assert_eq!(result.thread, Some(String::from("conv-1")));
    }

    #[test]
    fn eval_error_produces_signal_error() {
        let reg = make_registry();
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Error),
            recipient: None,
            content: SExpr::Atom(Atom::Str(String::from("fail"))),
            params: Vec::new(),
            thread: None,
            sender: None,
            caused_by: None,
        };
        let result = evaluate(&msg, &reg).unwrap();
        assert_eq!(
            result.effects[0],
            Effect::SignalError {
                content: SExpr::Atom(Atom::Str(String::from("fail"))),
            }
        );
    }

    #[test]
    fn eval_ok_produces_acknowledge() {
        let reg = make_registry();
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Ok),
            recipient: None,
            content: SExpr::List(Vec::new()),
            params: Vec::new(),
            thread: None,
            sender: None,
            caused_by: None,
        };
        let result = evaluate(&msg, &reg).unwrap();
        assert_eq!(result.effects[0], Effect::Acknowledge);
    }

    #[test]
    fn eval_cancel_produces_cancel_conversation() {
        let reg = make_registry();
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Cancel),
            recipient: None,
            content: SExpr::List(Vec::new()),
            params: Vec::new(),
            thread: Some(String::from("conv-2")),
            sender: None,
            caused_by: None,
        };
        let result = evaluate(&msg, &reg).unwrap();
        assert_eq!(result.effects[0], Effect::CancelConversation);
        assert_eq!(result.thread, Some(String::from("conv-2")));
    }

    #[test]
    fn eval_hello_produces_announce_presence() {
        let reg = make_registry();
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Hello),
            recipient: None,
            content: SExpr::List(Vec::new()),
            params: Vec::new(),
            thread: None,
            sender: None,
            caused_by: None,
        };
        let result = evaluate(&msg, &reg).unwrap();
        assert_eq!(result.effects[0], Effect::AnnouncePresence);
    }

    #[test]
    fn eval_bye_produces_announce_departure() {
        let reg = make_registry();
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Bye),
            recipient: None,
            content: SExpr::List(Vec::new()),
            params: Vec::new(),
            thread: None,
            sender: None,
            caused_by: None,
        };
        let result = evaluate(&msg, &reg).unwrap();
        assert_eq!(result.effects[0], Effect::AnnounceDeparture);
    }

    #[test]
    fn eval_unknown_performative_errors() {
        let reg = make_registry();
        let msg = Message::Simple {
            performative: Performative::Custom(String::from("nonexistent")),
            recipient: None,
            content: SExpr::List(Vec::new()),
            params: Vec::new(),
            thread: None,
            sender: None,
            caused_by: None,
        };
        let msg = Message::Dialect {
            dialect_name: String::from("cbcl-base"),
            inner: alloc::boxed::Box::new(msg),
        };
        let err = evaluate(&msg, &reg).unwrap_err();
        assert!(matches!(err, EvalError::UnknownPerformative(_)));
    }

    // -- Custom dialect performative --

    #[test]
    fn eval_custom_performative() {
        let reg = make_registry_with_custom();
        let msg = Message::Simple {
            performative: Performative::Custom(String::from("ship")),
            recipient: None,
            content: SExpr::Atom(Atom::Str(String::from("PKG-123"))),
            params: vec![SExpr::Atom(Atom::Symbol(String::from("warehouse-A")))],
            thread: None,
            sender: None,
            caused_by: None,
        };
        let msg = Message::Dialect {
            dialect_name: String::from("logistics"),
            inner: alloc::boxed::Box::new(msg),
        };
        let result = evaluate(&msg, &reg).unwrap();
        // Template expands to (effect dispatch-shipment) — a custom effect action
        assert_eq!(
            extract_effect_action(&result.expanded),
            Some(String::from("dispatch-shipment"))
        );
        assert_eq!(result.effects.len(), 1);
        assert_eq!(result.effects[0], Effect::Custom(result.expanded.clone()));
    }

    // -- Meta message evaluation --

    #[test]
    fn eval_meta_produces_install_dialect() {
        let reg = make_registry();
        let dialect_def = SExpr::List(vec![
            SExpr::Atom(Atom::Symbol(String::from("define"))),
            SExpr::Atom(Atom::Symbol(String::from("test-dialect"))),
        ]);
        let msg = Message::Meta {
            dialect_def: dialect_def.clone(),
        };
        let result = evaluate(&msg, &reg).unwrap();
        assert_eq!(result.effects.len(), 1);
        assert_eq!(result.effects[0], Effect::InstallDialect(dialect_def));
    }

    // -- Dialect message evaluation --

    #[test]
    fn eval_dialect_message_delegates_to_inner() {
        let reg = make_registry_with_custom();
        let inner = Message::Simple {
            performative: Performative::Custom(String::from("ship")),
            recipient: None,
            content: SExpr::Atom(Atom::Str(String::from("PKG-456"))),
            params: vec![SExpr::Atom(Atom::Symbol(String::from("depot-B")))],
            thread: Some(String::from("shipment-thread")),
            sender: None,
            caused_by: None,
        };
        let msg = Message::Dialect {
            dialect_name: String::from("logistics"),
            inner: Box::new(inner),
        };
        let result = evaluate(&msg, &reg).unwrap();
        assert_eq!(
            extract_effect_action(&result.expanded),
            Some(String::from("dispatch-shipment"))
        );
        assert_eq!(result.thread, Some(String::from("shipment-thread")));
    }

    #[test]
    fn eval_dialect_message_uses_named_scope_for_custom_performatives() {
        let reg = make_registry_with_duplicate_customs();
        let inner = Message::Simple {
            performative: Performative::Custom(String::from("ship")),
            recipient: None,
            content: SExpr::Atom(Atom::Str(String::from("PKG-789"))),
            params: vec![SExpr::Atom(Atom::Symbol(String::from("dock-C")))],
            thread: None,
            sender: None,
            caused_by: None,
        };
        let msg = Message::Dialect {
            dialect_name: String::from("logistics"),
            inner: Box::new(inner),
        };

        let result = evaluate(&msg, &reg).unwrap();
        assert_eq!(
            extract_effect_action(&result.expanded),
            Some(String::from("dispatch-shipment"))
        );
    }

    #[test]
    fn eval_dialect_message_rejects_custom_performative_outside_scope() {
        let reg = make_registry_with_duplicate_customs();
        let inner = Message::Simple {
            performative: Performative::Custom(String::from("ship")),
            recipient: None,
            content: SExpr::Atom(Atom::Str(String::from("PKG-000"))),
            params: vec![SExpr::Atom(Atom::Symbol(String::from("dock-D")))],
            thread: None,
            sender: None,
            caused_by: None,
        };
        let msg = Message::Dialect {
            dialect_name: String::from("cbcl-base"),
            inner: Box::new(inner),
        };

        let err = evaluate(&msg, &reg).unwrap_err();
        assert!(matches!(err, EvalError::UnknownPerformative(_)));
    }

    /// Build an unscoped invocation of the duplicated `ship` performative.
    fn unscoped_ship() -> Message {
        Message::Simple {
            performative: Performative::Custom(String::from("ship")),
            recipient: None,
            content: SExpr::Atom(Atom::Str(String::from("PKG-789"))),
            params: vec![SExpr::Atom(Atom::Symbol(String::from("dock-C")))],
            thread: None,
            sender: None,
            caused_by: None,
        }
    }

    /// REQ-033: the same unscoped invocation is refused whatever the
    /// registry holds — the message never names a dialect, so no installed
    /// set can supply one.
    #[test]
    fn eval_unscoped_custom_performative_is_rejected() {
        for reg in [
            make_registry_with_custom(),
            make_registry_with_duplicate_customs(),
        ] {
            match evaluate(&unscoped_ship(), &reg).unwrap_err() {
                EvalError::UnscopedDialectPerformative(name) => assert_eq!(name, "ship"),
                other => panic!("expected UnscopedDialectPerformative, got {other:?}"),
            }
        }
    }

    /// Scoping is how a dialect performative is invoked at all — and two
    /// dialects defining one name is fine, because the wrapper chooses.
    #[test]
    fn eval_scoping_resolves_an_otherwise_ambiguous_performative() {
        let reg = make_registry_with_duplicate_customs();
        for name in ["logistics", "warehouse"] {
            let msg = Message::Dialect {
                dialect_name: String::from(name),
                inner: Box::new(unscoped_ship()),
            };
            assert!(
                evaluate(&msg, &reg).is_ok(),
                "scoped invocation to '{name}' must resolve"
            );
        }
    }

    #[test]
    fn scoped_resolution_preserves_wrapper_scope_and_install_order() {
        let forward = make_registry_with_duplicate_customs();
        let mut reverse = DialectRegistry::new();
        for name in ["warehouse", "logistics"] {
            reverse
                .install(forward.find_by_name(name).unwrap().clone())
                .unwrap();
        }
        for input in [
            "(lang logistics (ship parcel dock))",
            "(lang logistics (signed signature (ship parcel dock)))",
            "(signed signature (lang logistics (ship parcel dock)))",
            "(lang warehouse (lang logistics (ship parcel dock)))",
        ] {
            let msg = Message::try_from(&input.parse::<SExpr>().unwrap()).unwrap();
            let a = evaluate(&msg, &forward).unwrap();
            let b = evaluate(&msg, &reverse).unwrap();
            assert_eq!(a.expanded, b.expanded, "{input}");
            assert_eq!(
                extract_effect_action(&a.expanded).as_deref(),
                Some("dispatch-shipment")
            );
        }
        let msg = Message::try_from(
            &"(lang logistics (tell @bob parcel))"
                .parse::<SExpr>()
                .unwrap(),
        )
        .unwrap();
        assert_eq!(
            extract_effect_action(&evaluate(&msg, &reverse).unwrap().expanded).as_deref(),
            Some("send-message")
        );
    }

    #[test]
    fn eval_dialect_unknown_dialect_errors() {
        let reg = make_registry();
        let inner = Message::Simple {
            performative: Performative::Core(CorePerformative::Tell),
            recipient: None,
            content: SExpr::Atom(Atom::Str(String::from("hi"))),
            params: Vec::new(),
            thread: None,
            sender: None,
            caused_by: None,
        };
        let msg = Message::Dialect {
            dialect_name: String::from("nonexistent"),
            inner: Box::new(inner),
        };
        let err = evaluate(&msg, &reg).unwrap_err();
        assert!(matches!(err, EvalError::UnknownDialect(_)));
    }

    // -- Wrapped message evaluation --

    #[test]
    fn eval_wrapped_evaluates_inner() {
        let reg = make_registry();
        let inner = Message::Simple {
            performative: Performative::Core(CorePerformative::Tell),
            recipient: Some("@bob".into()),
            content: SExpr::Atom(Atom::Str(String::from("secret"))),
            params: Vec::new(),
            thread: None,
            sender: None,
            caused_by: None,
        };
        let msg = Message::Wrapped {
            wrapper: WrapperType::Envelope,
            params: vec![
                SExpr::Atom(Atom::Keyword(String::from("from"))),
                SExpr::Atom(Atom::Symbol(String::from("@alice"))),
            ],
            content: Box::new(inner),
        };
        let result = evaluate(&msg, &reg).unwrap();
        assert_eq!(
            extract_effect_action(&result.expanded),
            Some(String::from("send-message"))
        );
        assert_eq!(result.effects.len(), 2); // SendMessage + StoreBelief
    }

    // -- Thread tracking --

    #[test]
    fn eval_preserves_thread_id() {
        let reg = make_registry();
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Tell),
            recipient: Some("@bob".into()),
            content: SExpr::Atom(Atom::Str(String::from("hi"))),
            params: Vec::new(),
            thread: Some(String::from("thread-42")),
            sender: None,
            caused_by: None,
        };
        let result = evaluate(&msg, &reg).unwrap();
        assert_eq!(result.thread, Some(String::from("thread-42")));
    }

    #[test]
    fn eval_no_thread_when_absent() {
        let reg = make_registry();
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Tell),
            recipient: None,
            content: SExpr::Atom(Atom::Str(String::from("hi"))),
            params: Vec::new(),
            thread: None,
            sender: None,
            caused_by: None,
        };
        let result = evaluate(&msg, &reg).unwrap();
        assert!(result.thread.is_none());
    }

    // -- EvalError Display --

    #[test]
    fn eval_error_display() {
        let e1 = EvalError::UnknownPerformative(String::from("foo"));
        assert!(alloc::format!("{e1}").contains("foo"));

        let e2 = EvalError::TemplateExpansionFailed {
            performative: String::from("bar"),
        };
        assert!(alloc::format!("{e2}").contains("bar"));

        let e3 = EvalError::UnknownDialect(String::from("baz"));
        assert!(alloc::format!("{e3}").contains("baz"));

        let e4 = EvalError::MalformedMessage(String::from("oops"));
        assert!(alloc::format!("{e4}").contains("oops"));
    }

    // -- extract_effect_action helper --

    #[test]
    fn extract_effect_action_valid() {
        let expr: SExpr = "(effect send-message)".parse().unwrap();
        assert_eq!(
            extract_effect_action(&expr),
            Some(String::from("send-message"))
        );
    }

    #[test]
    fn extract_effect_action_non_effect() {
        let expr: SExpr = "(tell @bob \"hi\")".parse().unwrap();
        assert_eq!(extract_effect_action(&expr), None);
    }

    #[test]
    fn extract_effect_action_atom() {
        let expr: SExpr = "hello".parse().unwrap();
        assert_eq!(extract_effect_action(&expr), None);
    }

    // -- Shape checking integration (REQ-223, REQ-224, REQ-225) --

    use crate::shape::{ShapeConstraint, ShapeRule, TypeConstraint};

    fn make_registry_with_shape() -> DialectRegistry {
        let mut reg = DialectRegistry::new();
        // Template: (ship-effect :package <pkg> :dest <dst>)
        // Params bind: pkg = args[0], dst = args[1]
        reg.install(Dialect {
            types: Default::default(),
            roles: Vec::new(),
            state: None,
            state_bounds: None,
            causal_locality: Default::default(),
            name: String::from("logistics"),
            extends: vec![String::from("cbcl")],
            author: None,
            performatives: vec![PerformativeDef {
                role: None,
                name: String::from("ship"),
                params: vec![
                    SExpr::Atom(Atom::Symbol(String::from("pkg"))),
                    SExpr::Atom(Atom::Symbol(String::from("dst"))),
                ],
                template: SExpr::List(vec![
                    SExpr::Atom(Atom::Symbol(String::from("ship-effect"))),
                    SExpr::Atom(Atom::Keyword(String::from("package"))),
                    SExpr::Atom(Atom::Symbol(String::from("pkg"))),
                    SExpr::Atom(Atom::Keyword(String::from("dest"))),
                    SExpr::Atom(Atom::Symbol(String::from("dst"))),
                ]),
            }],
            resources: ResourceBounds {
                max_depth: 8,
                max_expansion_size: 512,
            },
            examples: Vec::new(),
            signature: None,
            hash: None,
            protocol: None,
            causal_protocol: None,
            shapes: vec![ShapeConstraint {
                performative: String::from("ship"),
                rules: vec![
                    ShapeRule::Require {
                        keyword: String::from("package"),
                        type_constraint: Some(TypeConstraint::String),
                        children: vec![],
                    },
                    ShapeRule::Require {
                        keyword: String::from("dest"),
                        type_constraint: Some(TypeConstraint::String),
                        children: vec![],
                    },
                ],
            }],
        })
        .unwrap();
        reg
    }

    #[test]
    fn shape_check_passes_when_satisfied() {
        let reg = make_registry_with_shape();
        let msg = Message::Simple {
            performative: Performative::Custom(String::from("ship")),
            recipient: None,
            content: SExpr::Atom(Atom::Str(String::from("PKG-1"))),
            params: vec![SExpr::Atom(Atom::Str(String::from("warehouse-A")))],
            thread: None,
            sender: None,
            caused_by: None,
        };
        let msg = Message::Dialect {
            dialect_name: String::from("logistics"),
            inner: alloc::boxed::Box::new(msg),
        };
        let result = evaluate(&msg, &reg);
        assert!(result.is_ok());
    }

    #[test]
    fn shape_check_fails_when_type_mismatch() {
        let reg = make_registry_with_shape();
        // Pass a number where string is expected for :package
        let msg = Message::Simple {
            performative: Performative::Custom(String::from("ship")),
            recipient: None,
            content: SExpr::Atom(Atom::Num(42)),
            params: vec![SExpr::Atom(Atom::Str(String::from("warehouse-A")))],
            thread: None,
            sender: None,
            caused_by: None,
        };
        let msg = Message::Dialect {
            dialect_name: String::from("logistics"),
            inner: alloc::boxed::Box::new(msg),
        };
        let result = evaluate(&msg, &reg);
        match result {
            Err(EvalError::ShapeViolation(v)) => {
                assert!(v.detail.contains(":package"));
            }
            other => panic!("expected ShapeViolation, got {:?}", other),
        }
    }

    #[test]
    fn shape_check_no_shapes_passes() {
        // Base dialect has no shapes — core performatives should pass
        let reg = make_registry();
        let msg = Message::Simple {
            performative: Performative::Core(CorePerformative::Tell),
            recipient: Some("@bob".into()),
            content: SExpr::Atom(Atom::Str(String::from("hello"))),
            params: Vec::new(),
            thread: None,
            sender: None,
            caused_by: None,
        };
        assert!(evaluate(&msg, &reg).is_ok());
    }

    #[test]
    fn shape_conjunction_both_must_pass() {
        // Two shape constraints on same performative compose via conjunction (REQ-224)
        let mut reg = DialectRegistry::new();
        reg.install(Dialect {
            types: Default::default(),
            roles: Vec::new(),
            state: None,
            state_bounds: None,
            causal_locality: Default::default(),
            name: String::from("logistics"),
            extends: vec![String::from("cbcl")],
            author: None,
            performatives: vec![PerformativeDef {
                role: None,
                name: String::from("ship"),
                params: vec![
                    SExpr::Atom(Atom::Symbol(String::from("pkg"))),
                    SExpr::Atom(Atom::Symbol(String::from("dst"))),
                ],
                template: SExpr::List(vec![
                    SExpr::Atom(Atom::Symbol(String::from("ship-effect"))),
                    SExpr::Atom(Atom::Keyword(String::from("package"))),
                    SExpr::Atom(Atom::Symbol(String::from("pkg"))),
                    SExpr::Atom(Atom::Keyword(String::from("dest"))),
                    SExpr::Atom(Atom::Symbol(String::from("dst"))),
                ]),
            }],
            resources: ResourceBounds {
                max_depth: 8,
                max_expansion_size: 512,
            },
            examples: Vec::new(),
            signature: None,
            hash: None,
            protocol: None,
            causal_protocol: None,
            shapes: vec![
                // First shape: require :package string
                ShapeConstraint {
                    performative: String::from("ship"),
                    rules: vec![ShapeRule::Require {
                        keyword: String::from("package"),
                        type_constraint: Some(TypeConstraint::String),
                        children: vec![],
                    }],
                },
                // Second shape: require :dest string
                ShapeConstraint {
                    performative: String::from("ship"),
                    rules: vec![ShapeRule::Require {
                        keyword: String::from("dest"),
                        type_constraint: Some(TypeConstraint::String),
                        children: vec![],
                    }],
                },
            ],
        })
        .unwrap();

        // Message that satisfies both shapes
        let msg = Message::Simple {
            performative: Performative::Custom(String::from("ship")),
            recipient: None,
            content: SExpr::Atom(Atom::Str(String::from("PKG-1"))),
            params: vec![SExpr::Atom(Atom::Str(String::from("warehouse-A")))],
            thread: None,
            sender: None,
            caused_by: None,
        };
        let msg = Message::Dialect {
            dialect_name: String::from("logistics"),
            inner: alloc::boxed::Box::new(msg),
        };
        assert!(evaluate(&msg, &reg).is_ok());
    }

    #[test]
    fn shape_check_max_depth() {
        let mut reg = DialectRegistry::new();
        reg.install(Dialect {
            types: Default::default(),
            roles: Vec::new(),
            state: None,
            state_bounds: None,
            causal_locality: Default::default(),
            name: String::from("shallow"),
            extends: vec![String::from("cbcl")],
            author: None,
            performatives: vec![PerformativeDef {
                role: None,
                name: String::from("nest"),
                params: vec![],
                // Template that expands to deeply nested structure
                template: SExpr::List(vec![
                    SExpr::Atom(Atom::Symbol(String::from("nested"))),
                    SExpr::List(vec![
                        SExpr::Atom(Atom::Symbol(String::from("deep"))),
                        SExpr::List(vec![SExpr::Atom(Atom::Symbol(String::from("deeper")))]),
                    ]),
                ]),
            }],
            resources: ResourceBounds {
                max_depth: 8,
                max_expansion_size: 512,
            },
            examples: Vec::new(),
            signature: None,
            hash: None,
            protocol: None,
            causal_protocol: None,
            shapes: vec![ShapeConstraint {
                performative: String::from("nest"),
                rules: vec![ShapeRule::MaxDepth(1)],
            }],
        })
        .unwrap();

        let msg = Message::Simple {
            performative: Performative::Custom(String::from("nest")),
            recipient: None,
            content: SExpr::List(Vec::new()),
            params: vec![],
            thread: None,
            sender: None,
            caused_by: None,
        };
        let msg = Message::Dialect {
            dialect_name: String::from("shallow"),
            inner: alloc::boxed::Box::new(msg),
        };
        let result = evaluate(&msg, &reg);
        match result {
            Err(EvalError::ShapeViolation(v)) => {
                assert!(v.detail.contains("exceeds"));
            }
            other => panic!("expected ShapeViolation for max-depth, got {:?}", other),
        }
    }

    #[test]
    fn shape_violation_display() {
        let v = ShapeViolation {
            rule: String::from("require :x"),
            field: Some(String::from(":x")),
            expected: Some(String::from("present")),
            found: Some(String::from("missing")),
            detail: String::from("required parameter :x is missing"),
        };
        let err = EvalError::ShapeViolation(v);
        let msg = alloc::format!("{err}");
        assert!(msg.contains("shape violation"));
        assert!(msg.contains(":x"));
    }
}