cbcl-parser 0.3.0

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
//! SPEC-038 threshold reads (REQ-3802, CON-3801).
//!
//! TEST-3801: a dialect declaring thresholds over `count`, `set-union`,
//! nonnegative numeric `events` and `progress`; any permutation and duplication of a
//! delivery reaches the same element, across the growth of the accepted set
//! an element is reached at most once (pending… then reached, never pending
//! again) on non-conflicting growth. Conflicts produce separate terminal faults.
//!
//! TEST-3803: installation rejects a threshold set whose elements are not
//! pairwise incompatible, an element not admitted by the field's carrier, an
//! undeclared field and a threshold declared before its field; and the
//! pairwise check runs in `O(k²)` comparisons.
//!
//! The kernel is a function of the accepted set, so the tests feed acts to
//! `fold` directly, restricted to causally closed prefixes as admission would
//! produce them (SPEC-038 REQ-3800).
use cbcl_core::lattice::{pairwise, Element};
use cbcl_core::state::{fold, render_json, render_schema, state_schema, Act, Value as V};
use cbcl_parser::state_exports::{self, parse_and_install_dialect, Admission};
use cbcl_parser::{parse, parse_dialect, parse_message};
use proptest::prelude::*;
use serde_json::{json, Value};
use std::collections::BTreeSet;

const DEMO: &str = "(define threshold-demo (cbcl) @anuna \
  (extend open (to) (tell to)) \
  (extend tick (to) (tell to)) \
  (extend approve (to) (tell to)) \
  (extend tag (to label) (tell to :label label)) \
  (extend mint (to amount) (tell to :amount amount)) \
  (extend burn (to amount) (tell to :amount amount)) \
  (shape tag (require :label string)) \
  (shape mint (require :amount nonnegative)) \
  (shape burn (require :amount integer)) \
  (protocol (then begin open) (then open (repeat 3 tick)) (then open approve) (then open tag) (then open mint) (then open burn)) \
  (state \
    (approvals (count approve)) \
    (threshold quorum approvals (count 2)) \
    (tags (set-union tag :label)) \
    (threshold tagged tags (member \"x\")) \
    (balance (counter mint burn :amount)) \
    (credits (events mint :amount)) \
    (threshold funded credits (sum 10)) \
    (stage (progress tick)) \
    (threshold done stage (progress 2))))";

const THRESHOLDS: [&str; 4] = ["quorum", "tagged", "funded", "done"];

fn act(canonical: &str, signer: &str) -> Act {
    Act::from_message(parse_message(&parse(canonical).unwrap()).unwrap(), signer).unwrap()
}

fn demo(verb: &str, params: &str, pred: &str, signer: &str) -> Act {
    act(
        &format!(
            "(lang threshold-demo ({verb} @room{params} :caused-by {pred} :thread \"t\" :from {signer}))"
        ),
        signer,
    )
}

fn open() -> Act {
    demo("open", "", "begin", "@opener")
}

fn state_of(source: &str, acts: &[Act]) -> Value {
    let d = parse_dialect(&parse(source).unwrap()).unwrap();
    serde_json::from_str(&render_json(&fold(
        d.state.as_ref().unwrap(),
        d.causal_protocol.as_ref(),
        acts,
    )))
    .unwrap()
}

fn install(source: &str) -> Result<(), String> {
    parse_and_install_dialect(&parse(source).unwrap()).map(|_| ())
}

/// The largest causally closed subset of `acts`: what admission (R.1)
/// would have accepted from this delivery.
fn closed(acts: &[Act]) -> Vec<Act> {
    let mut present: BTreeSet<String> = BTreeSet::new();
    loop {
        let next: BTreeSet<String> = acts
            .iter()
            .filter(|a| {
                a.predecessors
                    .iter()
                    .all(|p| p == "begin" || present.contains(p))
            })
            .map(|a| a.address.clone())
            .collect();
        if next == present {
            break;
        }
        present = next;
    }
    acts.iter()
        .filter(|a| present.contains(&a.address))
        .cloned()
        .collect()
}

// ---------------------------------------------------------------------------
// Rendering shape and clause order
// ---------------------------------------------------------------------------

#[test]
fn a_threshold_is_pending_then_reached_with_its_element() {
    let o = open();
    let s = state_of(DEMO, std::slice::from_ref(&o));
    for t in THRESHOLDS {
        assert_eq!(s[t], json!({"status": "pending"}), "{t}");
    }
    let a1 = demo("approve", "", &o.address, "@a");
    let a2 = demo("approve", "", &o.address, "@b");
    let s = state_of(DEMO, &[o.clone(), a1.clone()]);
    assert_eq!(s["approvals"], 1);
    assert_eq!(s["quorum"], json!({"status": "pending"}));
    let s = state_of(DEMO, &[o.clone(), a1, a2]);
    assert_eq!(s["approvals"], 2);
    assert_eq!(
        s["quorum"],
        json!({"status": "reached", "element": {"count": 2}})
    );

    let tx = demo("tag", " :label \"x\"", &o.address, "@a");
    let ty = demo("tag", " :label \"y\"", &o.address, "@a");
    let s = state_of(DEMO, &[o.clone(), ty.clone()]);
    assert_eq!(s["tagged"], json!({"status": "pending"}));
    let s = state_of(DEMO, &[o.clone(), ty, tx]);
    assert_eq!(
        s["tagged"],
        json!({"status": "reached", "element": {"member": "x"}})
    );

    let m1 = demo("mint", " :amount 6", &o.address, "@m1");
    let m2 = demo("mint", " :amount 6", &o.address, "@m2");
    let b = demo("burn", " :amount 5", &o.address, "@b");
    let s = state_of(DEMO, &[o.clone(), m1.clone(), b.clone()]);
    assert_eq!(s["balance"], 1);
    assert_eq!(s["funded"], json!({"status": "pending"}));
    // Gross credits are explicitly named; the signed balance stays a snapshot.
    let s = state_of(DEMO, &[o.clone(), m1, m2, b]);
    assert_eq!(s["balance"], 7);
    assert_eq!(
        s["funded"],
        json!({"status": "reached", "element": {"sum": 10}})
    );

    let t1 = demo("tick", "", &o.address, "@a");
    let t2 = demo("tick", "", &t1.address, "@b");
    let s = state_of(DEMO, &[o.clone(), t1.clone()]);
    assert_eq!(s["stage"], 1);
    assert_eq!(s["done"], json!({"status": "pending"}));
    let s = state_of(DEMO, &[o, t1, t2]);
    assert_eq!(s["stage"], 2);
    assert_eq!(
        s["done"],
        json!({"status": "reached", "element": {"progress": 2}})
    );
}

// REQ-3802: shape validation must constrain the same numeric value the fold reads.
#[test]
fn duplicate_amount_cannot_hide_a_negative_state_contribution() {
    // Boundary recognition rejects duplicates; retain R7 defence-in-depth for
    // callers that construct a typed Message directly.
    fn raw_duplicate(params: &str, parent: &str) -> Act {
        fn inject(message: &mut cbcl_core::message::Message, fields: Vec<cbcl_core::sexpr::SExpr>) {
            use cbcl_core::message::Message;
            match message {
                Message::Simple { params, .. } => {
                    params.splice(0..2, fields);
                }
                Message::Dialect { inner, .. } => inject(inner, fields),
                Message::Wrapped { content, .. } => inject(content, fields),
                _ => panic!("expected simple"),
            }
        }
        let mut message = demo("mint", " :amount 0", parent, "@a").message;
        let cbcl_core::sexpr::SExpr::List(fields) = parse(&format!("({params})")).unwrap() else {
            panic!()
        };
        inject(&mut message, fields);
        Act::from_message(message, "@a").unwrap()
    }
    assert!(parse_message(&parse("(lang demo (mint () :amount 10 :amount -1))").unwrap()).is_err());
    let d = parse_dialect(&parse(DEMO).unwrap()).unwrap();
    let o = open();
    let candidate = raw_duplicate(" :amount 10 :amount -1", &o.address);
    assert_eq!(candidate.fields["amount"].to_string(), "-1");
    let positive = demo("mint", " :amount 10", &o.address, "@b");
    assert!(matches!(
        state_exports::admit(
            &d,
            &cbcl_core::store::ThreadId("t".into()),
            std::slice::from_ref(&o),
            &positive
        ),
        Admission::Accepted
    ));
    let before = state_of(DEMO, &[o.clone(), positive.clone()]);
    let after = state_of(DEMO, &[o.clone(), positive.clone(), candidate.clone()]);
    assert_eq!(before["funded"]["status"], "reached");
    assert_eq!(after["funded"]["status"], "pending");
    let verdict = state_exports::admit(
        &d,
        &cbcl_core::store::ThreadId("t".into()),
        &[o.clone(), positive],
        &candidate,
    );
    assert!(
        matches!(verdict, Admission::Rejected(_)),
        "ambiguous amount admitted: {verdict:?}"
    );
    for params in [
        " :amount 10 :amount 10",
        " :amount 0 :amount 1",
        " :amount -1 :amount 10",
    ] {
        let duplicate = raw_duplicate(params, &o.address);
        let error = cbcl_core::r7::verify_state_shape(&d, &duplicate.message).unwrap_err();
        assert!(error.to_string().contains("duplicate state keyword"));
    }
}

/// REQ-3802 / ADR-3805: nonnegative amounts are recognized before admission;
/// signed net balances retain their snapshot meaning.
#[test]
fn negative_credits_are_rejected_and_signed_balances_remain_snapshots() {
    assert_eq!(install(DEMO), Ok(()));
    let o = open();
    let positive = demo("mint", " :amount 10", &o.address, "@a");
    let negative = demo("mint", " :amount -1", &o.address, "@b");
    let before = state_of(DEMO, &[o.clone(), positive.clone()]);
    assert_eq!(before["funded"]["status"], "reached");
    let d = parse_dialect(&parse(DEMO).unwrap()).unwrap();
    assert!(matches!(
        state_exports::admit(
            &d,
            &cbcl_core::store::ThreadId("t".into()),
            &[o.clone(), positive.clone()],
            &negative
        ),
        Admission::Rejected(_)
    ));
    let signed = DEMO
        .replace("(require :amount nonnegative)", "(require :amount integer)")
        .replace("(threshold funded credits (sum 10))", "");
    assert_eq!(install(&signed), Ok(()));
    assert_eq!(
        state_of(&signed, &[o.clone(), positive.clone()])["balance"],
        10
    );
    assert_eq!(state_of(&signed, &[o, positive, negative])["balance"], 9);
    assert!(install(&DEMO.replace("funded credits", "funded balance"))
        .unwrap_err()
        .contains("snapshot"));
    assert!(install(&DEMO.replace("nonnegative", "number"))
        .unwrap_err()
        .contains("nonnegative"));
}

#[test]
fn a_threshold_renders_as_a_field_named_name_in_clause_order() {
    let d = parse_dialect(&parse(DEMO).unwrap()).unwrap();
    let folded = fold(d.state.as_ref().unwrap(), d.causal_protocol.as_ref(), &[]);
    let names: Vec<&str> = folded.iter().map(|(n, _)| n.as_str()).collect();
    assert_eq!(
        names,
        [
            "approvals",
            "quorum",
            "tags",
            "tagged",
            "balance",
            "credits",
            "funded",
            "stage",
            "done"
        ]
    );
    // Existing fields render exactly as before: a threshold adds a member
    // and changes nothing else (REQ-3807).
    let text = render_json(&folded);
    assert!(text.starts_with("{\"approvals\":0,\"quorum\":{\"status\":\"pending\"},\"tags\":[]"));
}

#[test]
fn the_schema_types_a_threshold_by_its_field_and_elements() {
    let d = parse_dialect(&parse(DEMO).unwrap()).unwrap();
    let schema: Value = serde_json::from_str(&render_schema(&state_schema(
        d.state.as_ref().unwrap(),
        &d.shapes,
    )))
    .unwrap();
    assert_eq!(
        schema["approvals"],
        json!({"type": "int", "observation": "snapshot"})
    );
    assert_eq!(
        schema["quorum"],
        json!({"type": "threshold", "field": "approvals", "elements": [{"count": 2}]})
    );
    assert_eq!(
        schema["tagged"],
        json!({"type": "threshold", "field": "tags", "elements": [{"member": "x"}]})
    );
    assert_eq!(
        schema["funded"],
        json!({"type": "threshold", "field": "credits", "elements": [{"sum": 10}]})
    );
    assert_eq!(
        schema["done"],
        json!({"type": "threshold", "field": "stage", "elements": [{"progress": 2}]})
    );
    let keys: Vec<&String> = schema.as_object().unwrap().keys().collect();
    assert_eq!(keys.len(), 9);
}

/// Initial conflicts are automatic faults; a bare `#t` reads the bool carrier.
#[test]
fn fault_and_scalar_elements_read_the_top_and_the_bool_carrier() {
    const FORK: &str = "(define opener-fork (cbcl) @anuna \
      (extend open (to title) (tell to :title title)) \
      (extend close (to) (tell to)) \
      (shape open (require :title string)) \
      (protocol (then begin open) (then open close)) \
      (state (title (initial open :title)) \
             (closed (exists close)) (threshold shut closed #t)))";
    let a = act(
        "(lang opener-fork (open @room :title \"Alpha\" :caused-by begin :thread \"t\" :from @a))",
        "@a",
    );
    let b = act(
        "(lang opener-fork (open @room :title \"Beta\" :caused-by begin :thread \"t\" :from @b))",
        "@b",
    );
    let c = act(
        &format!(
            "(lang opener-fork (close @room :caused-by {} :thread \"t\" :from @a))",
            a.address
        ),
        "@a",
    );
    let s = state_of(FORK, std::slice::from_ref(&a));
    assert_eq!(s["title"], "Alpha");
    assert_eq!(s["shut"], json!({"status": "pending"}));
    let s = state_of(FORK, &[a.clone(), b.clone(), c.clone()]);
    assert_eq!(s["title"]["status"], "fault");
    assert_eq!(s["shut"], json!({"status": "reached", "element": true}));
    let s = state_of(FORK, &[b, a, c]);
    assert_eq!(s["title"]["status"], "fault");
}

#[test]
fn initializer_conflict_faults_progress_and_its_reached_threshold() {
    let source = "(define closure-fork (cbcl) @anuna
      (extend open (to options) (tell to :options options))
      (extend tick (to choice) (tell to :choice choice))
      (shape open (require :options list)) (shape tick (require :choice string))
      (protocol (then begin open) (then open (repeat 3 tick)))
      (state (options (initial open :options)) (domain tick :choice options)
             (stage (progress tick)) (threshold done stage (progress 1))))";
    assert_eq!(install(source), Ok(()));
    let a = act("(lang closure-fork (open @room :options (\"yes\") :caused-by begin :thread \"t\" :from @a))", "@a");
    let b = act("(lang closure-fork (open @room :options (\"no\") :caused-by begin :thread \"t\" :from @b))", "@b");
    let tick = act(
        &format!(
            "(lang closure-fork (tick @room :choice \"yes\" :caused-by {} :thread \"t\" :from @a))",
            a.address
        ),
        "@a",
    );
    let before = state_of(source, &[a.clone(), tick.clone()]);
    assert_eq!(before["stage"], 1);
    assert_eq!(before["done"]["status"], "reached");
    let mut evidence = vec![a.address.clone(), b.address.clone()];
    evidence.sort();
    for acts in [
        vec![a.clone(), tick.clone(), b.clone()],
        vec![b, tick.clone(), a, tick],
    ] {
        let after = state_of(source, &acts);
        for field in ["stage", "done"] {
            assert_eq!(after[field]["status"], "fault", "{field}");
            assert_eq!(after[field]["evidence"], json!(evidence), "{field}");
        }
    }
}

// ---------------------------------------------------------------------------
// TEST-3801: threshold determinism
// ---------------------------------------------------------------------------

/// A delivery: the opener plus approvals, tags, mints, burns and a tick chain.
fn delivery(
    approvers: &[usize],
    tags: &[(usize, usize)],
    mints: &[(usize, i64)],
    burns: &[(usize, i64)],
    ticks: usize,
) -> Vec<Act> {
    let o = open();
    let who = ["@a", "@b", "@c", "@d"];
    let labels = ["\"x\"", "\"y\"", "\"z\""];
    let mut acts = vec![o.clone()];
    for i in approvers {
        acts.push(demo("approve", "", &o.address, who[*i]));
    }
    for (w, l) in tags {
        acts.push(demo(
            "tag",
            &format!(" :label {}", labels[*l]),
            &o.address,
            who[*w],
        ));
    }
    for (w, n) in mints {
        acts.push(demo("mint", &format!(" :amount {n}"), &o.address, who[*w]));
    }
    for (w, n) in burns {
        acts.push(demo("burn", &format!(" :amount {n}"), &o.address, who[*w]));
    }
    let mut pred = o.address.clone();
    for i in 0..ticks {
        let t = demo("tick", "", &pred, who[i % who.len()]);
        pred = t.address.clone();
        acts.push(t);
    }
    acts
}

fn delivery_strategy() -> impl Strategy<Value = Vec<Act>> {
    (
        proptest::collection::btree_set(0usize..4, 0..=4),
        proptest::collection::vec((0usize..4, 0usize..3), 0..=4),
        proptest::collection::vec((0usize..4, 1i64..=6), 0..=4),
        proptest::collection::vec((0usize..4, 1i64..=6), 0..=2),
        0usize..=3,
    )
        .prop_map(|(approvers, tags, mints, burns, ticks)| {
            let approvers: Vec<usize> = approvers.into_iter().collect();
            delivery(&approvers, &tags, &mints, &burns, ticks)
        })
}

/// A permutation of the delivery with some acts delivered again.
fn permuted(delivery: Vec<Act>) -> impl Strategy<Value = Vec<Act>> {
    let n = delivery.len();
    (
        Just(delivery).prop_shuffle(),
        proptest::collection::vec(0usize..n, 0..=n),
    )
        .prop_map(|(mut acts, dups)| {
            for i in dups {
                let a = acts[i].clone();
                acts.push(a);
            }
            acts
        })
}

fn thresholds(s: &Value) -> Vec<(&'static str, Value)> {
    THRESHOLDS.iter().map(|t| (*t, s[*t].clone())).collect()
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(64))]

    /// Every permutation and duplication of a delivery reaches the same
    /// element; across causally closed prefixes an element is reached at most
    /// once and never retracted; and no superset retracts it (REQ-3802).
    #[test]
    fn threshold_reads_are_deterministic_reached_once_and_never_retracted(
        (original, perm) in delivery_strategy().prop_flat_map(|d| (Just(d.clone()), permuted(d)))
    ) {
        let d = parse_dialect(&parse(DEMO).unwrap()).unwrap();
        let clause = d.state.as_ref().unwrap();
        let fold_json = |acts: &[Act]| -> Value {
            serde_json::from_str(&render_json(&fold(clause, d.causal_protocol.as_ref(), acts))).unwrap()
        };
        let want = thresholds(&fold_json(&original));
        prop_assert_eq!(thresholds(&fold_json(&perm)), want.clone(), "permutation and duplication");

        // Across the growth of the accepted set: pending… then reached with
        // one element, never pending or another element again.
        let mut seen: Vec<(&str, Option<Value>)> = THRESHOLDS.iter().map(|t| (*t, None)).collect();
        for end in 0..=perm.len() {
            let s = fold_json(&closed(&perm[..end]));
            for (t, reached) in seen.iter_mut() {
                let now = s[*t].clone();
                prop_assert!(now["status"] == "pending" || now["status"] == "reached", "{t}: {now}");
                match reached {
                    None => {
                        if now["status"] == "reached" {
                            *reached = Some(now);
                        }
                    }
                    Some(before) => prop_assert_eq!(&now, before, "{} retracted or re-reached", t),
                }
            }
        }
        let last = fold_json(&closed(&perm));
        for (t, reached) in &seen {
            prop_assert_eq!(&last[*t], &reached.clone().unwrap_or(json!({"status": "pending"})), "{}", t);
        }

        // Supersets: further valid acts never retract a reached element.
        let o = &original[0];
        let last_tick = original.iter().rfind(|a| a.verb == "tick").map(|a| a.address.clone()).unwrap_or(o.address.clone());
        let more = vec![
            demo("approve", "", &o.address, "@e"),
            demo("tag", " :label \"x\"", &o.address, "@e"),
            demo("mint", " :amount 100", &o.address, "@e"),
            demo("burn", " :amount 100", &o.address, "@e"),
            demo("tick", "", &last_tick, "@e"),
        ];
        let mut grown = original.clone();
        for extra in more {
            grown.push(extra);
            let s = fold_json(&grown);
            for (t, element) in &want {
                if element["status"] == "reached" {
                    prop_assert_eq!(&s[*t], element, "{} retracted on a superset", t);
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// TEST-3803: install rejects compatible thresholds and mistyped elements
// ---------------------------------------------------------------------------

/// A coin dialect whose `coins` is a nonnegative numeric events stream
/// and whose `flag` is an `exists` (carrier `bool`).
fn coin(thresholds: &str) -> String {
    format!(
        "(define coin (cbcl) @anuna \
          (extend open (to) (tell to)) \
          (extend mint (to amount) (tell to :amount amount)) \
          (extend burn (to amount) (tell to :amount amount)) \
          (extend tag (to label) (tell to :label label)) \
          (extend close (to) (tell to)) \
          (shape mint (require :amount nonnegative)) \
          (shape burn (require :amount integer)) \
          (shape tag (require :label string)) \
          (protocol (then begin open) (then open mint) (then open burn) (then open tag) (then open close)) \
          (state (coins (events mint :amount)) (balance (counter mint burn :amount)) (flag (exists close)) \
                 (labels (set-union tag :label)) (picked (values tag :label)) {thresholds}))"
    )
}

#[test]
fn install_rejects_a_compatible_pair_and_accepts_an_incompatible_one() {
    let e = install(&coin("(threshold t coins (sum 10) (sum 20))")).unwrap_err();
    assert!(
        e.contains("threshold t")
            && e.contains("(sum 10)")
            && e.contains("(sum 20)")
            && e.contains("compatible"),
        "{e}"
    );
    for declaration in [
        "(threshold t coins (sum 10) fault)",
        "(threshold t coins fault (sum 10))",
        "(threshold t flag #t fault)",
        "(threshold t coins fault)",
    ] {
        assert!(install(&coin(declaration))
            .unwrap_err()
            .contains("terminal outcome"));
    }
    assert_eq!(install(&coin("(threshold t coins (sum 10))")), Ok(()));
    let e = install(&coin("(threshold t coins (member 1) (sum 10))")).unwrap_err();
    assert!(e.contains("compatible"), "{e}");
}

#[test]
fn install_rejects_a_duplicate_element() {
    let e = install(&coin("(threshold t flag #t #t)")).unwrap_err();
    assert!(e.contains("threshold t") && e.contains("duplicate"), "{e}");
    let e = install(&coin("(threshold t coins fault fault)")).unwrap_err();
    assert!(e.contains("terminal outcome"), "{e}");
    let e = install(&coin("(threshold t labels (member \"a\") (member \"a\"))")).unwrap_err();
    assert!(e.contains("duplicate"), "{e}");
    // Two members are compatible: the set {a, b} lies above both.
    let e = install(&coin("(threshold t labels (member \"a\") (member \"b\"))")).unwrap_err();
    assert!(
        e.contains("(member \"a\")") && e.contains("(member \"b\")") && e.contains("compatible"),
        "{e}"
    );
}

#[test]
fn install_rejects_an_element_the_carrier_does_not_admit() {
    // `count n` against the `vals` carrier of set-union.
    let e = install(&coin("(threshold t labels (count 2))")).unwrap_err();
    assert!(e.contains("(count 2)") && e.contains("vals"), "{e}");
    // …and against the superseding carrier of `values`.
    let e = install(&coin("(threshold t picked (count 2))")).unwrap_err();
    assert!(e.contains("(count 2)"), "{e}");
    // `sum n` against bool; a bare scalar against amounts; progress against
    // a lift; `#f` is ⊥, not an element.
    assert!(install(&coin("(threshold t flag (sum 1))"))
        .unwrap_err()
        .contains("snapshot"));
    assert!(install(&coin("(threshold t coins #t)"))
        .unwrap_err()
        .contains("#t"));
    assert!(install(&coin("(threshold t coins (progress 1))"))
        .unwrap_err()
        .contains("(progress 1)"));
    assert!(install(&coin("(threshold t flag #f)")).is_err());
    // CON-3801 types against the carrier, not the writer's shape. A
    // scalar member is well typed even if this dialect never contributes it.
    assert_eq!(install(&coin("(threshold t labels (member 7))")), Ok(()));
}

#[test]
fn install_rejects_an_undeclared_field_a_threshold_before_its_field_and_a_clashing_name() {
    let e = install(&coin("(threshold t nothing (sum 1))")).unwrap_err();
    assert!(e.contains("threshold t") && e.contains("nothing"), "{e}");
    let src = coin("").replace(
        "(state (coins",
        "(state (threshold early coins (sum 1)) (coins",
    );
    let e = install(&src).unwrap_err();
    assert!(e.contains("early") && e.contains("coins"), "{e}");
    let e = install(&coin("(threshold coins coins (sum 1))")).unwrap_err();
    assert!(e.contains("coins"), "{e}");
    let e = install(&coin("(threshold t coins (sum 1)) (threshold t flag #t)")).unwrap_err();
    assert!(e.contains("duplicate") && e.contains("'t'"), "{e}");
}

#[test]
fn the_parser_rejects_malformed_threshold_entries() {
    assert!(install(&coin("(threshold t coins)")).is_err());
    assert!(install(&coin("(threshold Bad coins (sum 1))")).is_err());
    assert!(install(&coin("(threshold t coins (count))")).is_err());
    assert!(install(&coin("(threshold t coins (sum \"x\"))")).is_err());
    assert!(install(&coin("(threshold t coins (unknown 1))")).is_err());
    assert!(install(&coin("(threshold t coins notfault)")).is_err());
}

/// NFR-3800: the pairwise check is `O(k²)` comparisons. The shipped successful
/// threshold sources admit mutually compatible alternatives, so no dialect
/// can install `k = 64` incompatible elements before finite lattice support. The
/// bound is therefore asserted on the comparison count itself: the pairwise
/// walk over `k` elements that all compare incompatible makes exactly
/// `k(k-1)/2` comparisons and accepts.
#[test]
fn the_pairwise_check_makes_k_choose_2_comparisons() {
    let k = 64;
    let elements: Vec<Element> = (1..=k).map(|n| Element::Sum(n as i64)).collect();
    let mut comparisons = 0usize;
    let verdict = pairwise(&elements, |_, _| {
        comparisons += 1;
        None
    });
    assert_eq!(verdict, Ok(()));
    assert_eq!(comparisons, k * (k - 1) / 2);
    // On a chain the first compatible pair ends the walk.
    let mut comparisons = 0usize;
    let verdict = pairwise(&elements, |a, b| {
        comparisons += 1;
        cbcl_core::lattice::relation(a, b)
    });
    assert_eq!(verdict, Err((0, 1, "compatible")));
    assert_eq!(comparisons, 1);
    // And through the installer: a 64-element chain is rejected naming the
    // first pair.
    let chain: String = (1..=k).map(|n| format!(" (sum {n})")).collect();
    let e = install(&coin(&format!("(threshold t coins{chain})"))).unwrap_err();
    assert!(e.contains("(sum 1)") && e.contains("(sum 2)"), "{e}");
}

#[test]
fn elements_render_round_trip_the_wire_form() {
    let cases: Vec<(Element, &str, &str)> = vec![
        (Element::Count(2), "(count 2)", "{\"count\":2}"),
        (
            Element::Member(V::Str("x".into())),
            "(member \"x\")",
            "{\"member\":\"x\"}",
        ),
        (Element::Sum(10), "(sum 10)", "{\"sum\":10}"),
        (Element::Progress(3), "(progress 3)", "{\"progress\":3}"),
        (Element::Scalar(V::Bool(true)), "#t", "true"),
    ];
    for (e, wire, json) in cases {
        assert_eq!(e.wire(), wire);
        assert_eq!(e.render().render(), json);
    }
}

// TEST-3810/3812: authored conditions use fixed-bound source reads; they do
// not turn compatible bounds into competing alternatives or count a leaf twice.
fn condition_source(condition: &str) -> String {
    DEMO.replace(
        "(threshold quorum approvals (count 2))",
        &format!("(seen (exists approve)) (threshold quorum {condition})"),
    )
}

#[test]
fn authored_condition_conjunction_reaches_boolean_after_every_leaf() {
    let source = condition_source(
        "(and (read approvals (count 2)) (and (read seen #t) (read approvals (count 3)) (read approvals (count 2))))",
    );
    assert_eq!(install(&source), Ok(()));
    let opener = open();
    let mut history = vec![opener.clone()];
    for index in 0..3 {
        assert_eq!(
            state_of(&source, &history)["quorum"],
            json!({"status":"pending"})
        );
        history.push(demo(
            "approve",
            "",
            &opener.address,
            &format!("@reviewer{index}"),
        ));
    }
    let expected = json!({"status":"reached","element":true});
    assert_eq!(state_of(&source, &history)["quorum"], expected);
    history.reverse();
    history.extend(history.clone());
    assert_eq!(state_of(&source, &history)["quorum"], expected);
    // The direct syntax retains its scalar/count result.
    assert_eq!(
        state_of(DEMO, &history)["quorum"],
        json!({"status":"reached","element":{"count":2}})
    );
}

#[test]
fn authored_condition_single_read_returns_boolean() {
    let source = condition_source("(read approvals (count 2))");
    assert_eq!(install(&source), Ok(()));
    let opener = open();
    let history = vec![
        opener.clone(),
        demo("approve", "", &opener.address, "@a"),
        demo("approve", "", &opener.address, "@b"),
    ];
    assert_eq!(
        state_of(&source, &history)["quorum"],
        json!({"status":"reached","element":true})
    );
}

#[test]
fn authored_condition_rejects_unrecognized_or_ineligible_sources() {
    let late_condition = |condition: &str| {
        DEMO.replace(
            "(threshold done stage (progress 2))",
            &format!("(threshold done {condition})"),
        )
    };
    let signed = late_condition("(read balance (sum 1))");
    assert!(install(&signed).is_err());
    let negative_events = late_condition("(read credits (sum 1))").replace(
        "(shape mint (require :amount nonnegative))",
        "(shape mint (require :amount integer))",
    );
    let error = install(&negative_events).unwrap_err();
    assert!(error.contains("nonnegative"), "{error}");
    let bounded_string = late_condition("(read tags (member \"long\"))").replacen(
        "(cbcl) @anuna",
        "(cbcl) @anuna (:state-bounds (max-string 3))",
        1,
    );
    let error = install(&bounded_string).unwrap_err();
    assert!(error.contains("scalar bounds"), "{error}");
    for malformed in [
        "(and)",
        "(and (read approvals (count 1)))",
        "(or (read approvals (count 1)) (read approvals (count 2)))",
        "(read approvals)",
        "(read approvals (count 1) extra)",
    ] {
        assert!(
            parse_dialect(&parse(&condition_source(malformed)).unwrap()).is_err(),
            "recognition: {malformed}"
        );
    }
    for condition in [
        "(and)",
        "(and (read approvals (count 1)))",
        "(or (read approvals (count 1)) (read approvals (count 2)))",
        "(read approvals)",
        "(read approvals (count 1) extra)",
        "(read missing (count 1))",
        "(read tags (member \"x\"))",
        "(read approvals #t)",
        "(read quorum #t)",
        "(read balance (sum 1))",
        "(>= approvals stage)",
        "(read approvals (count stage))",
    ] {
        assert!(
            install(&condition_source(condition)).is_err(),
            "{condition}"
        );
    }
    let condition = "(and (read approvals (count 1)) (read seen #t))";
    let source = condition_source(condition);
    assert_eq!(install(&source), Ok(()));
    let bounded = |options: &str, source: &str| {
        source.replacen(
            "(cbcl) @anuna",
            &format!("(cbcl) @anuna (:state-bounds {options})"),
            1,
        )
    };
    assert!(install(&bounded("(max-list 2)", &source)).is_err());
    assert_eq!(install(&bounded("(max-list 3)", &source)), Ok(()));
    assert!(install(&bounded("(max-fields 9)", &source)).is_err());
    assert_eq!(install(&bounded("(max-fields 10)", &source)), Ok(()));
    assert!(install(&bounded(
        "(max-number 1)",
        &condition_source("(read approvals (count 2))")
    ))
    .is_err());
    assert!(
        install(&source.replace("(read approvals (count 1))", "(read credits (sum 1))")).is_err()
    );
}

#[test]
fn authored_condition_schema_and_canonical_round_trip() {
    let source = condition_source("(and (read approvals (count 2)) (read seen #t))");
    let registry = parse_and_install_dialect(&parse(&source).unwrap()).unwrap();
    let d = registry.iter().last().unwrap();
    let schema: Value = serde_json::from_str(&render_schema(&state_schema(
        d.state.as_ref().unwrap(),
        &d.shapes,
    )))
    .unwrap();
    assert_eq!(
        schema["quorum"],
        json!({"type":"threshold","of":"bool","condition":{"op":"and","conditions":[{"op":"read","field":"approvals","element":{"count":2}},{"op":"read","field":"seen","element":true}]}})
    );
    let condition = d
        .state
        .as_ref()
        .unwrap()
        .entries
        .iter()
        .find_map(|entry| match entry {
            cbcl_core::state::Entry::Condition { condition, .. } => Some(condition),
            _ => None,
        })
        .unwrap();
    let round_source = condition_source(&condition.to_sexpr().to_string());
    let registry = parse_and_install_dialect(&parse(&round_source).unwrap()).unwrap();
    let round = registry.iter().last().unwrap();
    assert_eq!(
        cbcl_core::canonical::dialect_name(d),
        cbcl_core::canonical::dialect_name(round)
    );
    let different =
        parse_dialect(&parse(&source.replace("(count 2)", "(count 3)")).unwrap()).unwrap();
    assert_ne!(
        cbcl_core::canonical::dialect_name(d),
        cbcl_core::canonical::dialect_name(&different)
    );
    let described = cbcl_parser::describe::describe(d, &source);
    assert_eq!(
        described["thresholds"][0]["condition"],
        schema["quorum"]["condition"]
    );
}

#[test]
fn authored_condition_faults_dominate_pending_and_union_every_leaf() {
    let source = "(define products (cbcl) @anuna
      (extend open (to) (tell to)) (extend vote (to) (tell to))
      (extend alpha (to flag) (tell to :flag flag)) (extend beta (to flag) (tell to :flag flag))
      (shape alpha (require :flag bool)) (shape beta (require :flag bool))
      (protocol (then begin open) (then open vote) (then open alpha) (then open beta))
      (state (lattice checks (elements idle invalid) (bottom idle) (top invalid)
        (join (idle idle idle) (idle invalid invalid) (invalid idle invalid) (invalid invalid invalid)))
        (votes (count vote))
        (left (lift alpha (into checks) (contribute (:flag #t invalid))))
        (right (lift beta (into checks) (contribute (:flag #t invalid))))
        (threshold ready (and (read votes (count 10)) (read left \"idle\") (read right \"idle\")))))";
    assert_eq!(install(source), Ok(()));
    let opener = act(
        "(lang products (open @room :caused-by begin :thread \"t\" :from @a))",
        "@a",
    );
    let write = |verb: &str, signer: &str| {
        act(&format!("(lang products ({verb} @room :flag #t :caused-by {} :thread \"t\" :from {signer}))",opener.address),signer)
    };
    let left = write("alpha", "@a");
    let right = write("beta", "@b");
    let extra = write("alpha", "@c");
    let mut history = vec![opener.clone(), left.clone(), right.clone()];
    for evidence in [
        vec![left.address.clone(), right.address.clone()],
        vec![
            left.address.clone(),
            right.address.clone(),
            extra.address.clone(),
        ],
    ] {
        let mut evidence = evidence;
        evidence.sort();
        let result = state_of(source, &history);
        assert_eq!(result["votes"], 0);
        assert_eq!(result["ready"]["status"], "fault");
        assert_eq!(result["ready"]["evidence"], json!(evidence));
        history.push(extra.clone());
        history.reverse();
    }
}

#[test]
fn authored_condition_uses_each_sources_freeze_scope_and_full_history_faults() {
    let source = "(define scopes (cbcl) @anuna (:roles (owner))
      (extend open (to) :from owner :to owner (tell to))
      (extend alpha (to) :from owner :to owner (tell to))
      (extend beta (to) :from owner :to owner (tell to))
      (extend seal-alpha (to) :from owner :to owner (tell to))
      (extend seal-beta (to) :from owner :to owner (tell to))
      (protocol (then begin open) (then open alpha) (then alpha seal-alpha) (then seal-alpha beta) (then beta seal-beta))
      (state (first (count alpha)) (second (count beta))
        (threshold ready (and (read first (count 1)) (read second (count 1))))
        (freeze first seal-alpha fault) (freeze second seal-beta fault)))";
    assert_eq!(install(source), Ok(()));
    let root = act(
        "(with-roles ((owner @owner)) (signed @owner (hello :thread \"t\" :caused-by begin)))",
        "@owner",
    );
    let next = |verb: &str, pred: &Act| {
        act(&format!("(signed @owner (lang scopes ({verb} @owner :from @owner :thread \"t\" :caused-by {})))",pred.address), "@owner")
    };
    let opener = next("open", &root);
    let alpha = next("alpha", &opener);
    let seal_alpha = next("seal-alpha", &alpha);
    let beta = next("beta", &seal_alpha);
    let seal_beta = next("seal-beta", &beta);
    let mut history = vec![
        root,
        opener.clone(),
        alpha,
        seal_alpha.clone(),
        beta,
        seal_beta.clone(),
    ];
    let d = parse_dialect(&parse(source).unwrap()).unwrap();
    for index in 0..history.len() {
        assert!(matches!(
            state_exports::admit(
                &d,
                &cbcl_core::store::ThreadId("t".into()),
                &history[..index],
                &history[index]
            ),
            Admission::Accepted
        ));
    }
    let state = state_of(source, &history);
    assert_eq!(state["first"]["frozen"], seal_alpha.address);
    assert_eq!(state["second"]["frozen"], seal_beta.address);
    assert_eq!(state["ready"], json!({"status":"reached","element":true}));
    history.reverse();
    history.extend(history.clone());
    assert_eq!(state_of(source, &history), state);
    let late = act(&format!("(signed @owner (lang scopes (alpha @owner (second) :from @owner :thread \"t\" :caused-by {})))", opener.address), "@owner");
    assert!(matches!(
        state_exports::admit(&d, &cbcl_core::store::ThreadId("t".into()), &history, &late),
        Admission::Accepted
    ));
    history.push(late.clone());
    let mut evidence = vec![seal_alpha.address.clone(), late.address];
    evidence.sort();
    let fault = state_of(source, &history);
    assert_eq!(fault["ready"]["status"], "fault");
    assert_eq!(fault["ready"]["evidence"], json!(evidence));
    let forbidden = source.replace(
        "(freeze first seal-alpha fault)",
        "(freeze first seal-alpha supersede)",
    );
    assert!(install(&forbidden).is_err());
    let earlier = forbidden
        .replace("(freeze first seal-alpha supersede)", "")
        .replace("(state ", "(state (freeze first seal-alpha supersede) ");
    assert!(install(&earlier).is_err());
    assert!(install(&source.replace("freeze first", "freeze ready")).is_err());
}