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
//! Role layer types and parsing (SPEC-014).
//!
//! Types and SExpr-level recognisers for the role layer: role declarations
//! (REQ-600, CON-600), per-performative `:from`/`:to` annotations (REQ-601,
//! CON-600), and the thread cast nominated by a `with-roles` wrapper
//! (REQ-611, CON-601). Fail-closed: malformed annotations are rejected, never
//! repaired (LangSec principle 4).
//!
//! The indexed-role marker is the head-position form `(* name)` (ADR-600).
//! Key identifiers ([`AgentKey`]) are whole symbols (e.g. `@alice`), compared
//! for equality as strings; cryptographic validity of the signature binding a
//! message to its key is an R4-layer precondition (CON-602).

#![forbid(unsafe_code)]

use crate::sexpr::{Atom, SExpr};
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

/// How many occupants a role admits (SPEC-014 §Terminology).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum RoleCardinality {
    /// Exactly one occupant, pinned by the cast (REQ-612).
    Singleton,
    /// Many occupants, membership sealed at thread open (REQ-614);
    /// declared `(* name)` (ADR-600).
    Indexed,
}

/// A declared role (CON-600, REQ-600).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RoleDecl {
    pub name: String,
    pub cardinality: RoleCardinality,
}

/// Per-performative `:from`/`:to` annotation (CON-600, REQ-601).
///
/// `to` is a set from the start: bare symbol = singleton, list = multicast,
/// `()` = empty (a terminal act addressed to no other role).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RoleAnnotation {
    pub from: String,
    pub to: BTreeSet<String>,
}

/// Key identifier as it appears in casts and signed messages (e.g. `@alice`).
///
/// Equality is whole-symbol string equality; cryptographic validity of the
/// signature that binds a message to this identifier is an R4-layer
/// precondition, outside this module (CON-602).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AgentKey(pub String);

/// The assignment of agents to roles for one thread (CON-601, REQ-611).
///
/// Nominated by the initiator at the causal root; tamper-evident because the
/// root's content hash anchors every subsequent `:caused-by` link. Indexed
/// memberships are *sealed*: occupant-dependent checks read them exclusively
/// from here (REQ-614).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Cast {
    pub singleton: BTreeMap<String, AgentKey>,
    pub indexed: BTreeMap<String, BTreeSet<AgentKey>>,
    /// REQ-628: the `f1220<hex64>` content hash of the dialect that
    /// governs the thread, from the wrapper's optional `:dialect` field.
    /// `None` for an unpinned root (accepted during the spec's
    /// warn-then-reject transition window).
    #[cfg_attr(feature = "serde", serde(default))]
    pub dialect_pin: Option<String>,
}

impl Cast {
    /// Whether `key` may occupy `role` under this cast.
    pub fn admits(&self, role: &str, key: &AgentKey) -> bool {
        match self.singleton.get(role) {
            Some(k) => k == key,
            None => self.indexed.get(role).is_some_and(|ks| ks.contains(key)),
        }
    }
}

/// A `(role, occupant)` pair; `occupant` is `None` for singleton roles
/// (CON-602).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Endpoint {
    pub role: String,
    pub occupant: Option<AgentKey>,
}

/// How the installer treats R6(vi) causal-locality failures (SPEC-015
/// REQ-709, ADR-704): the dialect's `(:causal-locality derive|reject)`
/// declaration. The default is [`CausalLocality::Reject`] — the v1
/// behaviour, bit-for-bit.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CausalLocality {
    /// R6(vi) failures reject the dialect at install (v1 semantics).
    #[default]
    Reject,
    /// R6(vi) stops being a rejection condition and becomes a compilation
    /// step: the installer derives the envelope-widening closure and
    /// records it here. The table is *derived*, never authored — the
    /// parser always produces an empty table, and
    /// `DialectRegistry::install` replaces it with the closure.
    Derive(EnvelopeRoutes),
}

/// Dialect-level envelope-routing table (SPEC-015 REQ-709): protocol
/// performative (step name) → the roles that receive its redacted envelope.
///
/// An envelope recipient counts as an endpoint role of the performative
/// *for R6(vi) observability only*: payload `:to` sets are untouched, and
/// projection emits an ExpectEnvelope step (never Send/Recv) per route.
/// Derived at install as a pure, deterministic fixpoint of the dialect
/// alone — every agent derives identical routes.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EnvelopeRoutes(pub BTreeMap<String, BTreeSet<String>>);

impl EnvelopeRoutes {
    /// Whether `role` is an envelope recipient of `performative`.
    pub fn routes_to(&self, performative: &str, role: &str) -> bool {
        self.0.get(performative).is_some_and(|s| s.contains(role))
    }
}

/// Per-occupant envelope-routing table (SPEC-015 REQ-709), the thread-open
/// half of the two-level derivation: performative → the sealed occupant
/// keys that receive redacted envelopes of its instances.
///
/// It cannot exist earlier than thread open — these routes are O(n²) in a
/// cast fixed only then — and it is a pure function of the dialect and the
/// sealed cast, so every agent derives identical routes. Indexed-role
/// routes appear only here, never in the install-time table.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OccupantEnvelopeRoutes(pub BTreeMap<String, BTreeSet<AgentKey>>);

/// R6 violation (CON-603): one variant per rejectable condition, each
/// carrying the names needed to locate the defect.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum R6Violation {
    /// REQ-601: a protocol performative lacks `:from` or `:to`.
    MissingFromTo { performative: String },
    /// REQ-602: `:from`/`:to` names a role absent from `:roles`.
    UndeclaredRole { performative: String, role: String },
    /// REQ-602: `:from`/`:to` present while no `:roles` is declared.
    StrayAnnotation { performative: String },
    /// REQ-603: a choice whose members do not share one sender role.
    ChooserIncoherent { members: Vec<String> },
    /// REQ-604: an endpoint role of `performative` is not an endpoint role
    /// of `predecessor`.
    NotCausallyLocal {
        performative: String,
        predecessor: String,
        role: String,
    },
    /// REQ-605: a declared role unreachable from `begin`.
    UnreachableRole { role: String },
    /// CON-600: malformed `:roles` value.
    MalformedRoles { detail: String },
    /// CON-600: malformed `:from`/`:to` value.
    MalformedFromTo {
        performative: String,
        detail: String,
    },
    /// CON-601: malformed `with-roles` bindings.
    MalformedCast { detail: String },
    /// CON-601: a cast binding names a role not declared in `:roles`.
    UnknownRole { role: String },
    /// CON-601: a singleton role bound to a number of keys other than one.
    ArityMismatch { role: String, keys: usize },
    /// REQ-608: per-occupant causal locality fails at `occupant`.
    PerOccupantLocalityFailure {
        performative: String,
        occupant: String,
    },
    /// REQ-628: the root's `:dialect` pin differs from the installed
    /// dialect's content hash.
    DialectPinMismatch { pinned: String, installed: String },
}

impl fmt::Display for R6Violation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            R6Violation::MissingFromTo { performative } => write!(
                f,
                "R6 violation: performative '{performative}' lacks :from or :to (REQ-601)"
            ),
            R6Violation::UndeclaredRole { performative, role } => write!(
                f,
                "R6 violation: performative '{performative}' names undeclared role '{role}' (REQ-602)"
            ),
            R6Violation::StrayAnnotation { performative } => write!(
                f,
                "R6 violation: performative '{performative}' carries :from/:to but the dialect declares no :roles (REQ-602)"
            ),
            R6Violation::ChooserIncoherent { members } => write!(
                f,
                "R6 violation: choice {members:?} has no common sender role (REQ-603)"
            ),
            R6Violation::NotCausallyLocal {
                performative,
                predecessor,
                role,
            } => write!(
                f,
                "R6 violation: role '{role}' is an endpoint of '{performative}' but not of its predecessor '{predecessor}' (REQ-604)"
            ),
            R6Violation::UnreachableRole { role } => write!(
                f,
                "R6 violation: role '{role}' is not an endpoint of any performative reachable from begin (REQ-605)"
            ),
            R6Violation::MalformedRoles { detail } => {
                write!(f, "R6 violation: malformed :roles — {detail} (CON-600)")
            }
            R6Violation::MalformedFromTo {
                performative,
                detail,
            } => write!(
                f,
                "R6 violation: malformed :from/:to on '{performative}' — {detail} (CON-600)"
            ),
            R6Violation::MalformedCast { detail } => {
                write!(f, "R6 violation: malformed cast — {detail} (CON-601)")
            }
            R6Violation::UnknownRole { role } => write!(
                f,
                "R6 violation: cast binds unknown role '{role}' (CON-601)"
            ),
            R6Violation::ArityMismatch { role, keys } => write!(
                f,
                "R6 violation: singleton role '{role}' bound to {keys} keys (CON-601)"
            ),
            R6Violation::PerOccupantLocalityFailure {
                performative,
                occupant,
            } => write!(
                f,
                "R6 violation: '{performative}' fails per-occupant causal locality at occupant '{occupant}' (REQ-608)"
            ),
            R6Violation::DialectPinMismatch { pinned, installed } => write!(
                f,
                "R6 violation: root pins dialect '{pinned}' but the installed dialect hashes to '{installed}' (REQ-628)"
            ),
        }
    }
}

/// Parse the value of a `:roles` attribute (CON-600, REQ-600).
///
/// `(auctioneer (* bidder))` → `[auctioneer: Singleton, bidder: Indexed]`.
/// Rejects (fail closed): a non-list value, an empty list, non-symbol
/// entries, a marker form that is not exactly `(* name)`, and duplicate role
/// names.
pub fn parse_roles(roles_value: &SExpr) -> Result<Vec<RoleDecl>, R6Violation> {
    let items = match roles_value {
        SExpr::List(items) if !items.is_empty() => items,
        SExpr::List(_) => {
            return Err(R6Violation::MalformedRoles {
                detail: String::from("empty :roles ()"),
            })
        }
        _ => {
            return Err(R6Violation::MalformedRoles {
                detail: String::from(":roles value is not a list"),
            })
        }
    };
    let mut decls: Vec<RoleDecl> = Vec::with_capacity(items.len());
    for item in items {
        let decl = match item {
            SExpr::Atom(Atom::Symbol(name)) => RoleDecl {
                name: name.clone(),
                cardinality: RoleCardinality::Singleton,
            },
            SExpr::List(marker) => match marker.as_slice() {
                [SExpr::Atom(Atom::Symbol(star)), SExpr::Atom(Atom::Symbol(name))]
                    if star == "*" =>
                {
                    RoleDecl {
                        name: name.clone(),
                        cardinality: RoleCardinality::Indexed,
                    }
                }
                _ => {
                    return Err(R6Violation::MalformedRoles {
                        detail: format!(
                            "role declaration must be a symbol or (* name), got {item}"
                        ),
                    })
                }
            },
            _ => {
                return Err(R6Violation::MalformedRoles {
                    detail: format!("role declaration must be a symbol or (* name), got {item}"),
                })
            }
        };
        if decls.iter().any(|d| d.name == decl.name) {
            return Err(R6Violation::MalformedRoles {
                detail: format!("duplicate role name '{}'", decl.name),
            });
        }
        decls.push(decl);
    }
    Ok(decls)
}

/// Parse the value of a `:from` annotation: exactly one role symbol
/// (CON-600).
pub fn parse_from(performative: &str, from_value: &SExpr) -> Result<String, R6Violation> {
    match from_value {
        SExpr::Atom(Atom::Symbol(role)) => Ok(role.clone()),
        other => Err(R6Violation::MalformedFromTo {
            performative: String::from(performative),
            detail: format!(":from must be exactly one role symbol, got {other}"),
        }),
    }
}

/// Parse the value of a `:to` annotation into a recipient set (CON-600):
/// bare symbol = singleton set, list = multicast, `()` = empty. Rejects
/// non-symbol members and duplicate members.
pub fn parse_recipient_set(
    performative: &str,
    to_value: &SExpr,
) -> Result<BTreeSet<String>, R6Violation> {
    match to_value {
        SExpr::Atom(Atom::Symbol(role)) => {
            let mut set = BTreeSet::new();
            set.insert(role.clone());
            Ok(set)
        }
        SExpr::List(items) => {
            let mut set = BTreeSet::new();
            for item in items {
                let SExpr::Atom(Atom::Symbol(role)) = item else {
                    return Err(R6Violation::MalformedFromTo {
                        performative: String::from(performative),
                        detail: format!(":to members must be role symbols, got {item}"),
                    });
                };
                if !set.insert(role.clone()) {
                    return Err(R6Violation::MalformedFromTo {
                        performative: String::from(performative),
                        detail: format!("duplicate :to member '{role}'"),
                    });
                }
            }
            Ok(set)
        }
        other => Err(R6Violation::MalformedFromTo {
            performative: String::from(performative),
            detail: format!(":to must be a role symbol or a list, got {other}"),
        }),
    }
}

/// Parse a `with-roles` bindings list into a [`Cast`] (CON-601, REQ-611).
///
/// Every declared role must be bound exactly once (a cast *assigns* each
/// role, REQ-611); a singleton role takes exactly one key
/// ([`R6Violation::ArityMismatch`] otherwise); an indexed role takes one or
/// more keys (its sealed membership, REQ-614); an undeclared role is
/// [`R6Violation::UnknownRole`].
pub fn parse_cast(bindings: &SExpr, roles: &[RoleDecl]) -> Result<Cast, R6Violation> {
    let SExpr::List(items) = bindings else {
        return Err(R6Violation::MalformedCast {
            detail: String::from("bindings must be a list of (role key+) forms"),
        });
    };
    let mut cast = Cast {
        singleton: BTreeMap::new(),
        indexed: BTreeMap::new(),
        dialect_pin: None,
    };
    for item in items {
        let SExpr::List(binding) = item else {
            return Err(R6Violation::MalformedCast {
                detail: format!("binding must be a (role key+) list, got {item}"),
            });
        };
        let [SExpr::Atom(Atom::Symbol(role_name)), keys @ ..] = binding.as_slice() else {
            return Err(R6Violation::MalformedCast {
                detail: format!("binding must start with a role symbol, got {item}"),
            });
        };
        let Some(decl) = roles.iter().find(|d| &d.name == role_name) else {
            return Err(R6Violation::UnknownRole {
                role: role_name.clone(),
            });
        };
        if cast.singleton.contains_key(role_name) || cast.indexed.contains_key(role_name) {
            return Err(R6Violation::MalformedCast {
                detail: format!("duplicate binding for role '{role_name}'"),
            });
        }
        let mut key_set: BTreeSet<AgentKey> = BTreeSet::new();
        for key in keys {
            let SExpr::Atom(Atom::Symbol(k)) = key else {
                return Err(R6Violation::MalformedCast {
                    detail: format!("key must be a symbol, got {key}"),
                });
            };
            if !key_set.insert(AgentKey(k.clone())) {
                return Err(R6Violation::MalformedCast {
                    detail: format!("duplicate key '{k}' for role '{role_name}'"),
                });
            }
        }
        match decl.cardinality {
            RoleCardinality::Singleton => {
                if key_set.len() != 1 {
                    return Err(R6Violation::ArityMismatch {
                        role: role_name.clone(),
                        keys: key_set.len(),
                    });
                }
                let key = key_set.into_iter().next().expect("len == 1");
                cast.singleton.insert(role_name.clone(), key);
            }
            RoleCardinality::Indexed => {
                if key_set.is_empty() {
                    return Err(R6Violation::MalformedCast {
                        detail: format!("indexed role '{role_name}' bound to no keys"),
                    });
                }
                cast.indexed.insert(role_name.clone(), key_set);
            }
        }
    }
    for decl in roles {
        let bound =
            cast.singleton.contains_key(&decl.name) || cast.indexed.contains_key(&decl.name);
        if !bound {
            return Err(R6Violation::MalformedCast {
                detail: format!("declared role '{}' is not bound by the cast", decl.name),
            });
        }
    }
    Ok(cast)
}

/// Length of the lowercase-hex digest in a `f1220<hex64>` pin (REQ-628).
const PIN_HEX_LEN: usize = 64;

/// Parse the value of a `with-roles` `:dialect` field (REQ-628): exactly
/// the string `"f1220<lowercase-hex64>"` on the strict wire path. Typed
/// symbol atoms remain accepted for existing in-process callers. The digest
/// is the form [`Dialect::hash`] takes at install. A bad prefix, wrong digest
/// length or non-hex character is rejected, never repaired (LangSec principle 4).
///
/// [`Dialect::hash`]: crate::dialect::Dialect::hash
pub fn parse_dialect_pin(value: &SExpr) -> Result<String, R6Violation> {
    let pin = match value {
        SExpr::Atom(Atom::Str(pin) | Atom::Symbol(pin)) => pin,
        _ => {
            return Err(R6Violation::MalformedCast {
                detail: format!(
                    ":dialect value must be a f1220<hex64> string or typed symbol, got {value}"
                ),
            })
        }
    };
    let Some(hex) = pin.strip_prefix("f1220") else {
        return Err(R6Violation::MalformedCast {
            detail: format!(":dialect value must start with 'f1220', got '{pin}'"),
        });
    };
    if hex.len() != PIN_HEX_LEN || !hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
        return Err(R6Violation::MalformedCast {
            detail: format!(
                ":dialect digest must be exactly {PIN_HEX_LEN} lowercase hex characters, got '{hex}'"
            ),
        });
    }
    Ok(pin.clone())
}

/// Parse a `with-roles` wrapper's parameter list into a [`Cast`] (CON-601,
/// REQ-628): the bindings list, optionally followed by
/// `:dialect "f1220<hex64>"` in that fixed position. Any other shape —
/// extra fields, a misplaced pin, an unknown keyword — is rejected, never
/// repaired (LangSec principle 4).
pub fn parse_wrapper_cast(params: &[SExpr], roles: &[RoleDecl]) -> Result<Cast, R6Violation> {
    let (bindings, pin) = match params {
        [bindings] => (bindings, None),
        [bindings, SExpr::Atom(Atom::Keyword(k)), value] if k == "dialect" => {
            (bindings, Some(parse_dialect_pin(value)?))
        }
        _ => {
            return Err(R6Violation::MalformedCast {
                detail: String::from(
                    "with-roles wrapper must carry exactly one bindings list, \
                     optionally followed by :dialect f1220<hex64> (CON-601, REQ-628)",
                ),
            })
        }
    };
    let mut cast = parse_cast(bindings, roles)?;
    cast.dialect_pin = pin;
    Ok(cast)
}

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

    fn sx(s: &str) -> SExpr {
        s.parse().expect("test fixture parses")
    }

    // ---- R6Violation Display (CON-603: violations are Display-formatted
    // like ProtocolViolation, carrying the names needed to locate the
    // defect) ----

    #[test]
    fn violation_display_carries_locating_names() {
        use alloc::string::ToString as _;
        let v = R6Violation::NotCausallyLocal {
            performative: "dispatch".to_string(),
            predecessor: "accept".to_string(),
            role: "warehouse".to_string(),
        };
        let s = alloc::format!("{v}");
        assert!(s.contains("dispatch") && s.contains("accept") && s.contains("warehouse"));
        assert!(s.contains("REQ-604"));

        let a = R6Violation::ArityMismatch {
            role: "auctioneer".to_string(),
            keys: 2,
        };
        let s = alloc::format!("{a}");
        assert!(s.contains("auctioneer") && s.contains('2') && s.contains("CON-601"));
    }

    fn auction_roles() -> Vec<RoleDecl> {
        vec![
            RoleDecl {
                name: "auctioneer".to_string(),
                cardinality: RoleCardinality::Singleton,
            },
            RoleDecl {
                name: "bidder".to_string(),
                cardinality: RoleCardinality::Indexed,
            },
        ]
    }

    // ---- parse_roles (REQ-600, TEST-600) ----

    #[test]
    fn roles_positive_singleton_and_indexed() {
        let decls = parse_roles(&sx("(auctioneer (* bidder))")).unwrap();
        assert_eq!(decls, auction_roles());
    }

    #[test]
    fn roles_negative_empty_list() {
        assert!(matches!(
            parse_roles(&sx("()")),
            Err(R6Violation::MalformedRoles { .. })
        ));
    }

    #[test]
    fn roles_negative_not_a_list() {
        assert!(matches!(
            parse_roles(&sx("auctioneer")),
            Err(R6Violation::MalformedRoles { .. })
        ));
    }

    #[test]
    fn roles_negative_postfix_marker() {
        // (bidder *) is the rejected postfix form — dispatch is on the head.
        assert!(matches!(
            parse_roles(&sx("((bidder *))")),
            Err(R6Violation::MalformedRoles { .. })
        ));
    }

    #[test]
    fn roles_negative_marker_arity() {
        assert!(matches!(
            parse_roles(&sx("((*))")),
            Err(R6Violation::MalformedRoles { .. })
        ));
        assert!(matches!(
            parse_roles(&sx("((* a b))")),
            Err(R6Violation::MalformedRoles { .. })
        ));
    }

    #[test]
    fn roles_negative_non_symbol_entry() {
        assert!(matches!(
            parse_roles(&sx("(auctioneer 42)")),
            Err(R6Violation::MalformedRoles { .. })
        ));
    }

    #[test]
    fn roles_negative_duplicate_names() {
        assert!(matches!(
            parse_roles(&sx("(a (* a))")),
            Err(R6Violation::MalformedRoles { .. })
        ));
    }

    // ---- parse_from / parse_recipient_set (REQ-601 values, TEST-601) ----

    #[test]
    fn from_positive_symbol() {
        assert_eq!(parse_from("login", &sx("server")).unwrap(), "server");
    }

    #[test]
    fn from_negative_list() {
        assert!(matches!(
            parse_from("login", &sx("(server client)")),
            Err(R6Violation::MalformedFromTo { .. })
        ));
    }

    #[test]
    fn to_positive_bare_symbol_is_singleton_set() {
        let set = parse_recipient_set("login", &sx("client")).unwrap();
        assert_eq!(set.len(), 1);
        assert!(set.contains("client"));
    }

    #[test]
    fn to_positive_multicast() {
        let set = parse_recipient_set("login", &sx("(client authoriser)")).unwrap();
        assert_eq!(set.len(), 2);
        assert!(set.contains("client") && set.contains("authoriser"));
    }

    #[test]
    fn to_positive_empty_terminal() {
        let set = parse_recipient_set("declare-winner", &sx("()")).unwrap();
        assert!(set.is_empty());
    }

    #[test]
    fn to_negative_non_symbol_member() {
        assert!(matches!(
            parse_recipient_set("login", &sx("(client 7)")),
            Err(R6Violation::MalformedFromTo { .. })
        ));
    }

    #[test]
    fn to_negative_duplicate_member() {
        assert!(matches!(
            parse_recipient_set("login", &sx("(client client)")),
            Err(R6Violation::MalformedFromTo { .. })
        ));
    }

    // ---- parse_cast (REQ-611/614, TEST-611/614) ----

    #[test]
    fn cast_positive_auction() {
        let cast = parse_cast(
            &sx("((auctioneer @auc) (bidder @b1 @b2 @b3))"),
            &auction_roles(),
        )
        .unwrap();
        assert_eq!(
            cast.singleton.get("auctioneer"),
            Some(&AgentKey("@auc".to_string()))
        );
        let members = cast.indexed.get("bidder").unwrap();
        assert_eq!(members.len(), 3);
        assert!(cast.admits("bidder", &AgentKey("@b2".to_string())));
        assert!(!cast.admits("bidder", &AgentKey("@b4".to_string())));
        assert!(cast.admits("auctioneer", &AgentKey("@auc".to_string())));
    }

    #[test]
    fn cast_negative_singleton_two_keys() {
        assert!(matches!(
            parse_cast(&sx("((auctioneer @a @b) (bidder @b1))"), &auction_roles()),
            Err(R6Violation::ArityMismatch { keys: 2, .. })
        ));
    }

    #[test]
    fn cast_negative_unknown_role() {
        assert!(matches!(
            parse_cast(
                &sx("((auctioneer @auc) (bidder @b1) (ghost @g))"),
                &auction_roles()
            ),
            Err(R6Violation::UnknownRole { .. })
        ));
    }

    #[test]
    fn cast_negative_missing_binding() {
        assert!(matches!(
            parse_cast(&sx("((auctioneer @auc))"), &auction_roles()),
            Err(R6Violation::MalformedCast { .. })
        ));
    }

    #[test]
    fn cast_negative_duplicate_binding() {
        assert!(matches!(
            parse_cast(
                &sx("((auctioneer @auc) (auctioneer @b) (bidder @b1))"),
                &auction_roles()
            ),
            Err(R6Violation::MalformedCast { .. })
        ));
    }

    #[test]
    fn cast_negative_indexed_no_keys() {
        assert!(matches!(
            parse_cast(&sx("((auctioneer @auc) (bidder))"), &auction_roles()),
            Err(R6Violation::MalformedCast { .. })
        ));
    }

    #[test]
    fn cast_negative_non_list_binding() {
        assert!(matches!(
            parse_cast(&sx("(auctioneer @auc)"), &auction_roles()),
            Err(R6Violation::MalformedCast { .. })
        ));
    }

    // ---- parse_wrapper_cast / parse_dialect_pin (REQ-628, TEST-642) ----

    fn hex64(c: char) -> String {
        core::iter::repeat(c).take(64).collect()
    }

    #[test]
    fn wrapper_cast_without_pin_has_none() {
        let cast = parse_wrapper_cast(&[sx("((auctioneer @auc) (bidder @b1))")], &auction_roles())
            .unwrap();
        assert_eq!(cast.dialect_pin, None);
    }

    #[test]
    fn wrapper_cast_with_wellformed_pin_carries_it() {
        let pin = alloc::format!("f1220{}", hex64('a'));
        let cast = parse_wrapper_cast(
            &[
                sx("((auctioneer @auc) (bidder @b1))"),
                sx(":dialect"),
                sx(&pin),
            ],
            &auction_roles(),
        )
        .unwrap();
        assert_eq!(cast.dialect_pin.as_deref(), Some(pin.as_str()));
    }

    #[test]
    fn pin_negative_bad_prefix() {
        assert!(matches!(
            parse_dialect_pin(&sx(&alloc::format!("md5:{}", hex64('a')))),
            Err(R6Violation::MalformedCast { .. })
        ));
    }

    #[test]
    fn pin_negative_wrong_length() {
        assert!(matches!(
            parse_dialect_pin(&sx("f1220abc")),
            Err(R6Violation::MalformedCast { .. })
        ));
        assert!(matches!(
            parse_dialect_pin(&sx(&alloc::format!("f1220{}a", hex64('a')))),
            Err(R6Violation::MalformedCast { .. })
        ));
    }

    #[test]
    fn pin_negative_non_hex_digits() {
        // 'g' is outside the hex alphabet; 'A' is uppercase — both rejected,
        // never case-folded or repaired (LangSec principle 4).
        assert!(matches!(
            parse_dialect_pin(&sx(&alloc::format!("f1220{}", hex64('g')))),
            Err(R6Violation::MalformedCast { .. })
        ));
        assert!(matches!(
            parse_dialect_pin(&sx(&alloc::format!("f1220{}", hex64('A')))),
            Err(R6Violation::MalformedCast { .. })
        ));
    }

    #[test]
    fn pin_negative_non_text_value() {
        assert!(matches!(
            parse_dialect_pin(&sx("(sha256 x)")),
            Err(R6Violation::MalformedCast { .. })
        ));
    }

    #[test]
    fn wrapper_cast_negative_extra_fields() {
        let pin = alloc::format!("f1220{}", hex64('a'));
        // Trailing garbage after the pin.
        assert!(matches!(
            parse_wrapper_cast(
                &[
                    sx("((auctioneer @auc) (bidder @b1))"),
                    sx(":dialect"),
                    sx(&pin),
                    sx("junk"),
                ],
                &auction_roles(),
            ),
            Err(R6Violation::MalformedCast { .. })
        ));
        // Unknown keyword field in the pin position.
        assert!(matches!(
            parse_wrapper_cast(
                &[
                    sx("((auctioneer @auc) (bidder @b1))"),
                    sx(":lang"),
                    sx(&pin),
                ],
                &auction_roles(),
            ),
            Err(R6Violation::MalformedCast { .. })
        ));
    }
}