cbcl-core 0.3.0

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
//! Structural shape constraints for dialect messages (REQ-220, REQ-223, REQ-224).
//!
//! Shape constraints declare the required structure of expanded messages:
//! which keyword parameters must or may be present, their expected atom types,
//! and maximum nesting depth.
//!
//! Shape checking is monotonic — it is a positive assertion about the structure
//! of an immutable S-expression. VPL ⊂ DCFL (Alur & Madhusudan 2004).

#![forbid(unsafe_code)]

use crate::sexpr::{Atom, SExpr};
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt;

/// Recognised type constraints for shape rules (REQ-221, SPEC-038 CON-3801).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TypeConstraint {
    String,
    /// Canonical host-supplied hybrid logical clock evidence, encoded as a string.
    Hlc,
    Integer,
    Number,
    Contract(crate::contracts::Contract),
    Float,
    Decimal,
    /// Integer >= 0, recognized before admission (SPEC-038 ADR-3805).
    Nonnegative,
    Bool,
    Symbol,
    Keyword,
    List,
}

impl TypeConstraint {
    /// Parse a type constraint from a symbol name.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<TypeConstraint> {
        match s {
            "string" => Some(TypeConstraint::String),
            "hlc" => Some(TypeConstraint::Hlc),
            "float" => Some(TypeConstraint::Float),
            "decimal" => Some(TypeConstraint::Decimal),
            "integer" => Some(TypeConstraint::Integer),
            "number" => Some(TypeConstraint::Number),
            "nonnegative" => Some(TypeConstraint::Nonnegative),
            "bool" => Some(TypeConstraint::Bool),
            "symbol" => Some(TypeConstraint::Symbol),
            "keyword" => Some(TypeConstraint::Keyword),
            "list" => Some(TypeConstraint::List),
            _ => None,
        }
    }

    pub fn check(&self, value: &SExpr, work: u64) -> Result<(), crate::contracts::CheckError> {
        if work == 0 || !crate::contracts::input_fits(value) {
            return Err(crate::contracts::CheckError::ResourceLimit);
        }
        if let Self::Contract(c) = self {
            return c.check(value, work);
        }
        if self.matches_builtin(value) {
            Ok(())
        } else {
            Err(crate::contracts::CheckError::Violation(alloc::format!(
                "expected {self}; found {}",
                describe_type(value)
            )))
        }
    }
    pub(crate) fn resource_detail(&self, value: &SExpr, available: u64) -> String {
        let required = match self {
            Self::Contract(c) => c.required_work().unwrap_or(1),
            _ => 1,
        };
        if available < required {
            return alloc::format!(
                "resource-limit: work requires {required} units; available {available}"
            );
        }
        match crate::contracts::check_input(value) {
            Err(reason) => alloc::format!("resource-limit: {reason}"),
            Ok(()) => String::from("resource-limit"),
        }
    }
    pub fn representation(&self) -> Option<Self> {
        if let Self::Contract(c) = self {
            c.representation().or_else(|| Some(self.clone()))
        } else {
            Some(self.clone())
        }
    }
    pub fn source(&self) -> SExpr {
        if let Self::Contract(c) = self {
            c.source().clone()
        } else {
            SExpr::Atom(Atom::Symbol(self.to_string()))
        }
    }

    /// Check whether an S-expression satisfies this type constraint.
    pub(crate) fn matches_builtin(&self, sexpr: &SExpr) -> bool {
        if *self == TypeConstraint::Hlc {
            return matches!(sexpr, SExpr::Atom(Atom::Str(text)) if crate::hlc::Hlc::parse(text).is_some());
        }
        if *self == TypeConstraint::Nonnegative {
            return matches!(sexpr, SExpr::Atom(Atom::Num(n)) if *n >= 0);
        }
        matches!(
            (self, sexpr),
            (TypeConstraint::String, SExpr::Atom(Atom::Str(_)))
                | (
                    TypeConstraint::Integer | TypeConstraint::Number,
                    SExpr::Atom(Atom::Num(_))
                )
                | (
                    TypeConstraint::Number,
                    SExpr::Atom(Atom::Float(_) | Atom::Decimal(_))
                )
                | (TypeConstraint::Float, SExpr::Atom(Atom::Float(_)))
                | (TypeConstraint::Decimal, SExpr::Atom(Atom::Decimal(_)))
                | (TypeConstraint::Bool, SExpr::Atom(Atom::Bool(_)))
                | (TypeConstraint::Symbol, SExpr::Atom(Atom::Symbol(_)))
                | (TypeConstraint::Keyword, SExpr::Atom(Atom::Keyword(_)))
                | (TypeConstraint::List, SExpr::List(_))
        )
    }
}

#[cfg(test)]
mod nonnegative_tests {
    use super::*;

    #[test]
    fn nonnegative_recognizes_only_unsigned_integer_values() {
        let ty = TypeConstraint::from_str("nonnegative").unwrap();
        for value in [0, 1, i64::MAX] {
            assert!(ty.matches_builtin(&SExpr::Atom(Atom::Num(value))));
        }
        for value in [i64::MIN, -1] {
            assert!(!ty.matches_builtin(&SExpr::Atom(Atom::Num(value))));
        }
        assert!(!ty.matches_builtin(&SExpr::Atom(Atom::Bool(true))));
        assert!(!ty.matches_builtin(&SExpr::Atom(Atom::Str("0".into()))));
        assert!(!ty.matches_builtin(&SExpr::List(Vec::new())));
        assert_eq!(ty.to_string(), "nonnegative");
    }
}

impl fmt::Display for TypeConstraint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            TypeConstraint::String => "string",
            TypeConstraint::Hlc => "hlc",
            TypeConstraint::Float => "float",
            TypeConstraint::Decimal => "decimal",
            TypeConstraint::Integer => "integer",
            TypeConstraint::Contract(c) => return write!(f, "{}", c.source()),
            TypeConstraint::Number => "number",
            TypeConstraint::Nonnegative => "nonnegative",
            TypeConstraint::Bool => "bool",
            TypeConstraint::Symbol => "symbol",
            TypeConstraint::Keyword => "keyword",
            TypeConstraint::List => "list",
        };
        f.write_str(s)
    }
}

/// A single shape rule within a shape constraint (REQ-221).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ShapeRule {
    /// A required keyword parameter.
    Require {
        keyword: String,
        type_constraint: Option<TypeConstraint>,
        children: Vec<ShapeRule>,
    },
    /// An optional keyword parameter with an optional default value.
    Optional {
        keyword: String,
        type_constraint: Option<TypeConstraint>,
        default: Option<SExpr>,
        children: Vec<ShapeRule>,
    },
    /// Maximum nesting depth for the message.
    MaxDepth(u32),
}

/// A shape constraint for a performative (REQ-220).
///
/// Declares the required structure of expanded messages for a specific
/// performative. Multiple shape constraints on the same performative
/// compose via conjunction (REQ-224).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ShapeConstraint {
    /// The performative this shape constrains.
    pub performative: String,
    /// The rules that expanded messages must satisfy.
    pub rules: Vec<ShapeRule>,
}

/// A violation found during shape checking (REQ-223).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShapeViolation {
    pub rule: String,
    pub field: Option<String>,
    pub expected: Option<String>,
    pub found: Option<String>,
    pub detail: String,
}

impl fmt::Display for ShapeViolation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "shape violation: {}", self.detail)
    }
}

impl ShapeConstraint {
    /// Check an expanded S-expression against this shape constraint (REQ-223).
    ///
    /// The `sexpr` should be the fully expanded message (after template expansion).
    /// Returns `Ok(())` if all rules are satisfied, or `Err` with the first violation.
    pub fn check(&self, sexpr: &SExpr) -> Result<(), ShapeViolation> {
        self.check_with_work(sexpr, crate::contracts::DEFAULT_WORK)
    }

    pub fn check_with_work(&self, sexpr: &SExpr, work: u64) -> Result<(), ShapeViolation> {
        for rule in &self.rules {
            check_rule(rule, sexpr, work)?;
        }
        Ok(())
    }

    /// Check whether this constraint has any duplicate require/optional keywords
    /// at the same depth (REQ-222 §5).
    pub fn no_duplicate_keywords(&self) -> Result<(), String> {
        check_duplicate_keywords(&self.rules)
    }

    /// Return the first declared max-depth bound, if any.
    ///
    /// Prefer [`max_depths`](Self::max_depths) when validating every declared
    /// bound (e.g. the R5 install-time check); this accessor is retained for
    /// callers that only want a single representative bound.
    pub fn max_depth(&self) -> Option<u32> {
        self.max_depths().next()
    }

    /// Iterate over every `(max-depth …)` bound declared on this shape,
    /// including bounds nested inside `require`/`optional` rules.
    ///
    /// A shape may declare more than one `MaxDepth` rule, and the parser
    /// allows `(max-depth N)` to appear among a parent rule's children
    /// (e.g. `(require :payload list (max-depth N))`). Install-time R5
    /// (REQ-222 §4) must check every declared bound against the dialect's
    /// R2 limit — a top-level-only walk would silently accept oversized
    /// nested bounds, since at runtime any subtree's depth is bounded by
    /// the whole message's depth, so `N > R2` is unreachable but still a
    /// malformed declaration.
    pub fn max_depths(&self) -> impl Iterator<Item = u32> {
        let mut out = Vec::new();
        collect_max_depths(&self.rules, &mut out);
        out.into_iter()
    }
}

/// Pre-order walk over a rule tree, pushing every `MaxDepth` value found.
fn collect_max_depths(rules: &[ShapeRule], out: &mut Vec<u32>) {
    for rule in rules {
        match rule {
            ShapeRule::MaxDepth(d) => out.push(*d),
            ShapeRule::Require { children, .. } | ShapeRule::Optional { children, .. } => {
                collect_max_depths(children, out);
            }
        }
    }
}

/// Check a single rule against an S-expression.
pub(crate) fn check_rule(rule: &ShapeRule, sexpr: &SExpr, work: u64) -> Result<(), ShapeViolation> {
    match rule {
        ShapeRule::Require {
            keyword,
            type_constraint,
            children,
        } => {
            let value = find_keyword_value(sexpr, keyword).ok_or_else(|| ShapeViolation {
                rule: alloc::format!("require :{keyword}"),
                field: Some(alloc::format!(":{keyword}")),
                expected: Some(String::from("present")),
                found: Some(String::from("missing")),
                detail: alloc::format!("required parameter :{keyword} is missing"),
            })?;
            if let Some(tc) = type_constraint {
                if let Err(check_error) = tc.check(value, work) {
                    let diagnostic =
                        if matches!(check_error, crate::contracts::CheckError::ResourceLimit) {
                            tc.resource_detail(value, work)
                        } else {
                            check_error.to_string()
                        };
                    return Err(ShapeViolation {
                        rule: if matches!(check_error, crate::contracts::CheckError::ResourceLimit)
                        {
                            "resource-limit".into()
                        } else {
                            alloc::format!("require :{keyword} {tc}")
                        },
                        field: Some(alloc::format!(":{keyword}")),
                        expected: Some(alloc::format!("{tc}")),
                        found: Some(describe_type(value)),
                        detail: if matches!(
                            check_error,
                            crate::contracts::CheckError::ResourceLimit
                        ) {
                            alloc::format!(
                                "parameter :{keyword}: {diagnostic}; found {}",
                                describe_type(value)
                            )
                        } else {
                            alloc::format!(
                                "parameter :{keyword} failed {tc}: {diagnostic}; found {}",
                                describe_type(value)
                            )
                        },
                    });
                }
            }
            for child in children {
                check_rule(child, value, work).map_err(|mut err| {
                    err.field = err.field.map(|field| alloc::format!(":{keyword}/{field}"));
                    err
                })?;
            }
            Ok(())
        }
        ShapeRule::Optional {
            keyword,
            type_constraint,
            children,
            ..
        } => {
            if let Some(value) = find_keyword_value(sexpr, keyword) {
                if let Some(tc) = type_constraint {
                    if let Err(check_error) = tc.check(value, work) {
                        let diagnostic =
                            if matches!(check_error, crate::contracts::CheckError::ResourceLimit) {
                                tc.resource_detail(value, work)
                            } else {
                                check_error.to_string()
                            };
                        return Err(ShapeViolation {
                            rule: if matches!(
                                check_error,
                                crate::contracts::CheckError::ResourceLimit
                            ) {
                                "resource-limit".into()
                            } else {
                                alloc::format!("optional :{keyword} {tc}")
                            },
                            field: Some(alloc::format!(":{keyword}")),
                            expected: Some(alloc::format!("{tc}")),
                            found: Some(describe_type(value)),
                            detail: if matches!(
                                check_error,
                                crate::contracts::CheckError::ResourceLimit
                            ) {
                                alloc::format!(
                                    "parameter :{keyword}: {diagnostic}; found {}",
                                    describe_type(value)
                                )
                            } else {
                                alloc::format!(
                                    "parameter :{keyword} failed {tc}: {diagnostic}; found {}",
                                    describe_type(value)
                                )
                            },
                        });
                    }
                }
                for child in children {
                    check_rule(child, value, work).map_err(|mut err| {
                        err.field = err.field.map(|field| alloc::format!(":{keyword}/{field}"));
                        err
                    })?;
                }
            }
            Ok(())
        }
        ShapeRule::MaxDepth(max) => {
            let depth = sexpr.depth() as u32;
            if depth > *max {
                Err(ShapeViolation {
                    rule: alloc::format!("max-depth {max}"),
                    field: None,
                    expected: Some(alloc::format!("<= {max}")),
                    found: Some(alloc::format!("{depth}")),
                    detail: alloc::format!("message depth {depth} exceeds max-depth {max}"),
                })
            } else {
                Ok(())
            }
        }
    }
}

/// Find the value following a keyword in an S-expression list.
///
/// Scans `(performative ... :keyword value ...)` and returns `value`.
fn find_keyword_value<'a>(sexpr: &'a SExpr, keyword: &str) -> Option<&'a SExpr> {
    let items = match sexpr {
        SExpr::List(items) => items,
        _ => return None,
    };
    let mut i = 0;
    while i < items.len() {
        if let SExpr::Atom(Atom::Keyword(k)) = &items[i] {
            if k == keyword {
                return items.get(i + 1);
            }
        }
        i += 1;
    }
    None
}

/// Describe the type of an S-expression value for error messages.
pub(crate) fn describe_type(sexpr: &SExpr) -> String {
    match sexpr {
        SExpr::Atom(Atom::Str(_)) => String::from("string"),
        SExpr::Atom(Atom::Float(_)) => String::from("float"),
        SExpr::Atom(Atom::Decimal(_)) => String::from("decimal"),
        SExpr::Atom(Atom::Num(_)) => String::from("integer"),
        SExpr::Atom(Atom::Bool(_)) => String::from("bool"),
        SExpr::Atom(Atom::Symbol(_)) => String::from("symbol"),
        SExpr::Atom(Atom::Keyword(_)) => String::from("keyword"),
        SExpr::List(_) => String::from("list"),
    }
}

/// Check for duplicate require/optional keywords within the same parent
/// scope (REQ-222 §5).
///
/// Each `(...)` list in an expanded message has its own keyword namespace
/// (see `find_keyword_value` and the `Require` arm of `check_rule`, which
/// recurses children against the matched parent's value). The static check
/// mirrors that scoping: duplicates are sibling rules under the same
/// parent, not arbitrary co-depth rules across independent subtrees.
fn check_duplicate_keywords(rules: &[ShapeRule]) -> Result<(), String> {
    walk_keywords(rules, 0)
}

fn walk_keywords(rules: &[ShapeRule], depth: usize) -> Result<(), String> {
    let mut seen: alloc::collections::BTreeSet<String> = alloc::collections::BTreeSet::new();
    for rule in rules {
        let (keyword, children) = match rule {
            ShapeRule::Require {
                keyword, children, ..
            }
            | ShapeRule::Optional {
                keyword, children, ..
            } => (keyword, children),
            ShapeRule::MaxDepth(_) => continue,
        };
        if !seen.insert(keyword.clone()) {
            return Err(alloc::format!(
                "duplicate keyword :{keyword} at depth {depth}"
            ));
        }
        walk_keywords(children, depth + 1)?;
    }
    Ok(())
}

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

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

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

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

    fn num(n: i64) -> SExpr {
        SExpr::Atom(Atom::Num(n))
    }

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

    // -- TypeConstraint tests --

    #[test]
    fn type_constraint_from_str() {
        assert_eq!(
            TypeConstraint::from_str("string"),
            Some(TypeConstraint::String)
        );
        assert_eq!(
            TypeConstraint::from_str("number"),
            Some(TypeConstraint::Number)
        );
        assert_eq!(TypeConstraint::from_str("bool"), Some(TypeConstraint::Bool));
        assert_eq!(
            TypeConstraint::from_str("symbol"),
            Some(TypeConstraint::Symbol)
        );
        assert_eq!(
            TypeConstraint::from_str("keyword"),
            Some(TypeConstraint::Keyword)
        );
        assert_eq!(TypeConstraint::from_str("list"), Some(TypeConstraint::List));
        assert_eq!(TypeConstraint::from_str("unknown"), None);
    }

    #[test]
    fn type_constraint_matches() {
        assert!(TypeConstraint::String.matches_builtin(&str_expr("hello")));
        assert!(!TypeConstraint::String.matches_builtin(&num(42)));
        assert!(TypeConstraint::Number.matches_builtin(&num(42)));
        assert!(TypeConstraint::Bool.matches_builtin(&SExpr::Atom(Atom::Bool(true))));
        assert!(TypeConstraint::Symbol.matches_builtin(&sym("x")));
        assert!(TypeConstraint::Keyword.matches_builtin(&kw("key")));
        assert!(TypeConstraint::List.matches_builtin(&list(vec![sym("a")])));
        assert!(!TypeConstraint::List.matches_builtin(&sym("a")));
    }

    #[test]
    fn type_constraint_display() {
        assert_eq!(TypeConstraint::String.to_string(), "string");
        assert_eq!(TypeConstraint::Number.to_string(), "number");
        assert_eq!(TypeConstraint::List.to_string(), "list");
    }

    // -- ShapeConstraint::check tests --

    #[test]
    fn check_require_present() {
        let shape = ShapeConstraint {
            performative: String::from("track-shipment"),
            rules: vec![ShapeRule::Require {
                keyword: String::from("package"),
                type_constraint: Some(TypeConstraint::String),
                children: vec![],
            }],
        };
        let msg = list(vec![
            sym("track-shipment"),
            kw("package"),
            str_expr("box-1"),
        ]);
        assert!(shape.check(&msg).is_ok());
    }

    #[test]
    fn check_require_missing() {
        let shape = ShapeConstraint {
            performative: String::from("track-shipment"),
            rules: vec![ShapeRule::Require {
                keyword: String::from("package"),
                type_constraint: Some(TypeConstraint::String),
                children: vec![],
            }],
        };
        let msg = list(vec![sym("track-shipment"), kw("route"), str_expr("A-B")]);
        let err = shape.check(&msg).unwrap_err();
        assert_eq!(err.field, Some(String::from(":package")));
        assert!(err.detail.contains("missing"));
    }

    #[test]
    fn check_require_wrong_type() {
        let shape = ShapeConstraint {
            performative: String::from("track-shipment"),
            rules: vec![ShapeRule::Require {
                keyword: String::from("package"),
                type_constraint: Some(TypeConstraint::String),
                children: vec![],
            }],
        };
        let msg = list(vec![sym("track-shipment"), kw("package"), num(42)]);
        let err = shape.check(&msg).unwrap_err();
        assert_eq!(err.expected, Some(String::from("string")));
        assert_eq!(err.found, Some(String::from("integer")));
    }

    #[test]
    fn check_optional_absent_ok() {
        let shape = ShapeConstraint {
            performative: String::from("track-shipment"),
            rules: vec![ShapeRule::Optional {
                keyword: String::from("priority"),
                type_constraint: Some(TypeConstraint::String),
                default: Some(str_expr("normal")),
                children: vec![],
            }],
        };
        let msg = list(vec![sym("track-shipment")]);
        assert!(shape.check(&msg).is_ok());
    }

    #[test]
    fn check_optional_present_wrong_type() {
        let shape = ShapeConstraint {
            performative: String::from("track-shipment"),
            rules: vec![ShapeRule::Optional {
                keyword: String::from("priority"),
                type_constraint: Some(TypeConstraint::String),
                default: None,
                children: vec![],
            }],
        };
        let msg = list(vec![sym("track-shipment"), kw("priority"), num(1)]);
        let err = shape.check(&msg).unwrap_err();
        assert_eq!(err.expected, Some(String::from("string")));
    }

    #[test]
    fn check_max_depth_ok() {
        let shape = ShapeConstraint {
            performative: String::from("test"),
            rules: vec![ShapeRule::MaxDepth(4)],
        };
        // depth 1: (test :a "b")
        let msg = list(vec![sym("test"), kw("a"), str_expr("b")]);
        assert!(shape.check(&msg).is_ok());
    }

    #[test]
    fn check_max_depth_exceeded() {
        let shape = ShapeConstraint {
            performative: String::from("test"),
            rules: vec![ShapeRule::MaxDepth(1)],
        };
        // depth 2: (test (nested (deep)))
        let msg = list(vec![
            sym("test"),
            list(vec![sym("nested"), list(vec![sym("deep")])]),
        ]);
        let err = shape.check(&msg).unwrap_err();
        assert!(err.detail.contains("exceeds"));
    }

    #[test]
    fn check_nested_children() {
        // (shape propose-step
        //   (require :params list
        //     (require :target string)))
        let shape = ShapeConstraint {
            performative: String::from("propose-step"),
            rules: vec![ShapeRule::Require {
                keyword: String::from("params"),
                type_constraint: Some(TypeConstraint::List),
                children: vec![ShapeRule::Require {
                    keyword: String::from("target"),
                    type_constraint: Some(TypeConstraint::String),
                    children: vec![],
                }],
            }],
        };
        let msg = list(vec![
            sym("propose-step"),
            kw("params"),
            list(vec![kw("target"), str_expr("server-1")]),
        ]);
        assert!(shape.check(&msg).is_ok());
    }

    #[test]
    fn check_nested_children_missing_inner() {
        let shape = ShapeConstraint {
            performative: String::from("propose-step"),
            rules: vec![ShapeRule::Require {
                keyword: String::from("params"),
                type_constraint: Some(TypeConstraint::List),
                children: vec![ShapeRule::Require {
                    keyword: String::from("target"),
                    type_constraint: Some(TypeConstraint::String),
                    children: vec![],
                }],
            }],
        };
        let msg = list(vec![
            sym("propose-step"),
            kw("params"),
            list(vec![kw("other"), str_expr("x")]),
        ]);
        let err = shape.check(&msg).unwrap_err();
        assert!(err.detail.contains(":target"));
    }

    // -- no_duplicate_keywords tests --

    #[test]
    fn no_duplicate_keywords_ok() {
        let shape = ShapeConstraint {
            performative: String::from("test"),
            rules: vec![
                ShapeRule::Require {
                    keyword: String::from("a"),
                    type_constraint: None,
                    children: vec![],
                },
                ShapeRule::Optional {
                    keyword: String::from("b"),
                    type_constraint: None,
                    default: None,
                    children: vec![],
                },
            ],
        };
        assert!(shape.no_duplicate_keywords().is_ok());
    }

    #[test]
    fn no_duplicate_keywords_allows_shared_child_under_different_parents() {
        // Children rules are scoped to the matched parent list at runtime
        // (see `check_rule` Require branch), so `:x` under `:a` and `:x`
        // under `:b` live in independent keyword namespaces and must not
        // be reported as duplicates. Mirrors the pickup/dropoff :id pattern
        // that motivated this regression.
        let shape = ShapeConstraint {
            performative: String::from("test"),
            rules: vec![
                ShapeRule::Require {
                    keyword: String::from("a"),
                    type_constraint: Some(TypeConstraint::List),
                    children: vec![ShapeRule::Require {
                        keyword: String::from("x"),
                        type_constraint: None,
                        children: vec![],
                    }],
                },
                ShapeRule::Require {
                    keyword: String::from("b"),
                    type_constraint: Some(TypeConstraint::List),
                    children: vec![ShapeRule::Require {
                        keyword: String::from("x"),
                        type_constraint: None,
                        children: vec![],
                    }],
                },
            ],
        };
        assert!(shape.no_duplicate_keywords().is_ok());
    }

    #[test]
    fn no_duplicate_keywords_detects_duplicate_within_same_parent() {
        // Two child rules with the same keyword under the same parent
        // collide at runtime (they target the same value slot of `:a`),
        // so R5 must reject this even though the duplicates are nested.
        let shape = ShapeConstraint {
            performative: String::from("test"),
            rules: vec![ShapeRule::Require {
                keyword: String::from("a"),
                type_constraint: Some(TypeConstraint::List),
                children: vec![
                    ShapeRule::Require {
                        keyword: String::from("x"),
                        type_constraint: None,
                        children: vec![],
                    },
                    ShapeRule::Optional {
                        keyword: String::from("x"),
                        type_constraint: None,
                        default: None,
                        children: vec![],
                    },
                ],
            }],
        };
        let err = shape.no_duplicate_keywords().unwrap_err();
        assert!(err.contains(":x"), "expected :x to be flagged: {err}");
        assert!(err.contains("depth 1"), "expected depth in error: {err}");
    }

    #[test]
    fn no_duplicate_keywords_detects_duplicate() {
        let shape = ShapeConstraint {
            performative: String::from("test"),
            rules: vec![
                ShapeRule::Require {
                    keyword: String::from("a"),
                    type_constraint: None,
                    children: vec![],
                },
                ShapeRule::Optional {
                    keyword: String::from("a"),
                    type_constraint: None,
                    default: None,
                    children: vec![],
                },
            ],
        };
        let err = shape.no_duplicate_keywords().unwrap_err();
        assert!(err.contains(":a"));
    }

    // -- max_depth accessor --

    #[test]
    fn max_depth_accessor() {
        let shape = ShapeConstraint {
            performative: String::from("test"),
            rules: vec![
                ShapeRule::Require {
                    keyword: String::from("a"),
                    type_constraint: None,
                    children: vec![],
                },
                ShapeRule::MaxDepth(6),
            ],
        };
        assert_eq!(shape.max_depth(), Some(6));
    }

    #[test]
    fn max_depth_none() {
        let shape = ShapeConstraint {
            performative: String::from("test"),
            rules: vec![],
        };
        assert_eq!(shape.max_depth(), None);
    }

    // -- Composition via conjunction (REQ-224) --

    #[test]
    fn multiple_shapes_compose_via_conjunction() {
        let shape1 = ShapeConstraint {
            performative: String::from("track"),
            rules: vec![ShapeRule::Require {
                keyword: String::from("package"),
                type_constraint: Some(TypeConstraint::String),
                children: vec![],
            }],
        };
        let shape2 = ShapeConstraint {
            performative: String::from("track"),
            rules: vec![ShapeRule::Require {
                keyword: String::from("route"),
                type_constraint: Some(TypeConstraint::String),
                children: vec![],
            }],
        };
        // Must satisfy both
        let msg = list(vec![
            sym("track"),
            kw("package"),
            str_expr("box-1"),
            kw("route"),
            str_expr("A-B"),
        ]);
        assert!(shape1.check(&msg).is_ok());
        assert!(shape2.check(&msg).is_ok());

        // Missing route fails shape2
        let partial = list(vec![sym("track"), kw("package"), str_expr("box-1")]);
        assert!(shape1.check(&partial).is_ok());
        assert!(shape2.check(&partial).is_err());
    }

    // -- ShapeViolation display --

    #[test]
    fn shape_violation_display() {
        let v = ShapeViolation {
            rule: String::from("require :package string"),
            field: Some(String::from(":package")),
            expected: Some(String::from("string")),
            found: Some(String::from("number")),
            detail: String::from("parameter :package expected type string, found number"),
        };
        let s = v.to_string();
        assert!(s.contains("shape violation"));
        assert!(s.contains(":package"));
    }

    // -- find_keyword_value on non-list --

    #[test]
    fn check_on_atom_fails_for_require() {
        let shape = ShapeConstraint {
            performative: String::from("test"),
            rules: vec![ShapeRule::Require {
                keyword: String::from("a"),
                type_constraint: None,
                children: vec![],
            }],
        };
        assert!(shape.check(&sym("not-a-list")).is_err());
    }

    // -- Require without type constraint --

    #[test]
    fn require_without_type_constraint() {
        let shape = ShapeConstraint {
            performative: String::from("test"),
            rules: vec![ShapeRule::Require {
                keyword: String::from("data"),
                type_constraint: None,
                children: vec![],
            }],
        };
        // Any type of value is accepted
        let msg = list(vec![sym("test"), kw("data"), num(42)]);
        assert!(shape.check(&msg).is_ok());
    }
}