Skip to main content

cbcl_core/
dialect.rs

1//! Dialect definitions, resource bounds, and dialect registry.
2//!
3//! Mirrors `Dialect.lean` and the dialect-management parts of `Agent.lean`
4//! from the Lean 4 proof library.
5
6#![forbid(unsafe_code)]
7
8use crate::protocol::CausalProtocol;
9use crate::r1::{r1_violations, verify_r1_dialect};
10use crate::r2::verify_r2;
11use crate::r3::{r3_violations, verify_r3};
12use crate::r4::{check_r4, R4Result, Signer};
13use crate::r5::{r5_violations_with_ancestors, verify_r5_with_ancestors};
14use crate::r6::{derive_envelope_routes, r6_violations};
15use crate::role::{CausalLocality, R6Violation as R6ViolationDetail, RoleAnnotation, RoleDecl};
16use crate::sexpr::{Atom, SExpr};
17use crate::shape::ShapeConstraint;
18use alloc::string::String;
19use alloc::vec;
20use alloc::vec::Vec;
21use core::fmt;
22
23/// Resource bounds for dialect evaluation (REQ-020).
24#[derive(Debug, Clone, PartialEq, Eq, Hash)]
25#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
26pub struct ResourceBounds {
27    pub max_depth: u32,
28    pub max_expansion_size: u32,
29}
30
31impl ResourceBounds {
32    /// Check if bounds are valid (REQ-024).
33    pub fn is_valid(&self) -> bool {
34        self.max_depth > 0
35            && self.max_depth <= 64
36            && self.max_expansion_size > 0
37            && self.max_expansion_size <= 8192
38    }
39}
40
41/// Error returned when dialect installation fails.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum DialectInstallError {
44    ResourceLimit {
45        dialect_name: String,
46        detail: String,
47    },
48    /// A performative template references its own name (R1 violation).
49    R1Violation {
50        dialect_name: String,
51        recursive: Vec<String>,
52    },
53    /// The dialect's resource bounds are invalid (R2 violation).
54    R2Violation { dialect_name: String },
55    /// The protocol's expanded step count — after `(repeat k …)`
56    /// macro-expansion (SPEC-015 REQ-704) — is not within the dialect's
57    /// declared R2 expansion budget. This is what keeps `k` honest:
58    /// repetition is priced in R2's existing declared-bounds currency.
59    R2ProtocolBudgetExceeded {
60        dialect_name: String,
61        /// Post-expansion protocol step count (`begin` excluded).
62        expanded_steps: u32,
63        /// The dialect's declared `max-expansion-size` bound.
64        budget: u32,
65    },
66    /// The dialect redefines one or more core performatives (R3 violation).
67    R3Violation {
68        dialect_name: String,
69        redefined: Vec<String>,
70    },
71    /// The dialect's signature failed verification (R4 violation).
72    R4Violation { dialect_name: String },
73    /// The state clause is ill-formed or the self-address is wrong (R7,
74    /// SPEC-019 REQ-1910).
75    R7Violation {
76        dialect_name: String,
77        violations: Vec<crate::r7::R7Violation>,
78    },
79    /// A shape constraint is malformed (R5 violation).
80    R5Violation {
81        dialect_name: String,
82        shape_errors: Vec<String>,
83    },
84    /// The dialect's role layer is ill-formed (R6 violation, SPEC-014
85    /// REQ-627).
86    R6Violation {
87        dialect_name: String,
88        violations: Vec<R6ViolationDetail>,
89    },
90}
91
92impl fmt::Display for DialectInstallError {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        match self {
95            DialectInstallError::ResourceLimit {
96                dialect_name,
97                detail,
98            } => write!(f, "resource-limit: dialect {dialect_name}: {detail}"),
99            DialectInstallError::R1Violation {
100                dialect_name,
101                recursive,
102            } => {
103                write!(
104                    f,
105                    "R1 violation: dialect '{}' has recursive performative(s): {}",
106                    dialect_name,
107                    recursive.join(", ")
108                )
109            }
110            DialectInstallError::R2Violation { dialect_name } => {
111                write!(
112                    f,
113                    "R2 violation: dialect '{}' has invalid resource bounds",
114                    dialect_name,
115                )
116            }
117            DialectInstallError::R2ProtocolBudgetExceeded {
118                dialect_name,
119                expanded_steps,
120                budget,
121            } => {
122                write!(
123                    f,
124                    "R2 violation: dialect '{}' protocol expands to {} steps, \
125                     exceeding the declared expansion budget {}",
126                    dialect_name, expanded_steps, budget,
127                )
128            }
129            DialectInstallError::R3Violation {
130                dialect_name,
131                redefined,
132            } => {
133                write!(
134                    f,
135                    "R3 violation: dialect '{}' redefines core performative(s): {}",
136                    dialect_name,
137                    redefined.join(", ")
138                )
139            }
140            DialectInstallError::R4Violation { dialect_name } => {
141                write!(
142                    f,
143                    "R4 violation: dialect '{}' has an invalid signature",
144                    dialect_name,
145                )
146            }
147            DialectInstallError::R5Violation {
148                dialect_name,
149                shape_errors,
150            } => {
151                write!(
152                    f,
153                    "R5 violation: dialect '{}' has malformed shape(s): {}",
154                    dialect_name,
155                    shape_errors.join("; ")
156                )
157            }
158            DialectInstallError::R6Violation {
159                dialect_name,
160                violations,
161            } => {
162                write!(f, "R6 violation: dialect '{dialect_name}':")?;
163                for v in violations {
164                    write!(f, " {v};")?;
165                }
166                Ok(())
167            }
168            DialectInstallError::R7Violation {
169                dialect_name,
170                violations,
171            } => {
172                write!(f, "R7 violation: dialect '{dialect_name}':")?;
173                for v in violations {
174                    write!(f, " {v};")?;
175                }
176                Ok(())
177            }
178        }
179    }
180}
181
182/// A performative definition within a dialect (REQ-021).
183#[derive(Debug, Clone, PartialEq, Eq)]
184#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
185pub struct PerformativeDef {
186    pub name: String,
187    pub params: Vec<SExpr>,
188    pub template: SExpr,
189    /// `:from`/`:to` role annotation (SPEC-014 REQ-621, CON-600).
190    #[cfg_attr(feature = "serde", serde(default))]
191    pub role: Option<RoleAnnotation>,
192}
193
194/// A CBCL dialect (REQ-022).
195///
196/// Mirrors `CBCL.Dialect` in `Dialect.lean:34–44`.
197#[derive(Debug, Clone, PartialEq, Eq)]
198#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
199pub struct Dialect {
200    #[cfg_attr(feature = "serde", serde(default))]
201    pub types: alloc::collections::BTreeMap<String, SExpr>,
202    pub name: String,
203    /// Parent dialect names (Lean: `extends_ : List String`).
204    pub extends: Vec<String>,
205    pub author: Option<String>,
206    pub performatives: Vec<PerformativeDef>,
207    pub resources: ResourceBounds,
208    pub examples: Vec<SExpr>,
209    pub signature: Option<Vec<u8>>,
210    /// Canonical content hash, `f1220<lowercase-hex64>` over
211    /// [`crate::canonical::dialect_canonical_bytes`] (SPEC-014 REQ-628).
212    ///
213    /// Invariant: every dialect installed into a [`DialectRegistry`] has
214    /// `Some(..)` — installation computes the hash when this is `None`.
215    /// A pre-declared hash (e.g. a `:hash` clause in dialect source) is
216    /// preserved verbatim so wrappers can compare the claim against the
217    /// computed value and reject mismatches.
218    pub hash: Option<String>,
219    pub protocol: Option<String>,
220    /// Causal protocol declaration (REQ-200, REQ-201).
221    pub causal_protocol: Option<CausalProtocol>,
222    /// Shape constraints for expanded messages (REQ-220).
223    pub shapes: Vec<ShapeConstraint>,
224    /// Declared roles (SPEC-014 REQ-621, CON-600); empty = role-free dialect.
225    #[cfg_attr(feature = "serde", serde(default))]
226    pub roles: Vec<RoleDecl>,
227    /// `(:causal-locality derive|reject)` (SPEC-015 REQ-709, ADR-704):
228    /// under `Derive`, R6(vi) failures compile into the recorded
229    /// envelope-routing table instead of rejecting; the default `Reject`
230    /// preserves v1 semantics bit-for-bit.
231    #[cfg_attr(feature = "serde", serde(default))]
232    pub causal_locality: CausalLocality,
233    /// `(state …)` clause (SPEC-019 REQ-1902); `None` = no state layer.
234    #[cfg_attr(feature = "serde", serde(default))]
235    pub state: Option<crate::state::StateClause>,
236    /// `(:state-bounds …)` (SPEC-019 REQ-1904); `None` = the defaults.
237    #[cfg_attr(feature = "serde", serde(default))]
238    pub state_bounds: Option<crate::state::StateBounds>,
239}
240
241impl Dialect {
242    /// Check if this dialect defines a performative with the given name (REQ-025).
243    pub fn defines_performative(&self, name: &str) -> bool {
244        self.performatives.iter().any(|p| p.name == name)
245    }
246
247    /// Find a performative definition by name (REQ-025).
248    pub fn find_performative(&self, name: &str) -> Option<&PerformativeDef> {
249        self.performatives.iter().find(|p| p.name == name)
250    }
251
252    /// Return the names of all performatives in this dialect.
253    pub fn performative_names(&self) -> Vec<&str> {
254        self.performatives.iter().map(|p| p.name.as_str()).collect()
255    }
256}
257
258/// Effect-template helper: `(effect <action>)`.
259fn effect_template(action: &str) -> SExpr {
260    SExpr::List(vec![
261        SExpr::Atom(Atom::Symbol(String::from("effect"))),
262        SExpr::Atom(Atom::Symbol(String::from(action))),
263    ])
264}
265
266/// Map from core performative name to its effect action, matching Lean `baseDialect`.
267const CORE_EFFECT_ACTIONS: [(&str, &str); 8] = [
268    ("tell", "send-message"),
269    ("ask", "send-query"),
270    ("reply", "send-reply"),
271    ("error", "signal-error"),
272    ("ok", "acknowledge"),
273    ("cancel", "cancel-conversation"),
274    ("hello", "announce-presence"),
275    ("bye", "announce-departure"),
276];
277
278/// The base dialect with 8 core performatives (REQ-023).
279///
280/// Templates use the `(effect <action>)` form matching `baseDialect` in
281/// `Dialect.lean:53–68`.
282pub fn base_dialect() -> Dialect {
283    Dialect {
284        types: Default::default(),
285        state: None,
286        state_bounds: None,
287        causal_locality: CausalLocality::Reject,
288        roles: Vec::new(),
289        name: String::from("cbcl-base"),
290        extends: Vec::new(),
291        author: Some(String::from("@cbcl-system")),
292        performatives: CORE_EFFECT_ACTIONS
293            .iter()
294            .map(|&(name, action)| PerformativeDef {
295                role: None,
296                name: String::from(name),
297                params: Vec::new(),
298                template: effect_template(action),
299            })
300            .collect(),
301        resources: ResourceBounds {
302            max_depth: 8,
303            max_expansion_size: 512,
304        },
305        examples: Vec::new(),
306        signature: None,
307        hash: None,
308        protocol: None,
309        causal_protocol: None,
310        shapes: Vec::new(),
311    }
312}
313
314// ---------------------------------------------------------------------------
315// DialectRegistry — ordered collection with base dialect at index 0
316// ---------------------------------------------------------------------------
317
318/// An ordered dialect collection with the base dialect always at index 0.
319///
320/// Mirrors the `dialects : List Dialect` field on `Agent` in `Agent.lean`,
321/// extracted as a first-class type so it can be shared across agent and
322/// pipeline contexts.
323///
324/// Invariant: `dialects[0] == base_dialect()`.
325#[derive(Debug, Clone, PartialEq, Eq)]
326#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
327pub struct DialectRegistry {
328    dialects: Vec<Dialect>,
329}
330
331impl DialectRegistry {
332    /// Create a new registry containing only the base dialect.
333    pub fn new() -> Self {
334        Self {
335            dialects: vec![base_dialect()],
336        }
337    }
338
339    /// Install a dialect after verifying R1, R2, and R3 (REQ-034, REQ-060–062, REQ-070, REQ-080).
340    ///
341    /// Returns an error if the dialect contains recursive performatives (R1),
342    /// has invalid resource bounds (R2), or redefines any of the 8 core
343    /// performatives (R3).
344    /// Matches `Agent.installDialect` in `Agent.lean:38–39`
345    /// with the R1 precondition from `R1NoRecursion.lean:38–40`,
346    /// the R2 precondition from `R2ResourceBounds.lean:59–63`,
347    /// and the R3 precondition from `R3CorePreservation.lean:57`.
348    pub fn install(&mut self, mut d: Dialect) -> Result<(), DialectInstallError> {
349        crate::contracts::install(&mut d).map_err(|error| {
350            if error.starts_with("resource-limit:") {
351                DialectInstallError::ResourceLimit {
352                    dialect_name: d.name.clone(),
353                    detail: error,
354                }
355            } else {
356                DialectInstallError::R5Violation {
357                    dialect_name: d.name.clone(),
358                    shape_errors: alloc::vec![error],
359                }
360            }
361        })?;
362        if let Some(state) = &mut d.state {
363            state.resolve_lattices();
364        }
365        if !verify_r1_dialect(&d) {
366            return Err(DialectInstallError::R1Violation {
367                recursive: r1_violations(&d),
368                dialect_name: d.name,
369            });
370        }
371        if !verify_r2(&d) {
372            return Err(DialectInstallError::R2Violation {
373                dialect_name: d.name,
374            });
375        }
376        Self::check_protocol_expansion_budget(&d)?;
377        if !verify_r3(&d) {
378            return Err(DialectInstallError::R3Violation {
379                redefined: r3_violations(&d),
380                dialect_name: d.name,
381            });
382        }
383        let ancestors = self.resolve_ancestors(&d);
384        if !verify_r5_with_ancestors(&d, &ancestors) {
385            return Err(DialectInstallError::R5Violation {
386                shape_errors: r5_violations_with_ancestors(&d, &ancestors),
387                dialect_name: d.name,
388            });
389        }
390        // R6 (SPEC-014 REQ-627; SPEC-015 REQ-709): dialect-level role
391        // checks; role-free dialects pass trivially (REQ-607). Under
392        // `(:causal-locality derive)`, R6(vi) findings compile into the
393        // envelope-routing table instead of rejecting.
394        Self::apply_r6(&mut d)?;
395        crate::context::resolve(&mut d);
396        // R7 (SPEC-019 REQ-1910): state-clause well-formedness and the
397        // self-addressed name; dialects with neither clause pass trivially.
398        let r7 = crate::r7::r7_violations(&d);
399        if !r7.is_empty() {
400            return Err(DialectInstallError::R7Violation {
401                dialect_name: d.name,
402                violations: r7,
403            });
404        }
405        Self::ensure_hash(&mut d);
406        #[cfg(feature = "tracing")]
407        tracing::event!(
408            tracing::Level::INFO,
409            dialect = %d.name,
410            "dialect_install_count"
411        );
412        crate::canonical::canonicalise_dialect(&mut d);
413        self.dialects.push(d);
414        Ok(())
415    }
416
417    /// R6 gate (SPEC-014 REQ-627; SPEC-015 REQ-709, ADR-704).
418    ///
419    /// Under the default `(:causal-locality reject)` any violation rejects,
420    /// exactly as v1. Under `derive`, R6(vi) `NotCausallyLocal` findings
421    /// stop being rejection conditions and become the derivation's
422    /// worklist: every *other* violation class still rejects, and when none
423    /// remain the envelope-widening closure is derived
424    /// ([`derive_envelope_routes`]) and recorded on the dialect. Payload
425    /// `:to` sets are untouched — the closure only adds envelope routes.
426    fn apply_r6(d: &mut Dialect) -> Result<(), DialectInstallError> {
427        let r6 = r6_violations(d);
428        let deriving = matches!(d.causal_locality, CausalLocality::Derive(_));
429        let violations: Vec<R6ViolationDetail> = if deriving {
430            r6.into_iter()
431                .filter(|v| !matches!(v, R6ViolationDetail::NotCausallyLocal { .. }))
432                .collect()
433        } else {
434            r6
435        };
436        if !violations.is_empty() {
437            return Err(DialectInstallError::R6Violation {
438                violations,
439                dialect_name: d.name.clone(),
440            });
441        }
442        if deriving {
443            // Deterministic and idempotent: the closure is a pure function
444            // of the dialect body, so every independent install records the
445            // identical table (the replicated-choreographer property
446            // extended from projection to repair).
447            d.causal_locality = CausalLocality::Derive(derive_envelope_routes(d));
448        }
449        Ok(())
450    }
451
452    /// Populate `d.hash` with the canonical content hash when absent
453    /// (SPEC-014 REQ-628: every installed dialect carries `Some(hash)`).
454    ///
455    /// A pre-declared hash is left untouched: overwriting it would defeat
456    /// wrappers that compare the declared claim against the computed value
457    /// after install (e.g. the wasm bindings' `:hash` verification).
458    ///
459    /// SIMPLIFY: only *installed* dialects are hashed — the base dialect
460    /// seeded by `DialectRegistry::new()` keeps `hash: None` because
461    /// `is_well_formed()` (and callers) compare `dialects[0]` against
462    /// `base_dialect()` by equality. Upgrade path: make `base_dialect()`
463    /// itself return `hash: Some(dialect_hash(..))` and update the golden
464    /// expectations that pin its serialized form.
465    fn ensure_hash(d: &mut Dialect) {
466        if d.hash.is_none() {
467            d.hash = Some(crate::canonical::dialect_hash(d));
468        }
469    }
470
471    /// SPEC-015 REQ-704: the protocol's expanded step count counts against
472    /// R2's declared expansion budget. By install time, `(repeat k …)`
473    /// forms are already macro-expanded into the `CausalProtocol` (the
474    /// parser expands once at parse), so the count here *is* the expanded
475    /// size; a hand-unrolled equivalent protocol is priced identically.
476    ///
477    /// Uses R2's strict-`<` idiom (`ResourceState::add_expansion` in
478    /// `R2ResourceBounds.lean:43–47`): a count at or above the declared
479    /// bound is a typed rejection.
480    fn check_protocol_expansion_budget(d: &Dialect) -> Result<(), DialectInstallError> {
481        if let Some(cp) = &d.causal_protocol {
482            let expanded_steps = cp.expansion_size();
483            if expanded_steps >= d.resources.max_expansion_size {
484                return Err(DialectInstallError::R2ProtocolBudgetExceeded {
485                    dialect_name: d.name.clone(),
486                    expanded_steps,
487                    budget: d.resources.max_expansion_size,
488                });
489            }
490        }
491        Ok(())
492    }
493
494    /// Resolve `d.extends` to currently-installed ancestor dialects (REQ-206).
495    ///
496    /// Names that do not match an installed dialect are silently skipped —
497    /// install-time R5 will only credit performatives from ancestors that the
498    /// registry actually knows about. The shorthand `cbcl` is aliased to the
499    /// canonical base dialect name `cbcl-base` since dialect literals
500    /// commonly write `(extends cbcl)` while the registry stores the base
501    /// under its full name.
502    ///
503    /// Public so standalone tooling (e.g. `cbcl verify`) can match install-time
504    /// R5 semantics by feeding the result into [`crate::r5::verify_r5_with_ancestors`].
505    pub fn resolve_ancestors<'a>(&'a self, d: &Dialect) -> Vec<&'a Dialect> {
506        d.extends
507            .iter()
508            .filter_map(|name| {
509                let resolved = if name == "cbcl" {
510                    "cbcl-base"
511                } else {
512                    name.as_str()
513                };
514                self.find_by_name(resolved)
515            })
516            .collect()
517    }
518
519    /// Install a dialect after verifying R1–R4 (REQ-034, REQ-060–062, REQ-070, REQ-080, REQ-090–091).
520    ///
521    /// Like [`install`](Self::install) but additionally checks R4 signature
522    /// integrity using the provided signer. Unsigned dialects are accepted
523    /// (the spec allows them with a warning); dialects with *invalid*
524    /// signatures are rejected with [`DialectInstallError::R4Violation`].
525    ///
526    /// Returns `((), R4Result)` on success so callers can inspect whether the
527    /// dialect was signed or unsigned.
528    pub fn install_with_signer(
529        &mut self,
530        mut d: Dialect,
531        signer: &dyn Signer,
532    ) -> Result<R4Result, DialectInstallError> {
533        crate::contracts::install(&mut d).map_err(|error| {
534            if error.starts_with("resource-limit:") {
535                DialectInstallError::ResourceLimit {
536                    dialect_name: d.name.clone(),
537                    detail: error,
538                }
539            } else {
540                DialectInstallError::R5Violation {
541                    dialect_name: d.name.clone(),
542                    shape_errors: alloc::vec![error],
543                }
544            }
545        })?;
546        // R1–R3 checks (same as install)
547        if !verify_r1_dialect(&d) {
548            return Err(DialectInstallError::R1Violation {
549                recursive: r1_violations(&d),
550                dialect_name: d.name,
551            });
552        }
553        if !verify_r2(&d) {
554            return Err(DialectInstallError::R2Violation {
555                dialect_name: d.name,
556            });
557        }
558        Self::check_protocol_expansion_budget(&d)?;
559        if !verify_r3(&d) {
560            return Err(DialectInstallError::R3Violation {
561                redefined: r3_violations(&d),
562                dialect_name: d.name,
563            });
564        }
565        let ancestors = self.resolve_ancestors(&d);
566        if !verify_r5_with_ancestors(&d, &ancestors) {
567            return Err(DialectInstallError::R5Violation {
568                shape_errors: r5_violations_with_ancestors(&d, &ancestors),
569                dialect_name: d.name,
570            });
571        }
572        // R6 (SPEC-014 REQ-627; SPEC-015 REQ-709): as in `install`. The
573        // derived routing table is excluded from the canonical signing
574        // form (only the declared mode is signed), so recording it here
575        // cannot invalidate the signature checked next.
576        Self::apply_r6(&mut d)?;
577        // R4 check: invalid signatures are rejected; unsigned is accepted.
578        // The canonical signing form (`canonical::to_signable_sexpr`) covers
579        // every semantics-relevant field, including `causal_protocol` and
580        // `shapes`, so a Valid signature binds runtime acceptance.
581        let r4 = check_r4(&d, signer);
582        if r4 == R4Result::Invalid {
583            return Err(DialectInstallError::R4Violation {
584                dialect_name: d.name,
585            });
586        }
587        // The hash is over the signable form, which excludes integrity
588        // fields, so populating it after the R4 check cannot invalidate
589        // the just-verified signature.
590        Self::ensure_hash(&mut d);
591        #[cfg(feature = "tracing")]
592        tracing::event!(
593            tracing::Level::INFO,
594            dialect = %d.name,
595            r4_result = ?r4,
596            "dialect_install_count"
597        );
598        crate::canonical::canonicalise_dialect(&mut d);
599        self.dialects.push(d);
600        Ok(r4)
601    }
602
603    /// The number of installed dialects (including the base dialect).
604    pub fn len(&self) -> usize {
605        self.dialects.len()
606    }
607
608    /// Always false — the registry always contains at least the base dialect.
609    pub fn is_empty(&self) -> bool {
610        false
611    }
612
613    /// Well-formedness check: base dialect is at index 0 (REQ-032).
614    pub fn is_well_formed(&self) -> bool {
615        !self.dialects.is_empty() && self.dialects[0] == base_dialect()
616    }
617
618    /// Get a dialect by index.
619    pub fn get(&self, index: usize) -> Option<&Dialect> {
620        self.dialects.get(index)
621    }
622
623    /// Get a dialect by name.
624    pub fn find_by_name(&self, name: &str) -> Option<&Dialect> {
625        self.dialects.iter().find(|d| d.name == name)
626    }
627
628    /// The base dialect, if it defines `name` (REQ-033).
629    ///
630    /// This is the *only* name-based lookup dispatch performs, and it is
631    /// confined to the base dialect because R3 guarantees the eight core
632    /// performatives have exactly one definer. A custom performative is never
633    /// looked up this way: it is resolved against the dialect its `(lang …)`
634    /// wrapper names, so which definition applies is fixed by the message
635    /// rather than by the installed set. That is what allows two dialects to
636    /// define the same performative name without conflict.
637    ///
638    /// Matches `Agent.baseDefinerOf` in `Agent.lean`.
639    pub fn base_definer_of(&self, name: &str) -> Option<&Dialect> {
640        self.dialects
641            .first()
642            .filter(|d| d.defines_performative(name))
643    }
644
645    /// Every installed dialect defining `name`, in installation order.
646    ///
647    /// Introspection only — capability queries, diagnostics, tooling. It is
648    /// deliberately not a dispatch path: several dialects may legitimately
649    /// define one name, and choosing between them is the `(lang …)` wrapper's
650    /// job, not the registry's.
651    pub fn dialects_defining<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Dialect> {
652        self.dialects
653            .iter()
654            .filter(move |d| d.defines_performative(name))
655    }
656
657    /// Iterate over all installed dialects in order.
658    pub fn iter(&self) -> core::slice::Iter<'_, Dialect> {
659        self.dialects.iter()
660    }
661
662    /// Return a slice of all installed dialects.
663    pub fn as_slice(&self) -> &[Dialect] {
664        &self.dialects
665    }
666}
667
668impl Default for DialectRegistry {
669    fn default() -> Self {
670        Self::new()
671    }
672}
673
674impl<'a> IntoIterator for &'a DialectRegistry {
675    type Item = &'a Dialect;
676    type IntoIter = core::slice::Iter<'a, Dialect>;
677
678    fn into_iter(self) -> Self::IntoIter {
679        self.iter()
680    }
681}
682
683#[cfg(test)]
684mod tests {
685    use super::*;
686
687    #[test]
688    fn base_dialect_has_8_performatives() {
689        let d = base_dialect();
690        assert_eq!(d.performatives.len(), 8);
691        assert_eq!(d.name, "cbcl-base");
692    }
693
694    #[test]
695    fn base_dialect_templates_are_effect_forms() {
696        let d = base_dialect();
697        let tell = d.find_performative("tell").unwrap();
698        // Template should be (effect send-message)
699        match &tell.template {
700            SExpr::List(items) => {
701                assert_eq!(items.len(), 2);
702                assert!(items[0].is_symbol("effect"));
703                assert!(items[1].is_symbol("send-message"));
704            }
705            _ => panic!("expected list template"),
706        }
707    }
708
709    #[test]
710    fn base_dialect_resource_bounds_valid() {
711        let d = base_dialect();
712        assert!(d.resources.is_valid());
713    }
714
715    #[test]
716    fn base_dialect_extends_is_empty() {
717        let d = base_dialect();
718        assert!(d.extends.is_empty());
719    }
720
721    #[test]
722    fn defines_and_find_performative() {
723        let d = base_dialect();
724        assert!(d.defines_performative("tell"));
725        assert!(!d.defines_performative("nonexistent"));
726        assert!(d.find_performative("ask").is_some());
727    }
728
729    #[test]
730    fn performative_names() {
731        let d = base_dialect();
732        let names = d.performative_names();
733        assert_eq!(names.len(), 8);
734        assert!(names.contains(&"tell"));
735        assert!(names.contains(&"bye"));
736    }
737
738    #[test]
739    fn resource_bounds_validation() {
740        let valid = ResourceBounds {
741            max_depth: 8,
742            max_expansion_size: 512,
743        };
744        assert!(valid.is_valid());
745
746        let invalid = ResourceBounds {
747            max_depth: 0,
748            max_expansion_size: 512,
749        };
750        assert!(!invalid.is_valid());
751
752        let too_large = ResourceBounds {
753            max_depth: 65,
754            max_expansion_size: 512,
755        };
756        assert!(!too_large.is_valid());
757    }
758
759    // ---- DialectRegistry tests ----
760
761    #[test]
762    fn registry_new_has_base_dialect() {
763        let reg = DialectRegistry::new();
764        assert_eq!(reg.len(), 1);
765        assert!(reg.is_well_formed());
766        assert_eq!(reg.get(0).unwrap().name, "cbcl-base");
767    }
768
769    #[test]
770    fn registry_install_appends() {
771        let mut reg = DialectRegistry::new();
772        let planning = Dialect {
773            types: Default::default(),
774            roles: Vec::new(),
775            state: None,
776            state_bounds: None,
777            causal_locality: Default::default(),
778            name: String::from("cbcl-planning"),
779            extends: vec![String::from("cbcl")],
780            author: Some(String::from("@planning-authority")),
781            performatives: vec![PerformativeDef {
782                role: None,
783                name: String::from("propose-step"),
784                params: vec![],
785                template: effect_template("propose"),
786            }],
787            resources: ResourceBounds {
788                max_depth: 16,
789                max_expansion_size: 1024,
790            },
791            examples: vec![],
792            signature: None,
793            hash: None,
794            protocol: Some(String::from("ed25519")),
795            causal_protocol: None,
796            shapes: Vec::new(),
797        };
798        reg.install(planning).unwrap();
799        assert_eq!(reg.len(), 2);
800        assert!(reg.is_well_formed());
801        assert_eq!(reg.get(1).unwrap().name, "cbcl-planning");
802    }
803
804    /// A dialect defining a single custom performative `greet`.
805    fn greeter(name: &str) -> Dialect {
806        Dialect {
807            types: Default::default(),
808            roles: Vec::new(),
809            state: None,
810            state_bounds: None,
811            causal_locality: Default::default(),
812            name: String::from(name),
813            extends: vec![String::from("cbcl")],
814            author: None,
815            performatives: vec![PerformativeDef {
816                role: None,
817                name: String::from("greet"),
818                params: vec![],
819                template: effect_template("greet-action"),
820            }],
821            resources: ResourceBounds {
822                max_depth: 8,
823                max_expansion_size: 512,
824            },
825            examples: vec![],
826            signature: None,
827            hash: None,
828            protocol: None,
829            causal_protocol: None,
830            shapes: Vec::new(),
831        }
832    }
833
834    #[test]
835    fn base_definer_of_finds_core_performatives() {
836        let reg = DialectRegistry::new();
837        assert_eq!(reg.base_definer_of("tell").unwrap().name, "cbcl-base");
838    }
839
840    /// REQ-033: core dispatch consults the base dialect only, so installing
841    /// dialects can never change what a core performative means.
842    #[test]
843    fn base_definer_of_ignores_installed_dialects() {
844        let mut reg = DialectRegistry::new();
845        reg.install(greeter("first")).unwrap();
846        assert!(reg.base_definer_of("greet").is_none());
847    }
848
849    /// REQ-033: two dialects defining one performative name is legitimate.
850    /// The `(lang …)` wrapper chooses between them, so the registry reports
851    /// both instead of picking or rejecting.
852    #[test]
853    fn dialects_defining_reports_every_definer_in_install_order() {
854        let mut reg = DialectRegistry::new();
855        reg.install(greeter("first")).unwrap();
856        reg.install(greeter("second")).unwrap();
857        let names: Vec<&str> = reg
858            .dialects_defining("greet")
859            .map(|d| d.name.as_str())
860            .collect();
861        assert_eq!(names, vec!["first", "second"]);
862    }
863
864    #[test]
865    fn registry_install_rejects_r3_violation() {
866        let mut reg = DialectRegistry::new();
867        let bad = Dialect {
868            types: Default::default(),
869            roles: Vec::new(),
870            state: None,
871            state_bounds: None,
872            causal_locality: Default::default(),
873            name: String::from("bad-dialect"),
874            extends: vec![String::from("cbcl")],
875            author: None,
876            performatives: vec![PerformativeDef {
877                role: None,
878                name: String::from("tell"),
879                params: vec![],
880                template: effect_template("custom-tell"),
881            }],
882            resources: ResourceBounds {
883                max_depth: 8,
884                max_expansion_size: 512,
885            },
886            examples: vec![],
887            signature: None,
888            hash: None,
889            protocol: None,
890            causal_protocol: None,
891            shapes: Vec::new(),
892        };
893        let err = reg.install(bad).unwrap_err();
894        match err {
895            DialectInstallError::R3Violation {
896                dialect_name,
897                redefined,
898            } => {
899                assert_eq!(dialect_name, "bad-dialect");
900                assert_eq!(redefined, vec!["tell"]);
901            }
902            other => panic!("expected R3Violation, got {:?}", other),
903        }
904        // Registry unchanged.
905        assert_eq!(reg.len(), 1);
906    }
907
908    #[test]
909    fn registry_install_rejects_r2_violation() {
910        let mut reg = DialectRegistry::new();
911        let bad = Dialect {
912            types: Default::default(),
913            roles: Vec::new(),
914            state: None,
915            state_bounds: None,
916            causal_locality: Default::default(),
917            name: String::from("bad-bounds"),
918            extends: vec![String::from("cbcl")],
919            author: None,
920            performatives: vec![],
921            resources: ResourceBounds {
922                max_depth: 100, // exceeds max allowed 64
923                max_expansion_size: 512,
924            },
925            examples: vec![],
926            signature: None,
927            hash: None,
928            protocol: None,
929            causal_protocol: None,
930            shapes: Vec::new(),
931        };
932        let err = reg.install(bad).unwrap_err();
933        match err {
934            DialectInstallError::R2Violation { dialect_name } => {
935                assert_eq!(dialect_name, "bad-bounds");
936            }
937            _ => panic!("expected R2Violation"),
938        }
939        // Registry unchanged.
940        assert_eq!(reg.len(), 1);
941    }
942
943    #[test]
944    fn registry_install_rejects_zero_bounds() {
945        let mut reg = DialectRegistry::new();
946        let bad = Dialect {
947            types: Default::default(),
948            roles: Vec::new(),
949            state: None,
950            state_bounds: None,
951            causal_locality: Default::default(),
952            name: String::from("zero-depth"),
953            extends: vec![],
954            author: None,
955            performatives: vec![],
956            resources: ResourceBounds {
957                max_depth: 0,
958                max_expansion_size: 512,
959            },
960            examples: vec![],
961            signature: None,
962            hash: None,
963            protocol: None,
964            causal_protocol: None,
965            shapes: Vec::new(),
966        };
967        assert!(matches!(
968            reg.install(bad),
969            Err(DialectInstallError::R2Violation { .. })
970        ));
971    }
972
973    #[test]
974    fn registry_find_by_name() {
975        let reg = DialectRegistry::new();
976        assert!(reg.find_by_name("cbcl-base").is_some());
977        assert!(reg.find_by_name("nonexistent").is_none());
978    }
979
980    #[test]
981    fn registry_is_never_empty() {
982        let reg = DialectRegistry::new();
983        assert!(!reg.is_empty());
984    }
985
986    #[test]
987    fn registry_multi_dialect_install() {
988        // Matches test vector dial-ver-006: base + 3 installed = 4
989        let mut reg = DialectRegistry::new();
990        for name in &[
991            "cbcl-planning",
992            "cbcl-crosschain-transfer",
993            "cbcl-artifacts",
994        ] {
995            reg.install(Dialect {
996                types: Default::default(),
997                roles: Vec::new(),
998                state: None,
999                state_bounds: None,
1000                causal_locality: Default::default(),
1001                name: String::from(*name),
1002                extends: vec![String::from("cbcl")],
1003                author: None,
1004                performatives: vec![],
1005                resources: ResourceBounds {
1006                    max_depth: 8,
1007                    max_expansion_size: 512,
1008                },
1009                examples: vec![],
1010                signature: None,
1011                hash: None,
1012                protocol: Some(String::from("ed25519")),
1013                causal_protocol: None,
1014                shapes: Vec::new(),
1015            })
1016            .unwrap();
1017        }
1018        assert_eq!(reg.len(), 4);
1019        assert!(reg.is_well_formed());
1020    }
1021
1022    #[test]
1023    fn registry_iter() {
1024        let reg = DialectRegistry::new();
1025        let names: Vec<&str> = reg.iter().map(|d| d.name.as_str()).collect();
1026        assert_eq!(names, vec!["cbcl-base"]);
1027    }
1028
1029    #[test]
1030    fn registry_default() {
1031        let reg = DialectRegistry::default();
1032        assert!(reg.is_well_formed());
1033    }
1034
1035    // ---- R4 integration tests ----
1036
1037    use crate::r4::{R4Result, Signer};
1038
1039    struct MockSigner;
1040
1041    impl Signer for MockSigner {
1042        fn sign(&self, _data: &[u8]) -> Vec<u8> {
1043            alloc::vec![0xAA, 0xBB]
1044        }
1045        fn verify(&self, _data: &[u8], sig: &[u8]) -> bool {
1046            sig == [0xAA, 0xBB]
1047        }
1048    }
1049
1050    #[test]
1051    fn registry_install_with_signer_accepts_unsigned() {
1052        let mut reg = DialectRegistry::new();
1053        let d = Dialect {
1054            types: Default::default(),
1055            roles: Vec::new(),
1056            state: None,
1057            state_bounds: None,
1058            causal_locality: Default::default(),
1059            name: String::from("unsigned-dialect"),
1060            extends: vec![],
1061            author: None,
1062            performatives: vec![],
1063            resources: ResourceBounds {
1064                max_depth: 8,
1065                max_expansion_size: 512,
1066            },
1067            examples: vec![],
1068            signature: None,
1069            hash: None,
1070            protocol: None,
1071            causal_protocol: None,
1072            shapes: Vec::new(),
1073        };
1074        let result = reg.install_with_signer(d, &MockSigner).unwrap();
1075        assert_eq!(result, R4Result::Unsigned);
1076        assert_eq!(reg.len(), 2);
1077    }
1078
1079    #[test]
1080    fn registry_install_with_signer_accepts_valid_signature() {
1081        let mut reg = DialectRegistry::new();
1082        let d = Dialect {
1083            types: Default::default(),
1084            roles: Vec::new(),
1085            state: None,
1086            state_bounds: None,
1087            causal_locality: Default::default(),
1088            name: String::from("signed-dialect"),
1089            extends: vec![],
1090            author: None,
1091            performatives: vec![],
1092            resources: ResourceBounds {
1093                max_depth: 8,
1094                max_expansion_size: 512,
1095            },
1096            examples: vec![],
1097            signature: Some(alloc::vec![0xAA, 0xBB]),
1098            hash: None,
1099            protocol: Some(String::from("ed25519")),
1100            causal_protocol: None,
1101            shapes: Vec::new(),
1102        };
1103        let result = reg.install_with_signer(d, &MockSigner).unwrap();
1104        assert_eq!(result, R4Result::Valid);
1105        assert_eq!(reg.len(), 2);
1106    }
1107
1108    #[test]
1109    fn registry_install_with_signer_rejects_invalid_signature() {
1110        let mut reg = DialectRegistry::new();
1111        let d = Dialect {
1112            types: Default::default(),
1113            roles: Vec::new(),
1114            state: None,
1115            state_bounds: None,
1116            causal_locality: Default::default(),
1117            name: String::from("bad-sig-dialect"),
1118            extends: vec![],
1119            author: None,
1120            performatives: vec![],
1121            resources: ResourceBounds {
1122                max_depth: 8,
1123                max_expansion_size: 512,
1124            },
1125            examples: vec![],
1126            signature: Some(alloc::vec![0xFF, 0xFF]),
1127            hash: None,
1128            protocol: Some(String::from("ed25519")),
1129            causal_protocol: None,
1130            shapes: Vec::new(),
1131        };
1132        let err = reg.install_with_signer(d, &MockSigner).unwrap_err();
1133        match err {
1134            DialectInstallError::R4Violation { dialect_name } => {
1135                assert_eq!(dialect_name, "bad-sig-dialect");
1136            }
1137            other => panic!("expected R4Violation, got {:?}", other),
1138        }
1139        // Registry unchanged.
1140        assert_eq!(reg.len(), 1);
1141    }
1142
1143    #[test]
1144    fn registry_install_with_signer_still_checks_r1_r2_r3() {
1145        let mut reg = DialectRegistry::new();
1146        // R3 violation: redefines "tell"
1147        let d = Dialect {
1148            types: Default::default(),
1149            roles: Vec::new(),
1150            state: None,
1151            state_bounds: None,
1152            causal_locality: Default::default(),
1153            name: String::from("bad-r3"),
1154            extends: vec![],
1155            author: None,
1156            performatives: vec![PerformativeDef {
1157                role: None,
1158                name: String::from("tell"),
1159                params: vec![],
1160                template: effect_template("custom-tell"),
1161            }],
1162            resources: ResourceBounds {
1163                max_depth: 8,
1164                max_expansion_size: 512,
1165            },
1166            examples: vec![],
1167            signature: Some(alloc::vec![0xAA, 0xBB]),
1168            hash: None,
1169            protocol: None,
1170            causal_protocol: None,
1171            shapes: Vec::new(),
1172        };
1173        let err = reg.install_with_signer(d, &MockSigner).unwrap_err();
1174        assert!(matches!(err, DialectInstallError::R3Violation { .. }));
1175    }
1176
1177    #[test]
1178    fn r4_violation_display() {
1179        let err = DialectInstallError::R4Violation {
1180            dialect_name: String::from("bad"),
1181        };
1182        let msg = alloc::format!("{}", err);
1183        assert!(msg.contains("R4 violation"));
1184        assert!(msg.contains("bad"));
1185    }
1186
1187    // -- R4 binds causal_protocol/shapes via canonical signing form --
1188
1189    /// A signer whose verifier accepts only signatures produced by `sign(d)`
1190    /// over `dialect_canonical_bytes(d)` — useful for confirming that
1191    /// mutating bound fields invalidates the signature.
1192    struct CanonicalSigner;
1193
1194    impl Signer for CanonicalSigner {
1195        fn sign(&self, data: &[u8]) -> Vec<u8> {
1196            // Trivial reversible "signature": a hash of the bytes.
1197            let mut sum: u32 = 0x9e3779b9;
1198            for &b in data {
1199                sum = sum.wrapping_mul(33).wrapping_add(b as u32);
1200            }
1201            sum.to_le_bytes().to_vec()
1202        }
1203        fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
1204            self.sign(data) == sig
1205        }
1206    }
1207
1208    fn signed_dialect_with_protocol_and_shapes() -> Dialect {
1209        use crate::protocol::{CausalProtocol, NodeRef, StepDecl};
1210        use crate::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
1211        let mut steps = alloc::collections::BTreeMap::new();
1212        steps.insert(
1213            "begin".into(),
1214            StepDecl {
1215                performative: "begin".into(),
1216                predecessors: vec![],
1217                successors: vec![NodeRef::Single("greet".into())],
1218            },
1219        );
1220        steps.insert(
1221            "greet".into(),
1222            StepDecl {
1223                performative: "greet".into(),
1224                predecessors: vec![NodeRef::Single("begin".into())],
1225                successors: vec![],
1226            },
1227        );
1228        Dialect {
1229            types: Default::default(),
1230            roles: Vec::new(),
1231            state: None,
1232            state_bounds: None,
1233            causal_locality: Default::default(),
1234            name: String::from("bound-by-signature"),
1235            extends: vec![String::from("cbcl")],
1236            author: None,
1237            performatives: vec![PerformativeDef {
1238                role: None,
1239                name: String::from("greet"),
1240                params: vec![],
1241                template: SExpr::List(vec![
1242                    SExpr::Atom(Atom::Symbol(String::from("effect"))),
1243                    SExpr::Atom(Atom::Symbol(String::from("greet-action"))),
1244                ]),
1245            }],
1246            resources: ResourceBounds {
1247                max_depth: 8,
1248                max_expansion_size: 512,
1249            },
1250            examples: vec![],
1251            signature: None,
1252            hash: None,
1253            protocol: None,
1254            causal_protocol: Some(CausalProtocol { steps }),
1255            shapes: vec![ShapeConstraint {
1256                performative: String::from("greet"),
1257                rules: vec![ShapeRule::Require {
1258                    keyword: String::from("target"),
1259                    type_constraint: Some(TypeConstraint::String),
1260                    children: vec![],
1261                }],
1262            }],
1263        }
1264    }
1265
1266    #[test]
1267    fn signed_dialect_with_causal_protocol_now_installs() {
1268        // What used to be rejected as a stopgap should now install: the
1269        // canonical signing form covers causal_protocol.
1270        let mut d = signed_dialect_with_protocol_and_shapes();
1271        d.shapes = Vec::new(); // protocol-only case
1272        let bytes = crate::canonical::dialect_canonical_bytes(&d);
1273        d.signature = Some(CanonicalSigner.sign(&bytes));
1274
1275        let mut reg = DialectRegistry::new();
1276        let result = reg.install_with_signer(d, &CanonicalSigner).unwrap();
1277        assert_eq!(result, R4Result::Valid);
1278    }
1279
1280    #[test]
1281    fn signed_dialect_with_shapes_now_installs() {
1282        let mut d = signed_dialect_with_protocol_and_shapes();
1283        d.causal_protocol = None; // shapes-only case
1284        let bytes = crate::canonical::dialect_canonical_bytes(&d);
1285        d.signature = Some(CanonicalSigner.sign(&bytes));
1286
1287        let mut reg = DialectRegistry::new();
1288        let result = reg.install_with_signer(d, &CanonicalSigner).unwrap();
1289        assert_eq!(result, R4Result::Valid);
1290    }
1291
1292    #[test]
1293    fn mutating_causal_protocol_invalidates_existing_signature() {
1294        use crate::protocol::{NodeRef, StepDecl};
1295        // Sign a dialect, then mutate its causal_protocol without re-signing.
1296        // The previously-valid signature must no longer verify.
1297        let original = signed_dialect_with_protocol_and_shapes();
1298        let bytes = crate::canonical::dialect_canonical_bytes(&original);
1299        let sig = CanonicalSigner.sign(&bytes);
1300
1301        let mut tampered = original;
1302        tampered.signature = Some(sig);
1303        // Replace the protocol's `greet` step with a different predecessor.
1304        if let Some(ref mut p) = tampered.causal_protocol {
1305            p.steps.insert(
1306                "greet".into(),
1307                StepDecl {
1308                    performative: "greet".into(),
1309                    predecessors: vec![NodeRef::Single("ok".into())],
1310                    successors: vec![],
1311                },
1312            );
1313        }
1314
1315        let mut reg = DialectRegistry::new();
1316        let err = reg
1317            .install_with_signer(tampered, &CanonicalSigner)
1318            .unwrap_err();
1319        assert!(
1320            matches!(err, DialectInstallError::R4Violation { .. }),
1321            "expected R4 violation after causal_protocol tamper, got {err:?}"
1322        );
1323    }
1324
1325    #[test]
1326    fn mutating_shapes_invalidates_existing_signature() {
1327        use crate::shape::{ShapeRule, TypeConstraint};
1328        let original = signed_dialect_with_protocol_and_shapes();
1329        let bytes = crate::canonical::dialect_canonical_bytes(&original);
1330        let sig = CanonicalSigner.sign(&bytes);
1331
1332        let mut tampered = original;
1333        tampered.signature = Some(sig);
1334        // Add a new rule to the existing shape.
1335        if let Some(shape) = tampered.shapes.first_mut() {
1336            shape.rules.push(ShapeRule::Require {
1337                keyword: String::from("priority"),
1338                type_constraint: Some(TypeConstraint::Integer),
1339                children: vec![],
1340            });
1341        }
1342
1343        let mut reg = DialectRegistry::new();
1344        let err = reg
1345            .install_with_signer(tampered, &CanonicalSigner)
1346            .unwrap_err();
1347        assert!(
1348            matches!(err, DialectInstallError::R4Violation { .. }),
1349            "expected R4 violation after shapes tamper, got {err:?}"
1350        );
1351    }
1352
1353    // -- "cbcl" extends shorthand resolves to base (PR feedback P2) --
1354
1355    #[test]
1356    fn cbcl_shorthand_extends_resolves_to_base_at_install() {
1357        use crate::protocol::{CausalProtocol, NodeRef, StepDecl};
1358        let mut reg = DialectRegistry::new();
1359        // Child dialect extends "cbcl" (shorthand for cbcl-base) and its
1360        // protocol references the inherited core performative `ok`. Without
1361        // the alias, install would reject this as undefined.
1362        let mut steps = alloc::collections::BTreeMap::new();
1363        steps.insert(
1364            "begin".into(),
1365            StepDecl {
1366                performative: "begin".into(),
1367                predecessors: vec![],
1368                successors: vec![NodeRef::Single("ok".into())],
1369            },
1370        );
1371        steps.insert(
1372            "ok".into(),
1373            StepDecl {
1374                performative: "ok".into(),
1375                predecessors: vec![NodeRef::Single("begin".into())],
1376                successors: vec![],
1377            },
1378        );
1379        let d = Dialect {
1380            types: Default::default(),
1381            roles: Vec::new(),
1382            state: None,
1383            state_bounds: None,
1384            causal_locality: Default::default(),
1385            name: String::from("uses-ok"),
1386            extends: vec![String::from("cbcl")],
1387            author: None,
1388            performatives: vec![],
1389            resources: ResourceBounds {
1390                max_depth: 8,
1391                max_expansion_size: 512,
1392            },
1393            examples: vec![],
1394            signature: None,
1395            hash: None,
1396            protocol: None,
1397            causal_protocol: Some(CausalProtocol { steps }),
1398            shapes: Vec::new(),
1399        };
1400        reg.install(d)
1401            .expect("dialect extending cbcl should install");
1402    }
1403
1404    // ---- install-time content hashing (SPEC-014 REQ-628) ----
1405
1406    fn hashless_dialect(name: &str) -> Dialect {
1407        Dialect {
1408            types: Default::default(),
1409            roles: Vec::new(),
1410            state: None,
1411            state_bounds: None,
1412            causal_locality: Default::default(),
1413            name: String::from(name),
1414            extends: vec![String::from("cbcl")],
1415            author: Some(String::from("@hash-tests")),
1416            performatives: vec![PerformativeDef {
1417                role: None,
1418                name: String::from("greet"),
1419                params: vec![],
1420                template: effect_template("greet-action"),
1421            }],
1422            resources: ResourceBounds {
1423                max_depth: 8,
1424                max_expansion_size: 512,
1425            },
1426            examples: vec![],
1427            signature: None,
1428            hash: None,
1429            protocol: None,
1430            causal_protocol: None,
1431            shapes: Vec::new(),
1432        }
1433    }
1434
1435    #[test]
1436    fn install_populates_canonical_hash() {
1437        let d = hashless_dialect("hashed");
1438        let expected = crate::canonical::dialect_hash(&d);
1439        let mut reg = DialectRegistry::new();
1440        reg.install(d).unwrap();
1441        let installed = reg.find_by_name("hashed").unwrap();
1442        let h = installed.hash.as_deref().expect("install must set hash");
1443        assert_eq!(h, expected);
1444        let hex = h.strip_prefix("f1220").expect("f1220 prefix");
1445        assert_eq!(hex.len(), 64);
1446        assert!(hex
1447            .chars()
1448            .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)));
1449    }
1450
1451    #[test]
1452    fn install_hash_is_stable_across_registries() {
1453        let mut reg1 = DialectRegistry::new();
1454        let mut reg2 = DialectRegistry::new();
1455        reg1.install(hashless_dialect("stable")).unwrap();
1456        reg2.install(hashless_dialect("stable")).unwrap();
1457        assert_eq!(
1458            reg1.find_by_name("stable").unwrap().hash,
1459            reg2.find_by_name("stable").unwrap().hash
1460        );
1461    }
1462
1463    #[test]
1464    fn install_hash_changes_when_performative_renamed() {
1465        let mut renamed = hashless_dialect("same-name");
1466        renamed.performatives[0].name = String::from("salute");
1467        let mut reg1 = DialectRegistry::new();
1468        let mut reg2 = DialectRegistry::new();
1469        reg1.install(hashless_dialect("same-name")).unwrap();
1470        reg2.install(renamed).unwrap();
1471        assert_ne!(
1472            reg1.find_by_name("same-name").unwrap().hash,
1473            reg2.find_by_name("same-name").unwrap().hash,
1474            "renaming a performative must change the installed hash"
1475        );
1476    }
1477
1478    #[test]
1479    fn install_preserves_declared_hash() {
1480        // A declared :hash claim is kept verbatim so wrappers can compare it
1481        // against the computed value and reject mismatches.
1482        let mut d = hashless_dialect("claimed");
1483        d.hash = Some(String::from("f1220abcd1234"));
1484        let mut reg = DialectRegistry::new();
1485        reg.install(d).unwrap();
1486        assert_eq!(
1487            reg.find_by_name("claimed").unwrap().hash.as_deref(),
1488            Some("f1220abcd1234")
1489        );
1490    }
1491
1492    #[test]
1493    fn install_with_signer_populates_canonical_hash() {
1494        let d = hashless_dialect("signer-hashed");
1495        let expected = crate::canonical::dialect_hash(&d);
1496        let mut reg = DialectRegistry::new();
1497        reg.install_with_signer(d, &MockSigner).unwrap();
1498        assert_eq!(
1499            reg.find_by_name("signer-hashed").unwrap().hash.as_deref(),
1500            Some(expected.as_str())
1501        );
1502    }
1503
1504    #[test]
1505    fn install_hash_of_signed_dialect_keeps_signature_valid() {
1506        // Populating `hash` post-R4 must not perturb the signable bytes:
1507        // sign, install, and confirm both hash presence and R4Result::Valid.
1508        let mut d = hashless_dialect("signed-and-hashed");
1509        d.protocol = Some(String::from("ed25519"));
1510        d.signature = Some(CanonicalSigner.sign(&crate::canonical::dialect_canonical_bytes(&d)));
1511        let mut reg = DialectRegistry::new();
1512        let r4 = reg.install_with_signer(d, &CanonicalSigner).unwrap();
1513        assert_eq!(r4, R4Result::Valid);
1514        assert!(reg
1515            .find_by_name("signed-and-hashed")
1516            .unwrap()
1517            .hash
1518            .is_some());
1519    }
1520}