Skip to main content

cbcl_parser/
pipeline.rs

1//! Full verified pipeline.
2//!
3//! Mirrors `Pipeline.lean` from the Lean 4 proof library.
4//!
5//! The pipeline chains: parse → parse_message → validate → expand →
6//! causal verify (6a) → shape check (6b) → success.
7//!
8//! Two entry points:
9//! - [`run_pipeline`] — lightweight parse + validate (no runtime context).
10//! - [`run_pipeline_full`] — full verification with dialect registry and
11//!   message store, including causal verification and shape checking
12//!   (REQ-231: fail-closed, no bypass, no partial checks).
13
14#![forbid(unsafe_code)]
15
16use crate::parser::{self, ParseError};
17use alloc::string::String;
18use alloc::vec::Vec;
19use cbcl_core::blame::ViolationError;
20use cbcl_core::dialect::{Dialect, DialectRegistry};
21use cbcl_core::evaluator::{evaluate_without_shape_check, EvalError};
22use cbcl_core::message::Message;
23use cbcl_core::policy::{apply_policy, PendingReason, PolicyOutcome, UnknownPredecessorPolicy};
24use cbcl_core::protocol::CausalViolation;
25use cbcl_core::r1;
26use cbcl_core::r3;
27use cbcl_core::r5;
28use cbcl_core::sexpr::SExpr;
29use cbcl_core::shape::ShapeViolation;
30use cbcl_core::store::{MessageStore, ThreadId};
31use core::fmt;
32
33/// Validation errors from the pipeline (ADR-002).
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum ValidationError {
36    R1RecursivePerformative {
37        performatives: Vec<String>,
38    },
39    R2ResourceBoundsInvalid {
40        field: &'static str,
41        value: u32,
42    },
43    R2FuelExhausted,
44    R3CoreOverride {
45        performatives: Vec<String>,
46    },
47    R4SignatureInvalid,
48    /// R5 shape/protocol well-formedness violation (REQ-208, REQ-222).
49    R5Violation {
50        errors: Vec<String>,
51    },
52    /// Causal protocol violation (REQ-231, step 6a).
53    CausalViolation {
54        violation: CausalViolation,
55        blame: ViolationError,
56    },
57    /// Shape constraint violation (REQ-231, step 6b).
58    ShapeViolation {
59        violation: ShapeViolation,
60        blame: ViolationError,
61    },
62    MalformedMessage {
63        reason: String,
64    },
65    MalformedDialect {
66        reason: String,
67    },
68}
69
70impl fmt::Display for ValidationError {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        match self {
73            ValidationError::R1RecursivePerformative { performatives } => {
74                write!(
75                    f,
76                    "R1 violation: recursive performative(s): {}",
77                    performatives.join(", ")
78                )
79            }
80            ValidationError::R2ResourceBoundsInvalid { field, value } => {
81                write!(f, "R2 violation: invalid resource bound {field}={value}")
82            }
83            ValidationError::R2FuelExhausted => write!(f, "R2 violation: fuel exhausted"),
84            ValidationError::R3CoreOverride { performatives } => {
85                write!(
86                    f,
87                    "R3 violation: core performative(s) overridden: {}",
88                    performatives.join(", ")
89                )
90            }
91            ValidationError::R4SignatureInvalid => write!(f, "R4 violation: invalid signature"),
92            ValidationError::R5Violation { errors } => {
93                write!(f, "R5 violation: {}", errors.join("; "))
94            }
95            ValidationError::CausalViolation { blame, .. } => {
96                write!(f, "causal violation: {}", blame)
97            }
98            ValidationError::ShapeViolation { blame, .. } => {
99                write!(f, "shape violation: {}", blame)
100            }
101            ValidationError::MalformedMessage { reason } => {
102                write!(f, "malformed message: {reason}")
103            }
104            ValidationError::MalformedDialect { reason } => {
105                write!(f, "malformed dialect: {reason}")
106            }
107        }
108    }
109}
110
111#[cfg(feature = "std")]
112impl std::error::Error for ValidationError {}
113
114/// Top-level pipeline result (REQ-111).
115#[derive(Debug, Clone, PartialEq, Eq)]
116#[allow(clippy::large_enum_variant)]
117pub enum PipelineResult {
118    Success(Message),
119    ParseError(ParseError),
120    ValidationError(ValidationError),
121    /// Causal predecessor not yet in the local store (REQ-305).
122    ///
123    /// Returned only under [`UnknownPredecessorPolicy::Reject`]. Senders may
124    /// retry once the predecessor arrives. The pipeline does not buffer; under
125    /// [`UnknownPredecessorPolicy::Buffer`] callers receive [`PipelineResult::Buffered`]
126    /// and are responsible for enqueuing the message into a `PendingQueue`.
127    Pending {
128        message: Message,
129        reason: PendingReason,
130    },
131    /// Causal predecessor unknown; caller should buffer for re-evaluation
132    /// (REQ-305 Buffer policy).
133    Buffered {
134        message: Message,
135    },
136}
137
138/// Runtime context for the full pipeline (REQ-231).
139///
140/// Provides the dialect registry and message store needed for causal
141/// verification (step 6a) and shape checking (step 6b), plus the policy that
142/// governs how `VerificationResult::Unknown` is handled (REQ-305).
143pub struct PipelineContext<'a, S: MessageStore> {
144    pub registry: &'a DialectRegistry,
145    pub store: &'a S,
146    /// Policy applied when a `:caused-by` hash is not yet present in the
147    /// store. Defaults to [`UnknownPredecessorPolicy::Reject`] when callers
148    /// use the [`PipelineContext::new`] constructor.
149    pub policy: UnknownPredecessorPolicy,
150}
151
152impl<'a, S: MessageStore> PipelineContext<'a, S> {
153    /// Create a context with the default `Reject` policy.
154    pub fn new(registry: &'a DialectRegistry, store: &'a S) -> Self {
155        Self {
156            registry,
157            store,
158            policy: UnknownPredecessorPolicy::default(),
159        }
160    }
161
162    /// Create a context with an explicit policy.
163    pub fn with_policy(
164        registry: &'a DialectRegistry,
165        store: &'a S,
166        policy: UnknownPredecessorPolicy,
167    ) -> Self {
168        Self {
169            registry,
170            store,
171            policy,
172        }
173    }
174}
175
176/// Run the lightweight verified pipeline (REQ-110).
177///
178/// Pipeline: parse → parse_message → validate → (for meta/define/teach: verify R1–R5) → success.
179///
180/// This entry point does **not** perform causal verification or shape checking
181/// on simple messages (no runtime context). Use [`run_pipeline_full`] for
182/// complete monitoring.
183pub fn run_pipeline(input: &str) -> PipelineResult {
184    let sexpr = match parser::parse(input) {
185        Ok(e) => e,
186        Err(e) => return PipelineResult::ParseError(e),
187    };
188
189    let message = match crate::message_parser::parse_message(&sexpr) {
190        Ok(m) => m,
191        Err(reason) => {
192            return PipelineResult::ValidationError(ValidationError::MalformedMessage { reason })
193        }
194    };
195
196    // For meta define/teach messages, validate the dialect definition (REQ-208, REQ-210).
197    if let Err(err) = validate_meta_dialect(&message, None) {
198        return PipelineResult::ValidationError(err);
199    }
200
201    PipelineResult::Success(message)
202}
203
204/// Run the full verified pipeline with runtime context (REQ-231).
205///
206/// Pipeline: parse → parse_message → validate → (for meta/define/teach: verify R1–R5)
207/// → evaluate (expand) → causal verify (6a) → shape check (6b) → success.
208///
209/// **Fail-closed**: any error at any step produces a `ValidationError`. No code
210/// path from receive to deliver skips verification (CON-206).
211pub fn run_pipeline_full<S: MessageStore>(
212    input: &str,
213    ctx: &PipelineContext<'_, S>,
214) -> PipelineResult {
215    // Step 1: Parse text → S-expression
216    let sexpr = match parser::parse(input) {
217        Ok(e) => e,
218        Err(e) => return PipelineResult::ParseError(e),
219    };
220
221    // Step 2: Parse S-expression → Message
222    let message = match crate::message_parser::parse_message(&sexpr) {
223        Ok(m) => m,
224        Err(reason) => {
225            return PipelineResult::ValidationError(ValidationError::MalformedMessage { reason })
226        }
227    };
228
229    // Step 3: For meta define/teach messages, validate R1–R5 (REQ-208, REQ-210).
230    // Pass the runtime registry so child dialects extending non-base parents
231    // are resolved correctly during R5 protocol-definedness (REQ-206).
232    if let Err(err) = validate_meta_dialect(&message, Some(ctx.registry)) {
233        return PipelineResult::ValidationError(err);
234    }
235
236    // Steps 4–6: For simple messages, causal verify (6a) → evaluate (4) → shape check (6b).
237    //
238    // Causal verification runs before evaluation so a causal failure cannot be
239    // masked by a downstream shape error, and so callers always see the most
240    // specific violation first (REQ-231 fail-closed ordering).
241    //
242    // Wrapped (`envelope`/`signed`/`with-limits`) and dialect-scoped (`lang`)
243    // messages defer to their innermost Simple payload so wrappers cannot be
244    // used to bypass causal/shape verification.
245    let inner_simple = message.innermost_simple();
246    if let Some(Message::Simple {
247        caused_by,
248        thread,
249        performative,
250        ..
251    }) = inner_simple
252    {
253        let performative = Some(performative);
254
255        // Step 6a: Causal verification (REQ-231).
256        //
257        // A child dialect can declare a protocol step for a performative
258        // inherited from a parent (including core performatives like `ok`),
259        // so it is *not* sufficient to find the dialect that *defines* the
260        // performative. Instead iterate every installed dialect: any whose
261        // `causal_protocol` declares a step for `perf_name` participates in
262        // verification, and constraints compose by conjunction (any
263        // rejection rejects the message).
264        if let Some(perf) = performative {
265            let perf_name = perf.name();
266            let thread_id = ThreadId(thread.clone().unwrap_or_else(|| String::from("default")));
267
268            for d in ctx.registry.iter() {
269                let Some(ref proto) = d.causal_protocol else {
270                    continue;
271                };
272                if !proto.steps.contains_key(perf_name) {
273                    continue;
274                }
275
276                let result = cbcl_core::protocol::verify_causal(
277                    perf_name,
278                    caused_by.as_ref(),
279                    ctx.store,
280                    proto,
281                    &thread_id,
282                );
283
284                match apply_policy(&result, &ctx.policy) {
285                    PolicyOutcome::Accept => {}
286                    PolicyOutcome::Reject(cv) => {
287                        let blame =
288                            ViolationError::from_causal_violation(&cv, None, thread.clone())
289                                .with_dialect_context(
290                                    &d.name,
291                                    d.author.as_deref(),
292                                    d.hash.as_deref(),
293                                    Some(perf_name),
294                                );
295                        blame.record_metrics(&d.name);
296                        return PipelineResult::ValidationError(ValidationError::CausalViolation {
297                            violation: cv,
298                            blame,
299                        });
300                    }
301                    PolicyOutcome::Pending(reason) => {
302                        return PipelineResult::Pending { message, reason };
303                    }
304                    PolicyOutcome::Buffered => {
305                        return PipelineResult::Buffered { message };
306                    }
307                }
308            }
309        }
310
311        // Step 4: Evaluate (template expansion). Shape checking is deferred to
312        // step 6b so blame can include the expanded form.
313        let eval_result = match evaluate_without_shape_check(&message, ctx.registry) {
314            Ok(r) => r,
315            Err(eval_err) => {
316                return PipelineResult::ValidationError(eval_error_to_validation(
317                    eval_err,
318                    thread.clone(),
319                ))
320            }
321        };
322
323        // Step 6b: Shape checking on expanded message (REQ-223, REQ-224, REQ-231).
324        // Compose via conjunction: every matching shape constraint must pass.
325        if let Some(perf) = performative {
326            let perf_name = perf.name();
327            for dialect in ctx.registry.iter() {
328                for shape in &dialect.shapes {
329                    if shape.performative == perf_name {
330                        if let Err(sv) = shape.check(&eval_result.expanded) {
331                            let blame = ViolationError::from_shape_violation(
332                                &sv,
333                                None,
334                                thread.clone(),
335                                None,
336                            )
337                            .with_dialect_context(
338                                &dialect.name,
339                                dialect.author.as_deref(),
340                                dialect.hash.as_deref(),
341                                Some(perf_name),
342                            );
343                            blame.record_metrics(&dialect.name);
344                            return PipelineResult::ValidationError(
345                                ValidationError::ShapeViolation {
346                                    violation: sv,
347                                    blame,
348                                },
349                            );
350                        }
351                    }
352                }
353            }
354        }
355    }
356
357    PipelineResult::Success(message)
358}
359
360/// Validate meta define/teach dialect definitions (REQ-208, REQ-210).
361///
362/// Both `(meta (define ...))` and `(meta (teach ...))` carry dialect definitions
363/// that must pass R1–R5 before acceptance. The teach form includes protocol and
364/// shape declarations for gossip propagation.
365#[allow(clippy::result_large_err)]
366fn validate_meta_dialect(
367    message: &Message,
368    registry: Option<&DialectRegistry>,
369) -> Result<(), ValidationError> {
370    if let Message::Meta { ref dialect_def } = message {
371        if let SExpr::List(items) = dialect_def {
372            if items.is_empty() {
373                return Ok(());
374            }
375
376            // (meta (define ...)) — direct dialect definition
377            if items[0].is_symbol("define") {
378                return validate_define_dialect(dialect_def, registry);
379            }
380
381            // (meta (teach <recipient> <define-form>)) — gossip propagation (REQ-210).
382            // The teach form wraps a define; extract and validate the inner definition.
383            if items[0].is_symbol("teach") {
384                // (teach <recipient> (define ...))
385                // Find the inner define form — it's the first list element after the symbol.
386                for item in items.iter().skip(1) {
387                    if let SExpr::List(inner_items) = item {
388                        if !inner_items.is_empty() && inner_items[0].is_symbol("define") {
389                            return validate_define_dialect(item, registry);
390                        }
391                    }
392                }
393                // teach without define — no dialect to validate, pass through.
394            }
395        }
396    }
397    Ok(())
398}
399
400#[allow(clippy::result_large_err)]
401fn validate_define_dialect(
402    dialect_def: &SExpr,
403    registry: Option<&DialectRegistry>,
404) -> Result<(), ValidationError> {
405    let dialect = crate::dialect_parser::parse_dialect(dialect_def)
406        .map_err(|reason| ValidationError::MalformedDialect { reason })?;
407
408    let recursive = r1::r1_violations(&dialect);
409    if !recursive.is_empty() {
410        return Err(ValidationError::R1RecursivePerformative {
411            performatives: recursive,
412        });
413    }
414
415    if let Some((field, value)) = invalid_resource_bound(&dialect) {
416        return Err(ValidationError::R2ResourceBoundsInvalid { field, value });
417    }
418
419    let overrides = r3::r3_violations(&dialect);
420    if !overrides.is_empty() {
421        return Err(ValidationError::R3CoreOverride {
422            performatives: overrides,
423        });
424    }
425
426    // R5: shape + protocol well-formedness (REQ-208, REQ-222).
427    //
428    // When a registry is available (full pipeline), resolve every `extends`
429    // entry against the installed dialects so child protocols can reference
430    // ancestor performatives without false-rejecting (REQ-206). Without a
431    // registry (lightweight pipeline) we still credit the base dialect for
432    // shorthand `cbcl` / canonical `cbcl-base` so most real definitions keep
433    // working. Other named parents we cannot resolve here — install-time R5
434    // re-checks definedness against the actual ancestor chain.
435    let base = cbcl_core::dialect::base_dialect();
436    let mut ancestors: alloc::vec::Vec<&cbcl_core::dialect::Dialect> = alloc::vec![];
437    let mut credited_base = false;
438    if let Some(reg) = registry {
439        for name in &dialect.extends {
440            let resolved = if name == "cbcl" {
441                "cbcl-base"
442            } else {
443                name.as_str()
444            };
445            if let Some(parent) = reg.find_by_name(resolved) {
446                ancestors.push(parent);
447                if resolved == base.name {
448                    credited_base = true;
449                }
450            }
451        }
452    }
453    if !credited_base {
454        let extends_base = dialect
455            .extends
456            .iter()
457            .any(|name| name == "cbcl" || name == &base.name);
458        if extends_base {
459            ancestors.push(&base);
460        }
461    }
462    let r5_errors = r5::r5_violations_with_ancestors(&dialect, &ancestors);
463    if !r5_errors.is_empty() {
464        return Err(ValidationError::R5Violation { errors: r5_errors });
465    }
466
467    Ok(())
468}
469
470fn invalid_resource_bound(dialect: &Dialect) -> Option<(&'static str, u32)> {
471    let bounds = &dialect.resources;
472    if bounds.max_depth == 0 || bounds.max_depth > 64 {
473        return Some(("max_depth", bounds.max_depth));
474    }
475    if bounds.max_expansion_size == 0 || bounds.max_expansion_size > 8192 {
476        return Some(("max_expansion_size", bounds.max_expansion_size));
477    }
478    None
479}
480
481/// Map evaluator errors to pipeline validation errors.
482///
483/// `thread` is the originating message's thread, threaded through so blame
484/// records carry it even when the evaluator surfaces a violation before the
485/// pipeline reaches its dedicated shape-check step (REQ-231).
486fn eval_error_to_validation(err: EvalError, thread: Option<String>) -> ValidationError {
487    match err {
488        EvalError::UnknownPerformative(name) => ValidationError::MalformedMessage {
489            reason: alloc::format!("unknown performative: {name}"),
490        },
491        // REQ-033: a dialect performative must name its dialect. The
492        // recogniser rejects the unscoped form, so this path is reached only
493        // by programmatically constructed messages.
494        EvalError::UnscopedDialectPerformative(name) => ValidationError::MalformedMessage {
495            reason: alloc::format!(
496                "dialect performative '{name}' invoked outside (lang <dialect> ...); \
497                 the message must name the dialect that defines it"
498            ),
499        },
500        EvalError::TemplateExpansionFailed { performative: _ } => ValidationError::R2FuelExhausted,
501        EvalError::UnknownDialect(name) => ValidationError::MalformedMessage {
502            reason: alloc::format!("unknown dialect: {name}"),
503        },
504        EvalError::MalformedMessage(reason) => ValidationError::MalformedMessage { reason },
505        EvalError::ShapeViolation(sv) => {
506            let blame = ViolationError::from_shape_violation(&sv, None, thread, None);
507            ValidationError::ShapeViolation {
508                violation: sv,
509                blame,
510            }
511        }
512    }
513}
514
515#[cfg(test)]
516mod tests {
517    use super::*;
518    use alloc::collections::BTreeMap;
519    use cbcl_core::dialect::{DialectRegistry, PerformativeDef, ResourceBounds};
520    use cbcl_core::message::{CausedBy, MessageType, Performative};
521    use cbcl_core::protocol::{CausalProtocol, NodeRef, StepDecl};
522    use cbcl_core::sexpr::Atom;
523    use cbcl_core::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
524    use cbcl_core::store::{ContentHash, ThreadId, ThreadedMessageStore};
525
526    fn effect_template(action: &str) -> SExpr {
527        SExpr::List(alloc::vec![
528            SExpr::Atom(Atom::Symbol(String::from("effect"))),
529            SExpr::Atom(Atom::Symbol(String::from(action))),
530        ])
531    }
532
533    fn make_simple_msg(perf: &str, caused_by: Option<CausedBy>) -> Message {
534        Message::Simple {
535            performative: Performative::Custom(String::from(perf)),
536            recipient: None,
537            content: SExpr::Atom(Atom::Str(String::from("test"))),
538            params: alloc::vec![],
539            thread: None,
540            sender: None,
541            caused_by,
542        }
543    }
544
545    // -- Basic pipeline (no context) --
546
547    #[test]
548    fn pipeline_parse_error() {
549        let result = run_pipeline("(unclosed");
550        assert!(matches!(result, PipelineResult::ParseError(_)));
551    }
552
553    #[test]
554    fn pipeline_simple_message() {
555        let result = run_pipeline("(tell \"hello\")");
556        assert!(matches!(result, PipelineResult::Success(_)));
557        if let PipelineResult::Success(msg) = result {
558            assert_eq!(msg.message_type(), MessageType::Simple);
559        }
560    }
561
562    #[test]
563    fn pipeline_meta_define() {
564        let input = "(meta (define test-dialect (cbcl) @author))";
565        let result = run_pipeline(input);
566        assert!(matches!(result, PipelineResult::Success(_)));
567        if let PipelineResult::Success(msg) = result {
568            assert_eq!(msg.message_type(), MessageType::Meta);
569        }
570    }
571
572    #[test]
573    fn pipeline_malformed_dialect() {
574        let input = "(meta (define))"; // missing required fields
575        let result = run_pipeline(input);
576        assert!(matches!(
577            result,
578            PipelineResult::ValidationError(ValidationError::MalformedDialect { .. })
579        ));
580    }
581
582    #[test]
583    fn pipeline_custom_performative() {
584        let result = run_pipeline(
585            "(lang cbcl-planning (share-conditional pickup box-location box-in-hand))",
586        );
587        assert!(matches!(result, PipelineResult::Success(_)));
588    }
589
590    #[test]
591    fn pipeline_meta_query() {
592        let result = run_pipeline("(meta (query (speak? cbcl-planning)))");
593        assert!(matches!(result, PipelineResult::Success(_)));
594    }
595
596    #[test]
597    fn pipeline_rejects_r3_core_override() {
598        let result = run_pipeline("(meta (define bad (cbcl) @author (extend tell () x)))");
599        assert!(matches!(
600            result,
601            PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
602        ));
603    }
604
605    #[test]
606    fn pipeline_rejects_mutual_recursion() {
607        let result = run_pipeline(
608            "(meta (define cyclic (cbcl) @author (extend ping () (pong)) (extend pong () (ping))))",
609        );
610        assert!(matches!(
611            result,
612            PipelineResult::ValidationError(ValidationError::R1RecursivePerformative { .. })
613        ));
614    }
615
616    // -- REQ-210: teach messages validated same as define --
617
618    #[test]
619    fn pipeline_teach_validates_r3() {
620        let result =
621            run_pipeline("(meta (teach @bob (define bad (cbcl) @author (extend tell () x))))");
622        assert!(matches!(
623            result,
624            PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
625        ));
626    }
627
628    #[test]
629    fn pipeline_teach_valid_passes() {
630        let result = run_pipeline("(meta (teach @bob (define good-dialect (cbcl) @author)))");
631        assert!(matches!(result, PipelineResult::Success(_)));
632    }
633
634    // -- REQ-231: full pipeline with context --
635
636    #[test]
637    fn full_pipeline_simple_message_passes() {
638        let registry = DialectRegistry::new();
639        let store = ThreadedMessageStore::new();
640        let ctx = PipelineContext::new(&registry, &store);
641        let result = run_pipeline_full("(tell \"hello\")", &ctx);
642        assert!(matches!(result, PipelineResult::Success(_)));
643    }
644
645    #[test]
646    fn full_pipeline_rejects_causal_violation() {
647        let mut registry = DialectRegistry::new();
648
649        // Install a dialect with a causal protocol: begin → greet
650        let mut steps = BTreeMap::new();
651        steps.insert(
652            "begin".into(),
653            StepDecl {
654                performative: "begin".into(),
655                predecessors: alloc::vec![],
656                successors: alloc::vec![NodeRef::Single("greet".into())],
657            },
658        );
659        steps.insert(
660            "greet".into(),
661            StepDecl {
662                performative: "greet".into(),
663                predecessors: alloc::vec![NodeRef::Single("begin".into())],
664                successors: alloc::vec![],
665            },
666        );
667        let proto = CausalProtocol { steps };
668
669        registry
670            .install(cbcl_core::dialect::Dialect {
671                types: Default::default(),
672                roles: Vec::new(),
673                state: None,
674                state_bounds: None,
675                causal_locality: Default::default(),
676                name: String::from("proto-dialect"),
677                extends: alloc::vec![String::from("cbcl")],
678                author: None,
679                performatives: alloc::vec![PerformativeDef {
680                    role: None,
681                    name: String::from("greet"),
682                    params: alloc::vec![],
683                    template: effect_template("greet-action"),
684                }],
685                resources: ResourceBounds {
686                    max_depth: 8,
687                    max_expansion_size: 512,
688                },
689                examples: alloc::vec![],
690                signature: None,
691                hash: None,
692                protocol: None,
693                causal_protocol: Some(proto),
694                shapes: alloc::vec![],
695            })
696            .unwrap();
697
698        let store = ThreadedMessageStore::new();
699        let ctx = PipelineContext::new(&registry, &store);
700
701        // Send "greet" without :caused-by — protocol requires begin as predecessor.
702        let result = run_pipeline_full("(lang proto-dialect (greet \"hi\"))", &ctx);
703        assert!(
704            matches!(
705                result,
706                PipelineResult::ValidationError(ValidationError::CausalViolation { .. })
707            ),
708            "expected causal violation, got {:?}",
709            result
710        );
711    }
712
713    #[test]
714    fn full_pipeline_shape_violation_rejected() {
715        let mut registry = DialectRegistry::new();
716
717        // Install dialect with shape constraint requiring :target string
718        registry
719            .install(cbcl_core::dialect::Dialect {
720                types: Default::default(),
721                roles: Vec::new(),
722                state: None,
723                state_bounds: None,
724                causal_locality: Default::default(),
725                name: String::from("shape-dialect"),
726                extends: alloc::vec![String::from("cbcl")],
727                author: None,
728                performatives: alloc::vec![PerformativeDef {
729                    role: None,
730                    name: String::from("propose"),
731                    params: alloc::vec![],
732                    template: effect_template("propose-action"),
733                }],
734                resources: ResourceBounds {
735                    max_depth: 8,
736                    max_expansion_size: 512,
737                },
738                examples: alloc::vec![],
739                signature: None,
740                hash: None,
741                protocol: None,
742                causal_protocol: None,
743                shapes: alloc::vec![ShapeConstraint {
744                    performative: String::from("propose"),
745                    rules: alloc::vec![ShapeRule::Require {
746                        keyword: String::from("target"),
747                        type_constraint: Some(TypeConstraint::String),
748                        children: alloc::vec![],
749                    }],
750                }],
751            })
752            .unwrap();
753
754        let store = ThreadedMessageStore::new();
755        let ctx = PipelineContext::new(&registry, &store);
756
757        // "propose" without :target — shape requires it.
758        let result = run_pipeline_full("(lang shape-dialect (propose \"idea\"))", &ctx);
759        assert!(
760            matches!(
761                result,
762                PipelineResult::ValidationError(ValidationError::ShapeViolation { .. })
763            ),
764            "expected shape violation, got {:?}",
765            result
766        );
767    }
768
769    #[test]
770    fn full_pipeline_causal_valid_with_predecessor() {
771        let mut registry = DialectRegistry::new();
772
773        // Protocol: begin → ack
774        let mut steps = BTreeMap::new();
775        steps.insert(
776            "begin".into(),
777            StepDecl {
778                performative: "begin".into(),
779                predecessors: alloc::vec![],
780                successors: alloc::vec![NodeRef::Single("ack".into())],
781            },
782        );
783        steps.insert(
784            "ack".into(),
785            StepDecl {
786                performative: "ack".into(),
787                predecessors: alloc::vec![NodeRef::Single("begin".into())],
788                successors: alloc::vec![],
789            },
790        );
791        let proto = CausalProtocol { steps };
792
793        registry
794            .install(cbcl_core::dialect::Dialect {
795                types: Default::default(),
796                roles: Vec::new(),
797                state: None,
798                state_bounds: None,
799                causal_locality: Default::default(),
800                name: String::from("ack-dialect"),
801                extends: alloc::vec![String::from("cbcl")],
802                author: None,
803                performatives: alloc::vec![PerformativeDef {
804                    role: None,
805                    name: String::from("ack"),
806                    params: alloc::vec![],
807                    template: effect_template("ack-action"),
808                }],
809                resources: ResourceBounds {
810                    max_depth: 8,
811                    max_expansion_size: 512,
812                },
813                examples: alloc::vec![],
814                signature: None,
815                hash: None,
816                protocol: None,
817                causal_protocol: Some(proto),
818                shapes: alloc::vec![],
819            })
820            .unwrap();
821
822        let thread = ThreadId(String::from("default"));
823        let mut store = ThreadedMessageStore::new();
824        // Insert a "begin" message that the ack can reference.
825        store.append(
826            ContentHash(String::from("abc123")),
827            thread.clone(),
828            make_simple_msg("begin", Some(CausedBy::Begin)),
829        );
830
831        let ctx = PipelineContext::new(&registry, &store);
832
833        // "ack" with :caused-by pointing to the begin message.
834        let result = run_pipeline_full(
835            "(lang ack-dialect (ack \"done\" :caused-by \"abc123\"))",
836            &ctx,
837        );
838        assert!(
839            matches!(result, PipelineResult::Success(_)),
840            "expected success, got {:?}",
841            result
842        );
843    }
844
845    #[test]
846    fn full_pipeline_meta_define_still_validated() {
847        let registry = DialectRegistry::new();
848        let store = ThreadedMessageStore::new();
849        let ctx = PipelineContext::new(&registry, &store);
850        // R3 violation via full pipeline
851        let result = run_pipeline_full(
852            "(meta (define bad (cbcl) @author (extend tell () x)))",
853            &ctx,
854        );
855        assert!(matches!(
856            result,
857            PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
858        ));
859    }
860
861    #[test]
862    fn full_pipeline_teach_validated() {
863        let registry = DialectRegistry::new();
864        let store = ThreadedMessageStore::new();
865        let ctx = PipelineContext::new(&registry, &store);
866        let result = run_pipeline_full(
867            "(meta (teach @bob (define bad (cbcl) @author (extend tell () x))))",
868            &ctx,
869        );
870        assert!(matches!(
871            result,
872            PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
873        ));
874    }
875
876    // -- REQ-305 / REQ-231: Unknown predecessor must not slip through --
877
878    fn ack_dialect_registry() -> DialectRegistry {
879        let mut registry = DialectRegistry::new();
880        let mut steps = BTreeMap::new();
881        steps.insert(
882            "begin".into(),
883            StepDecl {
884                performative: "begin".into(),
885                predecessors: alloc::vec![],
886                successors: alloc::vec![NodeRef::Single("ack".into())],
887            },
888        );
889        steps.insert(
890            "ack".into(),
891            StepDecl {
892                performative: "ack".into(),
893                predecessors: alloc::vec![NodeRef::Single("begin".into())],
894                successors: alloc::vec![],
895            },
896        );
897        let proto = CausalProtocol { steps };
898
899        registry
900            .install(cbcl_core::dialect::Dialect {
901                types: Default::default(),
902                roles: Vec::new(),
903                state: None,
904                state_bounds: None,
905                causal_locality: Default::default(),
906                name: String::from("ack-dialect"),
907                extends: alloc::vec![String::from("cbcl")],
908                author: None,
909                performatives: alloc::vec![PerformativeDef {
910                    role: None,
911                    name: String::from("ack"),
912                    params: alloc::vec![],
913                    template: effect_template("ack-action"),
914                }],
915                resources: ResourceBounds {
916                    max_depth: 8,
917                    max_expansion_size: 512,
918                },
919                examples: alloc::vec![],
920                signature: None,
921                hash: None,
922                protocol: None,
923                causal_protocol: Some(proto),
924                shapes: alloc::vec![],
925            })
926            .unwrap();
927        registry
928    }
929
930    #[test]
931    fn full_pipeline_unknown_predecessor_rejects_under_default_policy() {
932        let registry = ack_dialect_registry();
933        let store = ThreadedMessageStore::new(); // empty — predecessor absent
934        let ctx = PipelineContext::new(&registry, &store);
935
936        // ack with :caused-by referencing a hash not in the store.
937        let result = run_pipeline_full(
938            "(lang ack-dialect (ack \"done\" :caused-by \"missing-hash\"))",
939            &ctx,
940        );
941        assert!(
942            matches!(
943                result,
944                PipelineResult::Pending {
945                    reason: cbcl_core::policy::PendingReason::CausalPending,
946                    ..
947                }
948            ),
949            "expected Pending under default Reject policy, got {:?}",
950            result
951        );
952    }
953
954    #[test]
955    fn full_pipeline_unknown_predecessor_buffers_under_buffer_policy() {
956        let registry = ack_dialect_registry();
957        let store = ThreadedMessageStore::new();
958        let ctx = PipelineContext::with_policy(
959            &registry,
960            &store,
961            cbcl_core::policy::UnknownPredecessorPolicy::buffer(60),
962        );
963
964        let result = run_pipeline_full(
965            "(lang ack-dialect (ack \"done\" :caused-by \"missing-hash\"))",
966            &ctx,
967        );
968        assert!(
969            matches!(result, PipelineResult::Buffered { .. }),
970            "expected Buffered under Buffer policy, got {:?}",
971            result
972        );
973    }
974
975    // -- REQ-231: Pipeline orders causal before shape so a causal violation
976    // is not masked by an inline shape failure (was: shape ran inside evaluate
977    // before causal verification). --
978
979    #[test]
980    fn full_pipeline_causal_violation_takes_precedence_over_shape() {
981        let mut registry = DialectRegistry::new();
982
983        // Protocol requires "begin" before "ack". Shape requires :target string.
984        let mut steps = BTreeMap::new();
985        steps.insert(
986            "begin".into(),
987            StepDecl {
988                performative: "begin".into(),
989                predecessors: alloc::vec![],
990                successors: alloc::vec![NodeRef::Single("ack".into())],
991            },
992        );
993        steps.insert(
994            "ack".into(),
995            StepDecl {
996                performative: "ack".into(),
997                predecessors: alloc::vec![NodeRef::Single("begin".into())],
998                successors: alloc::vec![],
999            },
1000        );
1001        let proto = CausalProtocol { steps };
1002
1003        registry
1004            .install(cbcl_core::dialect::Dialect {
1005                types: Default::default(),
1006                roles: Vec::new(),
1007                state: None,
1008                state_bounds: None,
1009                causal_locality: Default::default(),
1010                name: String::from("ack-with-shape"),
1011                extends: alloc::vec![String::from("cbcl")],
1012                author: None,
1013                performatives: alloc::vec![PerformativeDef {
1014                    role: None,
1015                    name: String::from("ack"),
1016                    params: alloc::vec![],
1017                    template: effect_template("ack-action"),
1018                }],
1019                resources: ResourceBounds {
1020                    max_depth: 8,
1021                    max_expansion_size: 512,
1022                },
1023                examples: alloc::vec![],
1024                signature: None,
1025                hash: None,
1026                protocol: None,
1027                causal_protocol: Some(proto),
1028                shapes: alloc::vec![ShapeConstraint {
1029                    performative: String::from("ack"),
1030                    rules: alloc::vec![ShapeRule::Require {
1031                        keyword: String::from("target"),
1032                        type_constraint: Some(TypeConstraint::String),
1033                        children: alloc::vec![],
1034                    }],
1035                }],
1036            })
1037            .unwrap();
1038
1039        let store = ThreadedMessageStore::new();
1040        let ctx = PipelineContext::new(&registry, &store);
1041
1042        // ack with no :caused-by AND no :target — both causal and shape would fail.
1043        // We must see CausalViolation, not ShapeViolation, because causal is checked first.
1044        let result = run_pipeline_full("(lang ack-with-shape (ack \"done\"))", &ctx);
1045        assert!(
1046            matches!(
1047                result,
1048                PipelineResult::ValidationError(ValidationError::CausalViolation { .. })
1049            ),
1050            "expected CausalViolation to take precedence, got {:?}",
1051            result
1052        );
1053    }
1054
1055    // -- PR feedback P2: child dialect protocols on inherited performatives
1056    // (e.g. core `ok`) must be enforced. The dialect that *defines* `ok` is
1057    // `cbcl-base` (no protocol); the one that constrains it is the child. --
1058
1059    #[test]
1060    fn full_pipeline_child_protocol_on_core_perf_is_enforced() {
1061        let mut registry = DialectRegistry::new();
1062        let mut steps = BTreeMap::new();
1063        steps.insert(
1064            "begin".into(),
1065            StepDecl {
1066                performative: "begin".into(),
1067                predecessors: alloc::vec![],
1068                successors: alloc::vec![NodeRef::Single("ok".into())],
1069            },
1070        );
1071        steps.insert(
1072            "ok".into(),
1073            StepDecl {
1074                performative: "ok".into(),
1075                predecessors: alloc::vec![NodeRef::Single("begin".into())],
1076                successors: alloc::vec![],
1077            },
1078        );
1079        registry
1080            .install(cbcl_core::dialect::Dialect {
1081                types: Default::default(),
1082                roles: Vec::new(),
1083                state: None,
1084                state_bounds: None,
1085                causal_locality: Default::default(),
1086                name: String::from("ok-protocol"),
1087                extends: alloc::vec![String::from("cbcl")],
1088                author: None,
1089                performatives: alloc::vec![], // no own perfs; constrains base `ok`
1090                resources: ResourceBounds {
1091                    max_depth: 8,
1092                    max_expansion_size: 512,
1093                },
1094                examples: alloc::vec![],
1095                signature: None,
1096                hash: None,
1097                protocol: None,
1098                causal_protocol: Some(CausalProtocol { steps }),
1099                shapes: alloc::vec![],
1100            })
1101            .unwrap();
1102
1103        let store = ThreadedMessageStore::new();
1104        let ctx = PipelineContext::new(&registry, &store);
1105
1106        // `(ok)` with no :caused-by — protocol requires "begin" as predecessor.
1107        let result = run_pipeline_full("(ok)", &ctx);
1108        assert!(
1109            matches!(
1110                result,
1111                PipelineResult::ValidationError(ValidationError::CausalViolation { .. })
1112            ),
1113            "expected child protocol on core `ok` to fire, got {:?}",
1114            result
1115        );
1116    }
1117
1118    // -- PR feedback P2: meta-validation must use registry ancestors so a
1119    // child dialect extending a non-base installed parent isn't rejected. --
1120
1121    #[test]
1122    fn full_pipeline_meta_define_credits_non_base_parent_via_registry() {
1123        let mut registry = DialectRegistry::new();
1124        // First install a parent dialect that defines `notify`.
1125        registry
1126            .install(cbcl_core::dialect::Dialect {
1127                types: Default::default(),
1128                roles: Vec::new(),
1129                state: None,
1130                state_bounds: None,
1131                causal_locality: Default::default(),
1132                name: String::from("parent-dialect"),
1133                extends: alloc::vec![String::from("cbcl")],
1134                author: None,
1135                performatives: alloc::vec![PerformativeDef {
1136                    role: None,
1137                    name: String::from("notify"),
1138                    params: alloc::vec![],
1139                    template: effect_template("notify-action"),
1140                }],
1141                resources: ResourceBounds {
1142                    max_depth: 8,
1143                    max_expansion_size: 512,
1144                },
1145                examples: alloc::vec![],
1146                signature: None,
1147                hash: None,
1148                protocol: None,
1149                causal_protocol: None,
1150                shapes: alloc::vec![],
1151            })
1152            .unwrap();
1153
1154        let store = ThreadedMessageStore::new();
1155        let ctx = PipelineContext::new(&registry, &store);
1156
1157        // Child meta define references parent's `notify` from its protocol.
1158        // Without registry-aware meta validation, this fails as undefined at
1159        // parse time even though install would accept it.
1160        let input = "\
1161            (meta (define child-dialect (parent-dialect) @author \
1162              (protocol (then begin notify))))";
1163        let result = run_pipeline_full(input, &ctx);
1164        assert!(
1165            matches!(result, PipelineResult::Success(_)),
1166            "expected meta-define with registry ancestor to pass, got {:?}",
1167            result
1168        );
1169    }
1170
1171    // -- PR feedback P1: wrapped/dialect-scoped messages must verify their
1172    // innermost simple payload, not bypass causal/shape checks. --
1173
1174    #[test]
1175    fn full_pipeline_envelope_wrapping_does_not_bypass_causal() {
1176        let registry = ack_dialect_registry();
1177        let store = ThreadedMessageStore::new();
1178        let ctx = PipelineContext::new(&registry, &store);
1179
1180        // Wrap a protocol-violating ack inside an envelope. Without the
1181        // wrapper-traversal fix this returned Success.
1182        let result = run_pipeline_full(
1183            "(envelope (:from @alice) (ack \"done\" :caused-by \"missing\"))",
1184            &ctx,
1185        );
1186        assert!(
1187            !matches!(result, PipelineResult::Success(_)),
1188            "expected wrapper not to bypass verification, got Success: {result:?}"
1189        );
1190    }
1191
1192    #[test]
1193    fn full_pipeline_lang_scoped_message_does_not_bypass_causal() {
1194        let registry = ack_dialect_registry();
1195        let store = ThreadedMessageStore::new();
1196        let ctx = PipelineContext::new(&registry, &store);
1197
1198        // (lang ack-dialect (ack "done" :caused-by "missing"))
1199        let result = run_pipeline_full(
1200            "(lang ack-dialect (lang ack-dialect (ack \"done\" :caused-by \"missing\")))",
1201            &ctx,
1202        );
1203        assert!(
1204            !matches!(result, PipelineResult::Success(_)),
1205            "expected dialect-scoped wrapper not to bypass verification, got Success: {result:?}"
1206        );
1207    }
1208
1209    // -- Install-time dialect content hashing (SPEC-014 REQ-628) --
1210
1211    /// Parse dialect source text and install it into a fresh registry,
1212    /// returning the installed dialect's hash.
1213    fn parse_install_hash(source: &str) -> String {
1214        let sexpr = parser::parse(source).expect("dialect source parses");
1215        let d = crate::dialect_parser::parse_dialect(&sexpr).expect("dialect extracts");
1216        assert!(d.hash.is_none(), "source declares no :hash");
1217        let mut registry = DialectRegistry::new();
1218        registry.install(d).expect("dialect installs");
1219        registry
1220            .get(1)
1221            .expect("installed at index 1")
1222            .hash
1223            .clone()
1224            .expect("install populates hash")
1225    }
1226
1227    #[test]
1228    fn parsed_dialect_hash_populated_after_install() {
1229        let h = parse_install_hash(
1230            "(define greeting-dialect (cbcl) @author (extend greet () (effect greet-action)))",
1231        );
1232        let hex = h.strip_prefix("f1220").expect("f1220 prefix");
1233        assert_eq!(hex.len(), 64);
1234        assert!(hex
1235            .chars()
1236            .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)));
1237    }
1238
1239    #[test]
1240    fn parsed_dialect_hash_stable_under_reformatting() {
1241        // Same dialect, different whitespace/formatting: the hash is over
1242        // the RFC 9804 canonical form, so formatting cannot change it.
1243        let compact =
1244            "(define greeting-dialect (cbcl) @author (extend greet () (effect greet-action)))";
1245        let sprawling = "(define greeting-dialect\n    (cbcl)\n    @author\n    (extend greet\n        ()\n        (effect    greet-action)))\n";
1246        assert_eq!(
1247            parse_install_hash(compact),
1248            parse_install_hash(sprawling),
1249            "reformatted-but-equal source must yield the identical hash"
1250        );
1251    }
1252
1253    #[test]
1254    fn parsed_dialect_hash_changes_when_performative_renamed() {
1255        let original =
1256            "(define greeting-dialect (cbcl) @author (extend greet () (effect greet-action)))";
1257        let renamed =
1258            "(define greeting-dialect (cbcl) @author (extend salute () (effect greet-action)))";
1259        assert_ne!(
1260            parse_install_hash(original),
1261            parse_install_hash(renamed),
1262            "renaming a performative must change the hash"
1263        );
1264    }
1265
1266    #[test]
1267    fn blame_carries_installed_dialect_hash() {
1268        // With install-time hashing, shape-violation blame must now carry
1269        // `:dialect-hash` (previously None for unhashed dialects), and the
1270        // rest of the blame output is unchanged.
1271        let mut registry = DialectRegistry::new();
1272        registry
1273            .install(cbcl_core::dialect::Dialect {
1274                types: Default::default(),
1275                roles: Vec::new(),
1276                state: None,
1277                state_bounds: None,
1278                causal_locality: Default::default(),
1279                name: String::from("shape-dialect"),
1280                extends: alloc::vec![String::from("cbcl")],
1281                author: Some(String::from("@shape-author")),
1282                performatives: alloc::vec![PerformativeDef {
1283                    role: None,
1284                    name: String::from("propose"),
1285                    params: alloc::vec![],
1286                    template: effect_template("propose-action"),
1287                }],
1288                resources: ResourceBounds {
1289                    max_depth: 8,
1290                    max_expansion_size: 512,
1291                },
1292                examples: alloc::vec![],
1293                signature: None,
1294                hash: None,
1295                protocol: None,
1296                causal_protocol: None,
1297                shapes: alloc::vec![ShapeConstraint {
1298                    performative: String::from("propose"),
1299                    rules: alloc::vec![ShapeRule::Require {
1300                        keyword: String::from("target"),
1301                        type_constraint: Some(TypeConstraint::String),
1302                        children: alloc::vec![],
1303                    }],
1304                }],
1305            })
1306            .unwrap();
1307        let installed_hash = registry
1308            .find_by_name("shape-dialect")
1309            .unwrap()
1310            .hash
1311            .clone()
1312            .expect("install populates hash");
1313
1314        let store = ThreadedMessageStore::new();
1315        let ctx = PipelineContext::new(&registry, &store);
1316        let result = run_pipeline_full("(lang shape-dialect (propose \"idea\"))", &ctx);
1317        let PipelineResult::ValidationError(ValidationError::ShapeViolation { blame, .. }) = result
1318        else {
1319            panic!("expected shape violation, got {result:?}");
1320        };
1321        assert_eq!(blame.dialect_hash.as_deref(), Some(installed_hash.as_str()));
1322        assert_eq!(blame.dialect.as_deref(), Some("shape-dialect"));
1323        assert_eq!(blame.performative.as_deref(), Some("propose"));
1324        let rendered = alloc::format!("{}", blame.to_sexpr());
1325        assert!(
1326            rendered.contains("dialect-hash") && rendered.contains(&installed_hash),
1327            "blame wire form must carry the installed dialect hash: {rendered}"
1328        );
1329    }
1330}