cbcl-parser 0.3.1

CBCL pure parser and pipeline
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
//! Full verified pipeline.
//!
//! Mirrors `Pipeline.lean` from the Lean 4 proof library.
//!
//! The pipeline chains: parse → parse_message → validate → expand →
//! causal verify (6a) → shape check (6b) → success.
//!
//! Two entry points:
//! - [`run_pipeline`] — lightweight parse + validate (no runtime context).
//! - [`run_pipeline_full`] — full verification with dialect registry and
//!   message store, including causal verification and shape checking
//!   (REQ-231: fail-closed, no bypass, no partial checks).

#![forbid(unsafe_code)]

use crate::parser::{self, ParseError};
use alloc::string::String;
use alloc::vec::Vec;
use cbcl_core::blame::ViolationError;
use cbcl_core::dialect::{Dialect, DialectRegistry};
use cbcl_core::evaluator::{evaluate_without_shape_check, EvalError};
use cbcl_core::message::Message;
use cbcl_core::policy::{apply_policy, PendingReason, PolicyOutcome, UnknownPredecessorPolicy};
use cbcl_core::protocol::CausalViolation;
use cbcl_core::r1;
use cbcl_core::r3;
use cbcl_core::r5;
use cbcl_core::sexpr::SExpr;
use cbcl_core::shape::ShapeViolation;
use cbcl_core::store::{MessageStore, ThreadId};
use core::fmt;

/// Validation errors from the pipeline (ADR-002).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationError {
    R1RecursivePerformative {
        performatives: Vec<String>,
    },
    R2ResourceBoundsInvalid {
        field: &'static str,
        value: u32,
    },
    R2FuelExhausted,
    R3CoreOverride {
        performatives: Vec<String>,
    },
    R4SignatureInvalid,
    /// R5 shape/protocol well-formedness violation (REQ-208, REQ-222).
    R5Violation {
        errors: Vec<String>,
    },
    /// Causal protocol violation (REQ-231, step 6a).
    CausalViolation {
        violation: CausalViolation,
        blame: ViolationError,
    },
    /// Shape constraint violation (REQ-231, step 6b).
    ShapeViolation {
        violation: ShapeViolation,
        blame: ViolationError,
    },
    MalformedMessage {
        reason: String,
    },
    MalformedDialect {
        reason: String,
    },
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ValidationError::R1RecursivePerformative { performatives } => {
                write!(
                    f,
                    "R1 violation: recursive performative(s): {}",
                    performatives.join(", ")
                )
            }
            ValidationError::R2ResourceBoundsInvalid { field, value } => {
                write!(f, "R2 violation: invalid resource bound {field}={value}")
            }
            ValidationError::R2FuelExhausted => write!(f, "R2 violation: fuel exhausted"),
            ValidationError::R3CoreOverride { performatives } => {
                write!(
                    f,
                    "R3 violation: core performative(s) overridden: {}",
                    performatives.join(", ")
                )
            }
            ValidationError::R4SignatureInvalid => write!(f, "R4 violation: invalid signature"),
            ValidationError::R5Violation { errors } => {
                write!(f, "R5 violation: {}", errors.join("; "))
            }
            ValidationError::CausalViolation { blame, .. } => {
                write!(f, "causal violation: {}", blame)
            }
            ValidationError::ShapeViolation { blame, .. } => {
                write!(f, "shape violation: {}", blame)
            }
            ValidationError::MalformedMessage { reason } => {
                write!(f, "malformed message: {reason}")
            }
            ValidationError::MalformedDialect { reason } => {
                write!(f, "malformed dialect: {reason}")
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ValidationError {}

/// Top-level pipeline result (REQ-111).
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(clippy::large_enum_variant)]
pub enum PipelineResult {
    Success(Message),
    ParseError(ParseError),
    ValidationError(ValidationError),
    /// Causal predecessor not yet in the local store (REQ-305).
    ///
    /// Returned only under [`UnknownPredecessorPolicy::Reject`]. Senders may
    /// retry once the predecessor arrives. The pipeline does not buffer; under
    /// [`UnknownPredecessorPolicy::Buffer`] callers receive [`PipelineResult::Buffered`]
    /// and are responsible for enqueuing the message into a `PendingQueue`.
    Pending {
        message: Message,
        reason: PendingReason,
    },
    /// Causal predecessor unknown; caller should buffer for re-evaluation
    /// (REQ-305 Buffer policy).
    Buffered {
        message: Message,
    },
}

/// Runtime context for the full pipeline (REQ-231).
///
/// Provides the dialect registry and message store needed for causal
/// verification (step 6a) and shape checking (step 6b), plus the policy that
/// governs how `VerificationResult::Unknown` is handled (REQ-305).
pub struct PipelineContext<'a, S: MessageStore> {
    pub registry: &'a DialectRegistry,
    pub store: &'a S,
    /// Policy applied when a `:caused-by` hash is not yet present in the
    /// store. Defaults to [`UnknownPredecessorPolicy::Reject`] when callers
    /// use the [`PipelineContext::new`] constructor.
    pub policy: UnknownPredecessorPolicy,
}

impl<'a, S: MessageStore> PipelineContext<'a, S> {
    /// Create a context with the default `Reject` policy.
    pub fn new(registry: &'a DialectRegistry, store: &'a S) -> Self {
        Self {
            registry,
            store,
            policy: UnknownPredecessorPolicy::default(),
        }
    }

    /// Create a context with an explicit policy.
    pub fn with_policy(
        registry: &'a DialectRegistry,
        store: &'a S,
        policy: UnknownPredecessorPolicy,
    ) -> Self {
        Self {
            registry,
            store,
            policy,
        }
    }
}

/// Run the lightweight verified pipeline (REQ-110).
///
/// Pipeline: parse → parse_message → validate → (for meta/define/teach: verify R1–R5) → success.
///
/// This entry point does **not** perform causal verification or shape checking
/// on simple messages (no runtime context). Use [`run_pipeline_full`] for
/// complete monitoring.
pub fn run_pipeline(input: &str) -> PipelineResult {
    let sexpr = match parser::parse(input) {
        Ok(e) => e,
        Err(e) => return PipelineResult::ParseError(e),
    };

    let message = match crate::message_parser::parse_message(&sexpr) {
        Ok(m) => m,
        Err(reason) => {
            return PipelineResult::ValidationError(ValidationError::MalformedMessage { reason })
        }
    };

    // For meta define/teach messages, validate the dialect definition (REQ-208, REQ-210).
    if let Err(err) = validate_meta_dialect(&message, None) {
        return PipelineResult::ValidationError(err);
    }

    PipelineResult::Success(message)
}

/// Run the full verified pipeline with runtime context (REQ-231).
///
/// Pipeline: parse → parse_message → validate → (for meta/define/teach: verify R1–R5)
/// → evaluate (expand) → causal verify (6a) → shape check (6b) → success.
///
/// **Fail-closed**: any error at any step produces a `ValidationError`. No code
/// path from receive to deliver skips verification (CON-206).
pub fn run_pipeline_full<S: MessageStore>(
    input: &str,
    ctx: &PipelineContext<'_, S>,
) -> PipelineResult {
    // Step 1: Parse text → S-expression
    let sexpr = match parser::parse(input) {
        Ok(e) => e,
        Err(e) => return PipelineResult::ParseError(e),
    };

    // Step 2: Parse S-expression → Message
    let message = match crate::message_parser::parse_message(&sexpr) {
        Ok(m) => m,
        Err(reason) => {
            return PipelineResult::ValidationError(ValidationError::MalformedMessage { reason })
        }
    };

    // Step 3: For meta define/teach messages, validate R1–R5 (REQ-208, REQ-210).
    // Pass the runtime registry so child dialects extending non-base parents
    // are resolved correctly during R5 protocol-definedness (REQ-206).
    if let Err(err) = validate_meta_dialect(&message, Some(ctx.registry)) {
        return PipelineResult::ValidationError(err);
    }

    // Steps 4–6: For simple messages, causal verify (6a) → evaluate (4) → shape check (6b).
    //
    // Causal verification runs before evaluation so a causal failure cannot be
    // masked by a downstream shape error, and so callers always see the most
    // specific violation first (REQ-231 fail-closed ordering).
    //
    // Wrapped (`envelope`/`signed`/`with-limits`) and dialect-scoped (`lang`)
    // messages defer to their innermost Simple payload so wrappers cannot be
    // used to bypass causal/shape verification.
    let inner_simple = message.innermost_simple();
    if let Some(Message::Simple {
        caused_by,
        thread,
        performative,
        ..
    }) = inner_simple
    {
        let performative = Some(performative);

        // Step 6a: Causal verification (REQ-231).
        //
        // A child dialect can declare a protocol step for a performative
        // inherited from a parent (including core performatives like `ok`),
        // so it is *not* sufficient to find the dialect that *defines* the
        // performative. Instead iterate every installed dialect: any whose
        // `causal_protocol` declares a step for `perf_name` participates in
        // verification, and constraints compose by conjunction (any
        // rejection rejects the message).
        if let Some(perf) = performative {
            let perf_name = perf.name();
            let thread_id = ThreadId(thread.clone().unwrap_or_else(|| String::from("default")));

            for d in ctx.registry.iter() {
                let Some(ref proto) = d.causal_protocol else {
                    continue;
                };
                if !proto.steps.contains_key(perf_name) {
                    continue;
                }

                let result = cbcl_core::protocol::verify_causal(
                    perf_name,
                    caused_by.as_ref(),
                    ctx.store,
                    proto,
                    &thread_id,
                );

                match apply_policy(&result, &ctx.policy) {
                    PolicyOutcome::Accept => {}
                    PolicyOutcome::Reject(cv) => {
                        let blame =
                            ViolationError::from_causal_violation(&cv, None, thread.clone())
                                .with_dialect_context(
                                    &d.name,
                                    d.author.as_deref(),
                                    d.hash.as_deref(),
                                    Some(perf_name),
                                );
                        blame.record_metrics(&d.name);
                        return PipelineResult::ValidationError(ValidationError::CausalViolation {
                            violation: cv,
                            blame,
                        });
                    }
                    PolicyOutcome::Pending(reason) => {
                        return PipelineResult::Pending { message, reason };
                    }
                    PolicyOutcome::Buffered => {
                        return PipelineResult::Buffered { message };
                    }
                }
            }
        }

        // Step 4: Evaluate (template expansion). Shape checking is deferred to
        // step 6b so blame can include the expanded form.
        let eval_result = match evaluate_without_shape_check(&message, ctx.registry) {
            Ok(r) => r,
            Err(eval_err) => {
                return PipelineResult::ValidationError(eval_error_to_validation(
                    eval_err,
                    thread.clone(),
                ))
            }
        };

        // Step 6b: Shape checking on expanded message (REQ-223, REQ-224, REQ-231).
        // Compose via conjunction: every matching shape constraint must pass.
        if let Some(perf) = performative {
            let perf_name = perf.name();
            for dialect in ctx.registry.iter() {
                for shape in &dialect.shapes {
                    if shape.performative == perf_name {
                        if let Err(sv) = shape.check(&eval_result.expanded) {
                            let blame = ViolationError::from_shape_violation(
                                &sv,
                                None,
                                thread.clone(),
                                None,
                            )
                            .with_dialect_context(
                                &dialect.name,
                                dialect.author.as_deref(),
                                dialect.hash.as_deref(),
                                Some(perf_name),
                            );
                            blame.record_metrics(&dialect.name);
                            return PipelineResult::ValidationError(
                                ValidationError::ShapeViolation {
                                    violation: sv,
                                    blame,
                                },
                            );
                        }
                    }
                }
            }
        }
    }

    PipelineResult::Success(message)
}

/// Validate meta define/teach dialect definitions (REQ-208, REQ-210).
///
/// Both `(meta (define ...))` and `(meta (teach ...))` carry dialect definitions
/// that must pass R1–R5 before acceptance. The teach form includes protocol and
/// shape declarations for gossip propagation.
#[allow(clippy::result_large_err)]
fn validate_meta_dialect(
    message: &Message,
    registry: Option<&DialectRegistry>,
) -> Result<(), ValidationError> {
    if let Message::Meta { ref dialect_def } = message {
        if let SExpr::List(items) = dialect_def {
            if items.is_empty() {
                return Ok(());
            }

            // (meta (define ...)) — direct dialect definition
            if items[0].is_symbol("define") {
                return validate_define_dialect(dialect_def, registry);
            }

            // (meta (teach <recipient> <define-form>)) — gossip propagation (REQ-210).
            // The teach form wraps a define; extract and validate the inner definition.
            if items[0].is_symbol("teach") {
                // (teach <recipient> (define ...))
                // Find the inner define form — it's the first list element after the symbol.
                for item in items.iter().skip(1) {
                    if let SExpr::List(inner_items) = item {
                        if !inner_items.is_empty() && inner_items[0].is_symbol("define") {
                            return validate_define_dialect(item, registry);
                        }
                    }
                }
                // teach without define — no dialect to validate, pass through.
            }
        }
    }
    Ok(())
}

#[allow(clippy::result_large_err)]
fn validate_define_dialect(
    dialect_def: &SExpr,
    registry: Option<&DialectRegistry>,
) -> Result<(), ValidationError> {
    let dialect = crate::dialect_parser::parse_dialect(dialect_def)
        .map_err(|reason| ValidationError::MalformedDialect { reason })?;

    let recursive = r1::r1_violations(&dialect);
    if !recursive.is_empty() {
        return Err(ValidationError::R1RecursivePerformative {
            performatives: recursive,
        });
    }

    if let Some((field, value)) = invalid_resource_bound(&dialect) {
        return Err(ValidationError::R2ResourceBoundsInvalid { field, value });
    }

    let overrides = r3::r3_violations(&dialect);
    if !overrides.is_empty() {
        return Err(ValidationError::R3CoreOverride {
            performatives: overrides,
        });
    }

    // R5: shape + protocol well-formedness (REQ-208, REQ-222).
    //
    // When a registry is available (full pipeline), resolve every `extends`
    // entry against the installed dialects so child protocols can reference
    // ancestor performatives without false-rejecting (REQ-206). Without a
    // registry (lightweight pipeline) we still credit the base dialect for
    // shorthand `cbcl` / canonical `cbcl-base` so most real definitions keep
    // working. Other named parents we cannot resolve here — install-time R5
    // re-checks definedness against the actual ancestor chain.
    let base = cbcl_core::dialect::base_dialect();
    let mut ancestors: alloc::vec::Vec<&cbcl_core::dialect::Dialect> = alloc::vec![];
    let mut credited_base = false;
    if let Some(reg) = registry {
        for name in &dialect.extends {
            let resolved = if name == "cbcl" {
                "cbcl-base"
            } else {
                name.as_str()
            };
            if let Some(parent) = reg.find_by_name(resolved) {
                ancestors.push(parent);
                if resolved == base.name {
                    credited_base = true;
                }
            }
        }
    }
    if !credited_base {
        let extends_base = dialect
            .extends
            .iter()
            .any(|name| name == "cbcl" || name == &base.name);
        if extends_base {
            ancestors.push(&base);
        }
    }
    let r5_errors = r5::r5_violations_with_ancestors(&dialect, &ancestors);
    if !r5_errors.is_empty() {
        return Err(ValidationError::R5Violation { errors: r5_errors });
    }

    Ok(())
}

fn invalid_resource_bound(dialect: &Dialect) -> Option<(&'static str, u32)> {
    let bounds = &dialect.resources;
    if bounds.max_depth == 0 || bounds.max_depth > 64 {
        return Some(("max_depth", bounds.max_depth));
    }
    if bounds.max_expansion_size == 0 || bounds.max_expansion_size > 8192 {
        return Some(("max_expansion_size", bounds.max_expansion_size));
    }
    None
}

/// Map evaluator errors to pipeline validation errors.
///
/// `thread` is the originating message's thread, threaded through so blame
/// records carry it even when the evaluator surfaces a violation before the
/// pipeline reaches its dedicated shape-check step (REQ-231).
fn eval_error_to_validation(err: EvalError, thread: Option<String>) -> ValidationError {
    match err {
        EvalError::UnknownPerformative(name) => ValidationError::MalformedMessage {
            reason: alloc::format!("unknown performative: {name}"),
        },
        // REQ-033: a dialect performative must name its dialect. The
        // recogniser rejects the unscoped form, so this path is reached only
        // by programmatically constructed messages.
        EvalError::UnscopedDialectPerformative(name) => ValidationError::MalformedMessage {
            reason: alloc::format!(
                "dialect performative '{name}' invoked outside (lang <dialect> ...); \
                 the message must name the dialect that defines it"
            ),
        },
        EvalError::TemplateExpansionFailed { performative: _ } => ValidationError::R2FuelExhausted,
        EvalError::UnknownDialect(name) => ValidationError::MalformedMessage {
            reason: alloc::format!("unknown dialect: {name}"),
        },
        EvalError::MalformedMessage(reason) => ValidationError::MalformedMessage { reason },
        EvalError::ShapeViolation(sv) => {
            let blame = ViolationError::from_shape_violation(&sv, None, thread, None);
            ValidationError::ShapeViolation {
                violation: sv,
                blame,
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::collections::BTreeMap;
    use cbcl_core::dialect::{DialectRegistry, PerformativeDef, ResourceBounds};
    use cbcl_core::message::{CausedBy, MessageType, Performative};
    use cbcl_core::protocol::{CausalProtocol, NodeRef, StepDecl};
    use cbcl_core::sexpr::Atom;
    use cbcl_core::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
    use cbcl_core::store::{ContentHash, ThreadId, ThreadedMessageStore};

    fn effect_template(action: &str) -> SExpr {
        SExpr::List(alloc::vec![
            SExpr::Atom(Atom::Symbol(String::from("effect"))),
            SExpr::Atom(Atom::Symbol(String::from(action))),
        ])
    }

    fn make_simple_msg(perf: &str, caused_by: Option<CausedBy>) -> Message {
        Message::Simple {
            performative: Performative::Custom(String::from(perf)),
            recipient: None,
            content: SExpr::Atom(Atom::Str(String::from("test"))),
            params: alloc::vec![],
            thread: None,
            sender: None,
            caused_by,
        }
    }

    // -- Basic pipeline (no context) --

    #[test]
    fn pipeline_parse_error() {
        let result = run_pipeline("(unclosed");
        assert!(matches!(result, PipelineResult::ParseError(_)));
    }

    #[test]
    fn pipeline_simple_message() {
        let result = run_pipeline("(tell \"hello\")");
        assert!(matches!(result, PipelineResult::Success(_)));
        if let PipelineResult::Success(msg) = result {
            assert_eq!(msg.message_type(), MessageType::Simple);
        }
    }

    #[test]
    fn pipeline_meta_define() {
        let input = "(meta (define test-dialect (cbcl) @author))";
        let result = run_pipeline(input);
        assert!(matches!(result, PipelineResult::Success(_)));
        if let PipelineResult::Success(msg) = result {
            assert_eq!(msg.message_type(), MessageType::Meta);
        }
    }

    #[test]
    fn pipeline_malformed_dialect() {
        let input = "(meta (define))"; // missing required fields
        let result = run_pipeline(input);
        assert!(matches!(
            result,
            PipelineResult::ValidationError(ValidationError::MalformedDialect { .. })
        ));
    }

    #[test]
    fn pipeline_custom_performative() {
        let result = run_pipeline(
            "(lang cbcl-planning (share-conditional pickup box-location box-in-hand))",
        );
        assert!(matches!(result, PipelineResult::Success(_)));
    }

    #[test]
    fn pipeline_meta_query() {
        let result = run_pipeline("(meta (query (speak? cbcl-planning)))");
        assert!(matches!(result, PipelineResult::Success(_)));
    }

    #[test]
    fn pipeline_rejects_r3_core_override() {
        let result = run_pipeline("(meta (define bad (cbcl) @author (extend tell () x)))");
        assert!(matches!(
            result,
            PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
        ));
    }

    #[test]
    fn pipeline_rejects_mutual_recursion() {
        let result = run_pipeline(
            "(meta (define cyclic (cbcl) @author (extend ping () (pong)) (extend pong () (ping))))",
        );
        assert!(matches!(
            result,
            PipelineResult::ValidationError(ValidationError::R1RecursivePerformative { .. })
        ));
    }

    // -- REQ-210: teach messages validated same as define --

    #[test]
    fn pipeline_teach_validates_r3() {
        let result =
            run_pipeline("(meta (teach @bob (define bad (cbcl) @author (extend tell () x))))");
        assert!(matches!(
            result,
            PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
        ));
    }

    #[test]
    fn pipeline_teach_valid_passes() {
        let result = run_pipeline("(meta (teach @bob (define good-dialect (cbcl) @author)))");
        assert!(matches!(result, PipelineResult::Success(_)));
    }

    // -- REQ-231: full pipeline with context --

    #[test]
    fn full_pipeline_simple_message_passes() {
        let registry = DialectRegistry::new();
        let store = ThreadedMessageStore::new();
        let ctx = PipelineContext::new(&registry, &store);
        let result = run_pipeline_full("(tell \"hello\")", &ctx);
        assert!(matches!(result, PipelineResult::Success(_)));
    }

    #[test]
    fn full_pipeline_rejects_causal_violation() {
        let mut registry = DialectRegistry::new();

        // Install a dialect with a causal protocol: begin → greet
        let mut steps = BTreeMap::new();
        steps.insert(
            "begin".into(),
            StepDecl {
                performative: "begin".into(),
                predecessors: alloc::vec![],
                successors: alloc::vec![NodeRef::Single("greet".into())],
            },
        );
        steps.insert(
            "greet".into(),
            StepDecl {
                performative: "greet".into(),
                predecessors: alloc::vec![NodeRef::Single("begin".into())],
                successors: alloc::vec![],
            },
        );
        let proto = CausalProtocol { steps };

        registry
            .install(cbcl_core::dialect::Dialect {
                types: Default::default(),
                roles: Vec::new(),
                state: None,
                state_bounds: None,
                causal_locality: Default::default(),
                name: String::from("proto-dialect"),
                extends: alloc::vec![String::from("cbcl")],
                author: None,
                performatives: alloc::vec![PerformativeDef {
                    role: None,
                    name: String::from("greet"),
                    params: alloc::vec![],
                    template: effect_template("greet-action"),
                }],
                resources: ResourceBounds {
                    max_depth: 8,
                    max_expansion_size: 512,
                },
                examples: alloc::vec![],
                signature: None,
                hash: None,
                protocol: None,
                causal_protocol: Some(proto),
                shapes: alloc::vec![],
            })
            .unwrap();

        let store = ThreadedMessageStore::new();
        let ctx = PipelineContext::new(&registry, &store);

        // Send "greet" without :caused-by — protocol requires begin as predecessor.
        let result = run_pipeline_full("(lang proto-dialect (greet \"hi\"))", &ctx);
        assert!(
            matches!(
                result,
                PipelineResult::ValidationError(ValidationError::CausalViolation { .. })
            ),
            "expected causal violation, got {:?}",
            result
        );
    }

    #[test]
    fn full_pipeline_shape_violation_rejected() {
        let mut registry = DialectRegistry::new();

        // Install dialect with shape constraint requiring :target string
        registry
            .install(cbcl_core::dialect::Dialect {
                types: Default::default(),
                roles: Vec::new(),
                state: None,
                state_bounds: None,
                causal_locality: Default::default(),
                name: String::from("shape-dialect"),
                extends: alloc::vec![String::from("cbcl")],
                author: None,
                performatives: alloc::vec![PerformativeDef {
                    role: None,
                    name: String::from("propose"),
                    params: alloc::vec![],
                    template: effect_template("propose-action"),
                }],
                resources: ResourceBounds {
                    max_depth: 8,
                    max_expansion_size: 512,
                },
                examples: alloc::vec![],
                signature: None,
                hash: None,
                protocol: None,
                causal_protocol: None,
                shapes: alloc::vec![ShapeConstraint {
                    performative: String::from("propose"),
                    rules: alloc::vec![ShapeRule::Require {
                        keyword: String::from("target"),
                        type_constraint: Some(TypeConstraint::String),
                        children: alloc::vec![],
                    }],
                }],
            })
            .unwrap();

        let store = ThreadedMessageStore::new();
        let ctx = PipelineContext::new(&registry, &store);

        // "propose" without :target — shape requires it.
        let result = run_pipeline_full("(lang shape-dialect (propose \"idea\"))", &ctx);
        assert!(
            matches!(
                result,
                PipelineResult::ValidationError(ValidationError::ShapeViolation { .. })
            ),
            "expected shape violation, got {:?}",
            result
        );
    }

    #[test]
    fn full_pipeline_causal_valid_with_predecessor() {
        let mut registry = DialectRegistry::new();

        // Protocol: begin → ack
        let mut steps = BTreeMap::new();
        steps.insert(
            "begin".into(),
            StepDecl {
                performative: "begin".into(),
                predecessors: alloc::vec![],
                successors: alloc::vec![NodeRef::Single("ack".into())],
            },
        );
        steps.insert(
            "ack".into(),
            StepDecl {
                performative: "ack".into(),
                predecessors: alloc::vec![NodeRef::Single("begin".into())],
                successors: alloc::vec![],
            },
        );
        let proto = CausalProtocol { steps };

        registry
            .install(cbcl_core::dialect::Dialect {
                types: Default::default(),
                roles: Vec::new(),
                state: None,
                state_bounds: None,
                causal_locality: Default::default(),
                name: String::from("ack-dialect"),
                extends: alloc::vec![String::from("cbcl")],
                author: None,
                performatives: alloc::vec![PerformativeDef {
                    role: None,
                    name: String::from("ack"),
                    params: alloc::vec![],
                    template: effect_template("ack-action"),
                }],
                resources: ResourceBounds {
                    max_depth: 8,
                    max_expansion_size: 512,
                },
                examples: alloc::vec![],
                signature: None,
                hash: None,
                protocol: None,
                causal_protocol: Some(proto),
                shapes: alloc::vec![],
            })
            .unwrap();

        let thread = ThreadId(String::from("default"));
        let mut store = ThreadedMessageStore::new();
        // Insert a "begin" message that the ack can reference.
        store.append(
            ContentHash(String::from("abc123")),
            thread.clone(),
            make_simple_msg("begin", Some(CausedBy::Begin)),
        );

        let ctx = PipelineContext::new(&registry, &store);

        // "ack" with :caused-by pointing to the begin message.
        let result = run_pipeline_full(
            "(lang ack-dialect (ack \"done\" :caused-by \"abc123\"))",
            &ctx,
        );
        assert!(
            matches!(result, PipelineResult::Success(_)),
            "expected success, got {:?}",
            result
        );
    }

    #[test]
    fn full_pipeline_meta_define_still_validated() {
        let registry = DialectRegistry::new();
        let store = ThreadedMessageStore::new();
        let ctx = PipelineContext::new(&registry, &store);
        // R3 violation via full pipeline
        let result = run_pipeline_full(
            "(meta (define bad (cbcl) @author (extend tell () x)))",
            &ctx,
        );
        assert!(matches!(
            result,
            PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
        ));
    }

    #[test]
    fn full_pipeline_teach_validated() {
        let registry = DialectRegistry::new();
        let store = ThreadedMessageStore::new();
        let ctx = PipelineContext::new(&registry, &store);
        let result = run_pipeline_full(
            "(meta (teach @bob (define bad (cbcl) @author (extend tell () x))))",
            &ctx,
        );
        assert!(matches!(
            result,
            PipelineResult::ValidationError(ValidationError::R3CoreOverride { .. })
        ));
    }

    // -- REQ-305 / REQ-231: Unknown predecessor must not slip through --

    fn ack_dialect_registry() -> DialectRegistry {
        let mut registry = DialectRegistry::new();
        let mut steps = BTreeMap::new();
        steps.insert(
            "begin".into(),
            StepDecl {
                performative: "begin".into(),
                predecessors: alloc::vec![],
                successors: alloc::vec![NodeRef::Single("ack".into())],
            },
        );
        steps.insert(
            "ack".into(),
            StepDecl {
                performative: "ack".into(),
                predecessors: alloc::vec![NodeRef::Single("begin".into())],
                successors: alloc::vec![],
            },
        );
        let proto = CausalProtocol { steps };

        registry
            .install(cbcl_core::dialect::Dialect {
                types: Default::default(),
                roles: Vec::new(),
                state: None,
                state_bounds: None,
                causal_locality: Default::default(),
                name: String::from("ack-dialect"),
                extends: alloc::vec![String::from("cbcl")],
                author: None,
                performatives: alloc::vec![PerformativeDef {
                    role: None,
                    name: String::from("ack"),
                    params: alloc::vec![],
                    template: effect_template("ack-action"),
                }],
                resources: ResourceBounds {
                    max_depth: 8,
                    max_expansion_size: 512,
                },
                examples: alloc::vec![],
                signature: None,
                hash: None,
                protocol: None,
                causal_protocol: Some(proto),
                shapes: alloc::vec![],
            })
            .unwrap();
        registry
    }

    #[test]
    fn full_pipeline_unknown_predecessor_rejects_under_default_policy() {
        let registry = ack_dialect_registry();
        let store = ThreadedMessageStore::new(); // empty — predecessor absent
        let ctx = PipelineContext::new(&registry, &store);

        // ack with :caused-by referencing a hash not in the store.
        let result = run_pipeline_full(
            "(lang ack-dialect (ack \"done\" :caused-by \"missing-hash\"))",
            &ctx,
        );
        assert!(
            matches!(
                result,
                PipelineResult::Pending {
                    reason: cbcl_core::policy::PendingReason::CausalPending,
                    ..
                }
            ),
            "expected Pending under default Reject policy, got {:?}",
            result
        );
    }

    #[test]
    fn full_pipeline_unknown_predecessor_buffers_under_buffer_policy() {
        let registry = ack_dialect_registry();
        let store = ThreadedMessageStore::new();
        let ctx = PipelineContext::with_policy(
            &registry,
            &store,
            cbcl_core::policy::UnknownPredecessorPolicy::buffer(60),
        );

        let result = run_pipeline_full(
            "(lang ack-dialect (ack \"done\" :caused-by \"missing-hash\"))",
            &ctx,
        );
        assert!(
            matches!(result, PipelineResult::Buffered { .. }),
            "expected Buffered under Buffer policy, got {:?}",
            result
        );
    }

    // -- REQ-231: Pipeline orders causal before shape so a causal violation
    // is not masked by an inline shape failure (was: shape ran inside evaluate
    // before causal verification). --

    #[test]
    fn full_pipeline_causal_violation_takes_precedence_over_shape() {
        let mut registry = DialectRegistry::new();

        // Protocol requires "begin" before "ack". Shape requires :target string.
        let mut steps = BTreeMap::new();
        steps.insert(
            "begin".into(),
            StepDecl {
                performative: "begin".into(),
                predecessors: alloc::vec![],
                successors: alloc::vec![NodeRef::Single("ack".into())],
            },
        );
        steps.insert(
            "ack".into(),
            StepDecl {
                performative: "ack".into(),
                predecessors: alloc::vec![NodeRef::Single("begin".into())],
                successors: alloc::vec![],
            },
        );
        let proto = CausalProtocol { steps };

        registry
            .install(cbcl_core::dialect::Dialect {
                types: Default::default(),
                roles: Vec::new(),
                state: None,
                state_bounds: None,
                causal_locality: Default::default(),
                name: String::from("ack-with-shape"),
                extends: alloc::vec![String::from("cbcl")],
                author: None,
                performatives: alloc::vec![PerformativeDef {
                    role: None,
                    name: String::from("ack"),
                    params: alloc::vec![],
                    template: effect_template("ack-action"),
                }],
                resources: ResourceBounds {
                    max_depth: 8,
                    max_expansion_size: 512,
                },
                examples: alloc::vec![],
                signature: None,
                hash: None,
                protocol: None,
                causal_protocol: Some(proto),
                shapes: alloc::vec![ShapeConstraint {
                    performative: String::from("ack"),
                    rules: alloc::vec![ShapeRule::Require {
                        keyword: String::from("target"),
                        type_constraint: Some(TypeConstraint::String),
                        children: alloc::vec![],
                    }],
                }],
            })
            .unwrap();

        let store = ThreadedMessageStore::new();
        let ctx = PipelineContext::new(&registry, &store);

        // ack with no :caused-by AND no :target — both causal and shape would fail.
        // We must see CausalViolation, not ShapeViolation, because causal is checked first.
        let result = run_pipeline_full("(lang ack-with-shape (ack \"done\"))", &ctx);
        assert!(
            matches!(
                result,
                PipelineResult::ValidationError(ValidationError::CausalViolation { .. })
            ),
            "expected CausalViolation to take precedence, got {:?}",
            result
        );
    }

    // -- PR feedback P2: child dialect protocols on inherited performatives
    // (e.g. core `ok`) must be enforced. The dialect that *defines* `ok` is
    // `cbcl-base` (no protocol); the one that constrains it is the child. --

    #[test]
    fn full_pipeline_child_protocol_on_core_perf_is_enforced() {
        let mut registry = DialectRegistry::new();
        let mut steps = BTreeMap::new();
        steps.insert(
            "begin".into(),
            StepDecl {
                performative: "begin".into(),
                predecessors: alloc::vec![],
                successors: alloc::vec![NodeRef::Single("ok".into())],
            },
        );
        steps.insert(
            "ok".into(),
            StepDecl {
                performative: "ok".into(),
                predecessors: alloc::vec![NodeRef::Single("begin".into())],
                successors: alloc::vec![],
            },
        );
        registry
            .install(cbcl_core::dialect::Dialect {
                types: Default::default(),
                roles: Vec::new(),
                state: None,
                state_bounds: None,
                causal_locality: Default::default(),
                name: String::from("ok-protocol"),
                extends: alloc::vec![String::from("cbcl")],
                author: None,
                performatives: alloc::vec![], // no own perfs; constrains base `ok`
                resources: ResourceBounds {
                    max_depth: 8,
                    max_expansion_size: 512,
                },
                examples: alloc::vec![],
                signature: None,
                hash: None,
                protocol: None,
                causal_protocol: Some(CausalProtocol { steps }),
                shapes: alloc::vec![],
            })
            .unwrap();

        let store = ThreadedMessageStore::new();
        let ctx = PipelineContext::new(&registry, &store);

        // `(ok)` with no :caused-by — protocol requires "begin" as predecessor.
        let result = run_pipeline_full("(ok)", &ctx);
        assert!(
            matches!(
                result,
                PipelineResult::ValidationError(ValidationError::CausalViolation { .. })
            ),
            "expected child protocol on core `ok` to fire, got {:?}",
            result
        );
    }

    // -- PR feedback P2: meta-validation must use registry ancestors so a
    // child dialect extending a non-base installed parent isn't rejected. --

    #[test]
    fn full_pipeline_meta_define_credits_non_base_parent_via_registry() {
        let mut registry = DialectRegistry::new();
        // First install a parent dialect that defines `notify`.
        registry
            .install(cbcl_core::dialect::Dialect {
                types: Default::default(),
                roles: Vec::new(),
                state: None,
                state_bounds: None,
                causal_locality: Default::default(),
                name: String::from("parent-dialect"),
                extends: alloc::vec![String::from("cbcl")],
                author: None,
                performatives: alloc::vec![PerformativeDef {
                    role: None,
                    name: String::from("notify"),
                    params: alloc::vec![],
                    template: effect_template("notify-action"),
                }],
                resources: ResourceBounds {
                    max_depth: 8,
                    max_expansion_size: 512,
                },
                examples: alloc::vec![],
                signature: None,
                hash: None,
                protocol: None,
                causal_protocol: None,
                shapes: alloc::vec![],
            })
            .unwrap();

        let store = ThreadedMessageStore::new();
        let ctx = PipelineContext::new(&registry, &store);

        // Child meta define references parent's `notify` from its protocol.
        // Without registry-aware meta validation, this fails as undefined at
        // parse time even though install would accept it.
        let input = "\
            (meta (define child-dialect (parent-dialect) @author \
              (protocol (then begin notify))))";
        let result = run_pipeline_full(input, &ctx);
        assert!(
            matches!(result, PipelineResult::Success(_)),
            "expected meta-define with registry ancestor to pass, got {:?}",
            result
        );
    }

    // -- PR feedback P1: wrapped/dialect-scoped messages must verify their
    // innermost simple payload, not bypass causal/shape checks. --

    #[test]
    fn full_pipeline_envelope_wrapping_does_not_bypass_causal() {
        let registry = ack_dialect_registry();
        let store = ThreadedMessageStore::new();
        let ctx = PipelineContext::new(&registry, &store);

        // Wrap a protocol-violating ack inside an envelope. Without the
        // wrapper-traversal fix this returned Success.
        let result = run_pipeline_full(
            "(envelope (:from @alice) (ack \"done\" :caused-by \"missing\"))",
            &ctx,
        );
        assert!(
            !matches!(result, PipelineResult::Success(_)),
            "expected wrapper not to bypass verification, got Success: {result:?}"
        );
    }

    #[test]
    fn full_pipeline_lang_scoped_message_does_not_bypass_causal() {
        let registry = ack_dialect_registry();
        let store = ThreadedMessageStore::new();
        let ctx = PipelineContext::new(&registry, &store);

        // (lang ack-dialect (ack "done" :caused-by "missing"))
        let result = run_pipeline_full(
            "(lang ack-dialect (lang ack-dialect (ack \"done\" :caused-by \"missing\")))",
            &ctx,
        );
        assert!(
            !matches!(result, PipelineResult::Success(_)),
            "expected dialect-scoped wrapper not to bypass verification, got Success: {result:?}"
        );
    }

    // -- Install-time dialect content hashing (SPEC-014 REQ-628) --

    /// Parse dialect source text and install it into a fresh registry,
    /// returning the installed dialect's hash.
    fn parse_install_hash(source: &str) -> String {
        let sexpr = parser::parse(source).expect("dialect source parses");
        let d = crate::dialect_parser::parse_dialect(&sexpr).expect("dialect extracts");
        assert!(d.hash.is_none(), "source declares no :hash");
        let mut registry = DialectRegistry::new();
        registry.install(d).expect("dialect installs");
        registry
            .get(1)
            .expect("installed at index 1")
            .hash
            .clone()
            .expect("install populates hash")
    }

    #[test]
    fn parsed_dialect_hash_populated_after_install() {
        let h = parse_install_hash(
            "(define greeting-dialect (cbcl) @author (extend greet () (effect greet-action)))",
        );
        let hex = h.strip_prefix("f1220").expect("f1220 prefix");
        assert_eq!(hex.len(), 64);
        assert!(hex
            .chars()
            .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)));
    }

    #[test]
    fn parsed_dialect_hash_stable_under_reformatting() {
        // Same dialect, different whitespace/formatting: the hash is over
        // the RFC 9804 canonical form, so formatting cannot change it.
        let compact =
            "(define greeting-dialect (cbcl) @author (extend greet () (effect greet-action)))";
        let sprawling = "(define greeting-dialect\n    (cbcl)\n    @author\n    (extend greet\n        ()\n        (effect    greet-action)))\n";
        assert_eq!(
            parse_install_hash(compact),
            parse_install_hash(sprawling),
            "reformatted-but-equal source must yield the identical hash"
        );
    }

    #[test]
    fn parsed_dialect_hash_changes_when_performative_renamed() {
        let original =
            "(define greeting-dialect (cbcl) @author (extend greet () (effect greet-action)))";
        let renamed =
            "(define greeting-dialect (cbcl) @author (extend salute () (effect greet-action)))";
        assert_ne!(
            parse_install_hash(original),
            parse_install_hash(renamed),
            "renaming a performative must change the hash"
        );
    }

    #[test]
    fn blame_carries_installed_dialect_hash() {
        // With install-time hashing, shape-violation blame must now carry
        // `:dialect-hash` (previously None for unhashed dialects), and the
        // rest of the blame output is unchanged.
        let mut registry = DialectRegistry::new();
        registry
            .install(cbcl_core::dialect::Dialect {
                types: Default::default(),
                roles: Vec::new(),
                state: None,
                state_bounds: None,
                causal_locality: Default::default(),
                name: String::from("shape-dialect"),
                extends: alloc::vec![String::from("cbcl")],
                author: Some(String::from("@shape-author")),
                performatives: alloc::vec![PerformativeDef {
                    role: None,
                    name: String::from("propose"),
                    params: alloc::vec![],
                    template: effect_template("propose-action"),
                }],
                resources: ResourceBounds {
                    max_depth: 8,
                    max_expansion_size: 512,
                },
                examples: alloc::vec![],
                signature: None,
                hash: None,
                protocol: None,
                causal_protocol: None,
                shapes: alloc::vec![ShapeConstraint {
                    performative: String::from("propose"),
                    rules: alloc::vec![ShapeRule::Require {
                        keyword: String::from("target"),
                        type_constraint: Some(TypeConstraint::String),
                        children: alloc::vec![],
                    }],
                }],
            })
            .unwrap();
        let installed_hash = registry
            .find_by_name("shape-dialect")
            .unwrap()
            .hash
            .clone()
            .expect("install populates hash");

        let store = ThreadedMessageStore::new();
        let ctx = PipelineContext::new(&registry, &store);
        let result = run_pipeline_full("(lang shape-dialect (propose \"idea\"))", &ctx);
        let PipelineResult::ValidationError(ValidationError::ShapeViolation { blame, .. }) = result
        else {
            panic!("expected shape violation, got {result:?}");
        };
        assert_eq!(blame.dialect_hash.as_deref(), Some(installed_hash.as_str()));
        assert_eq!(blame.dialect.as_deref(), Some("shape-dialect"));
        assert_eq!(blame.performative.as_deref(), Some("propose"));
        let rendered = alloc::format!("{}", blame.to_sexpr());
        assert!(
            rendered.contains("dialect-hash") && rendered.contains(&installed_hash),
            "blame wire form must carry the installed dialect hash: {rendered}"
        );
    }
}