deduxit 0.5.0

A collection of logic suites: decides, checks, proves step by step and exports sequents of linear logic and of classical, intuitionistic and minimal propositional logic, with checked proofs, Kripke countermodels and Rocq certificates.
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
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! What takes a sequent with a quantifier and what refuses it: the
//! focused engine in the classical modes and the two-sided one in the
//! intuitionistic modes prove and refute it, every other engine refuses
//! it by its fragment, as interactive proving, the
//! proof structures and the propositional refutations' checks do by name.
//! A ground first-order sequent is propositional and refused by none.
#![cfg(all(feature = "parse", feature = "serialize", feature = "interactive"))]

use deduxit::linear::proofs::Fault;
use deduxit::linear::proofs::interactive::{GoalId, Needs, StepError, TermNode, Witness};
use deduxit::linear::search::Engine;
use deduxit::{
    Error, Limits,
    linear::{
        CheckError, Criterion, CutFormula, Disproof, Eigen, Forest, InputOptions, Interactive,
        Member, Mode, Options, Proof, ProofStructure, Rule, Sequent, Step, Verdict,
    },
};

/// The focused engine decides a quantified goal in the classical modes,
/// Mix included, and the two-sided engine in the intuitionistic modes, by
/// the dispatch and forced; every other engine refuses it; the ordered
/// modes refuse it by the fragment.
#[test]
fn the_focused_engine_takes_a_quantified_goal_and_no_other() {
    let sequent: Sequent = "forall x. p(x) |- p(a)".parse().unwrap();
    assert_eq!(sequent.fragment().to_string(), "MLL1");
    for mode in [
        Mode::CLASSICAL,
        Mode::INTUITIONISTIC,
        Mode::CLASSICAL.with_mix(),
        Mode::INTUITIONISTIC.with_affine(),
    ] {
        let focused = if mode.is_intuitionistic() {
            Engine::TwoSided
        } else {
            Engine::Focus
        };
        let outcome = deduxit::linear::prove(&sequent, mode, &Options::default()).unwrap();
        assert!(matches!(outcome.verdict, Verdict::Proved(_)), "{mode}");
        assert_eq!(outcome.engine, focused);
        for &engine in Engine::ALL {
            let options = Options::default().with_engine(Some(engine));
            match deduxit::linear::prove(&sequent, mode, &options) {
                Ok(outcome) if engine == focused => {
                    assert!(matches!(outcome.verdict, Verdict::Proved(_)), "{mode}");
                }
                Err(Error::EngineRefused { .. }) => {}
                other => panic!("{engine} in {mode}: {other:?}"),
            }
        }
    }
    let cyclic = Sequent::parse_ordered(
        "forall x. p(x) |- p(a)",
        deduxit::linear::Order::Cyclic,
        &Limits::default(),
    )
    .unwrap();
    let error = deduxit::linear::prove(&cyclic, Mode::CYCLIC, &Options::default()).unwrap_err();
    assert!(matches!(error, Error::OrderedFragment { .. }), "{error}");
    // A ground sequent is propositional and proved.
    let ground: Sequent = "p(a), p(a) -o q(f(a)) |- q(f(a))".parse().unwrap();
    let outcome =
        deduxit::linear::prove(&ground, Mode::INTUITIONISTIC, &Options::default()).unwrap();
    assert!(matches!(outcome.verdict, Verdict::Proved(_)));
    assert_eq!(outcome.fragment.to_string(), "MLL");
}

/// The proof structures and the refutations' checks refuse a sequent
/// with a quantifier by name; the checker gives a verdict, here on an
/// axiom that names an open atom without its instance.
#[test]
fn the_views_refuse_a_quantified_sequent_and_the_checker_judges_it() {
    let sequent: Sequent = "forall x. p(x) |- p(a)".parse().unwrap();
    let json = format!(
        r#"{{"version":7,"sequent":{},"nodes":[{{"ax":[1,2]}}],"mode":"classical"}}"#,
        serde_json::to_string(&sequent).unwrap()
    );
    let proof: Proof = serde_json::from_str(&json).unwrap();
    let Err(CheckError::Invalid(invalid)) = proof.check(Mode::CLASSICAL) else {
        panic!("an open atom named bare is no instance");
    };
    assert!(
        matches!(invalid.fault, Fault::Instance { member, .. } if member == Member::new(1)),
        "{invalid:?}"
    );
    let forest = Forest::new(&sequent).unwrap();
    let error = ProofStructure::new(forest, Criterion::default()).unwrap_err();
    assert!(matches!(error, Error::Net(_)), "{error}");
    let json = format!(
        r#"{{"version":7,"sequent":{},"mode":"classical","refutation":{{"kind":"exhausted"}}}}"#,
        serde_json::to_string(&sequent).unwrap()
    );
    let disproof: Disproof = serde_json::from_str(&json).unwrap();
    let error = disproof.check().unwrap_err();
    assert!(matches!(error, Error::Refutation(_)), "{error}");
}

/// A session read from JSON names an occurrence under a quantifier only
/// by its instance; a cut formula with a quantifier makes a session one
/// with quantifiers until its undo, and a cut in such a session on a
/// symbol its sequent lacks is refused; and a cut on a ground atom joins
/// the formula's symbols, so that the session writes and reads back.
#[test]
fn a_session_refuses_a_quantifier_on_every_path() {
    let sequent: Sequent = "forall x. p(x) |- p(a)".parse().unwrap();
    let json = format!(
        r#"{{"version":7,"sequent":{},"mode":"classical","inferences":[{{"sequent":[0,2],"rule":"∃","principal":0,"premises":[1]}},{{"sequent":[1,2]}}],"history":[0]}}"#,
        serde_json::to_string(&sequent).unwrap()
    );
    let error = serde_json::from_str::<Interactive>(&json).unwrap_err();
    assert!(error.to_string().contains("instance"), "{error}");
    let limits = Limits::default();
    let input = InputOptions::default();
    let mut session = Interactive::new(&"a |- a".parse().unwrap(), Mode::CLASSICAL).unwrap();
    let goal = session.goals().next().unwrap();
    let formula =
        CutFormula::parse_within("forall x. p(x)", Mode::CLASSICAL, &input, &limits).unwrap();
    let before = serde_json::to_string(&session).unwrap();
    session.cut(goal, &formula, &[], &limits).unwrap();
    let json = serde_json::to_string(&session).unwrap();
    assert!(json.contains(r#""instances":"#), "{json}");
    let back: Interactive = serde_json::from_str(&json).unwrap();
    assert_eq!(serde_json::to_string(&back).unwrap(), json);
    assert_eq!(session.undo(), Some(goal));
    assert_eq!(serde_json::to_string(&session).unwrap(), before);
    let mut quantified = Interactive::new(&sequent, Mode::CLASSICAL).unwrap();
    let root = quantified.goals().next().unwrap();
    let ground = CutFormula::parse_within("q(b)", Mode::CLASSICAL, &input, &limits).unwrap();
    let error = quantified.cut(root, &ground, &[], &limits).unwrap_err();
    assert!(
        matches!(&error, Error::Step(StepError::CutSymbol { name, .. }) if name == "b"),
        "{error}"
    );
    let formula = CutFormula::parse_within("p(b)", Mode::CLASSICAL, &input, &limits).unwrap();
    session.cut(goal, &formula, &[], &limits).unwrap();
    let json = serde_json::to_string(&session).unwrap();
    assert!(json.starts_with(r#"{"version":7,"#), "{json}");
    let back: Interactive = serde_json::from_str(&json).unwrap();
    assert_eq!(serde_json::to_string(&back).unwrap(), json);
}

/// Two sequents added keep their atoms paired and their symbols in their
/// roles: a nullary atom of a propositional side is the predicate of
/// that name, not a function symbol.
#[test]
fn adding_sequents_joins_their_tables() {
    let mut s: Sequent = "|- q, p(a)".parse().unwrap();
    s.add("|- ~q, p(f(a))".parse().unwrap());
    assert_eq!(s.to_string(), "⊢ q, p(a), ~q, p(f(a))");
    assert_eq!(s.atom_names(), ["q", "p(a)", "p(f(a))"]);
    let json = serde_json::to_string(&s).unwrap();
    assert_eq!(serde_json::from_str::<Sequent>(&json).unwrap(), s);
    let mut t: Sequent = "|- ~q".parse().unwrap();
    t.add("|- q, p(a)".parse().unwrap());
    assert_eq!(t.atom_names(), ["q", "p(a)"]);
    // A cyclic net of a ground sequent is a level-7 document.
    let cyclic = Sequent::parse_ordered(
        "p(a) |- p(a)",
        deduxit::linear::Order::Cyclic,
        &Limits::default(),
    )
    .unwrap();
    let outcome = deduxit::linear::prove(&cyclic, Mode::CYCLIC, &Options::default()).unwrap();
    let net = outcome.net.expect("a net");
    assert!(
        serde_json::to_string(&net)
            .unwrap()
            .starts_with(r#"{"version":7,"#)
    );
}

/// The proofs written by hand under `tests/first-order/`, read through
/// the wire: those the library's own tests accept are proofs in the mode
/// they record, and the others are no proofs, with a fault whose message
/// names formulas and instances.
#[test]
fn the_written_proofs_read_back_and_are_judged() {
    let accepted = [
        "apart",
        "cut",
        "cut_deep",
        "cut_deep_ill",
        "cut_ill",
        "cut_instance",
        "cut_shared",
        "cut_shared_ill",
        "cut_tensor",
        "cut_tensor_ill",
        "swap",
        "swap_ill",
        "unintroduced",
        "witness",
        "witness_ill",
    ];
    let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/first-order");
    let mut read = 0;
    for entry in std::fs::read_dir(dir).unwrap() {
        let path = entry.unwrap().path();
        let name = path.file_stem().unwrap().to_str().unwrap().to_owned();
        let json = std::fs::read_to_string(&path).unwrap();
        let proof: Proof = serde_json::from_str(&json).unwrap();
        let mode = proof.mode().unwrap_or(Mode::CLASSICAL);
        let mode = if name.starts_with("apart") || name.starts_with("shared") {
            mode.with_affine()
        } else {
            mode
        };
        let result = proof.check(mode);
        if accepted.contains(&name.as_str()) {
            assert_eq!(result, Ok(()), "{name}");
        } else {
            let error = result.expect_err(&name);
            assert!(matches!(error, CheckError::Invalid(_)), "{name}: {error}");
            let message = error.describe(&proof).to_string();
            assert!(message.starts_with("node "), "{name}: {message}");
        }
        read += 1;
    }
    assert_eq!(read, 22);
    // The eigenvariable a `∃` step below its `∀` step names, by name.
    let json = std::fs::read_to_string(
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/first-order/swap_back.json"),
    )
    .unwrap();
    let proof: Proof = serde_json::from_str(&json).unwrap();
    let error = proof.check(Mode::CLASSICAL).unwrap_err();
    assert_eq!(
        error.describe(&proof).to_string(),
        "node 4 (∃ on ∃x. (∀y. p(x, y)) from 3) with premises ⊢ ∃y. (∀x. ~p(x, y)), \
         ∀y. p(a, y): eigenvariable a occurs outside the ∀ step that introduces it"
    );
}

/// The proofs with cuts written by hand under `tests/first-order/`, read
/// through the wire, are eliminated in the mode they record (classical
/// where they record none): every step's
/// proof passes the checker and the last is cut-free; among them a cut on
/// a first-order formula (`cut`, `cut_deep`), one on an instance
/// (`cut_instance`, `cut_tensor`), a subproof shared under two cuts on a
/// `∀` formula (`cut_shared`), and an eigenvariable in a witness two rules
/// up its `∀` premise (`cut_deep`). The proof structures refuse them.
#[test]
fn the_written_cuts_are_eliminated() {
    use deduxit::linear::proofs::cut::{self, Case, End};
    let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/first-order");
    let mut cases: Vec<Case> = Vec::new();
    for name in [
        "cut",
        "cut_ill",
        "cut_instance",
        "cut_shared",
        "cut_shared_ill",
        "cut_tensor",
        "cut_tensor_ill",
        "cut_deep",
        "cut_deep_ill",
    ] {
        let json = std::fs::read_to_string(dir.join(format!("{name}.json"))).unwrap();
        let proof: Proof = serde_json::from_str(&json).unwrap();
        assert!(!proof.is_cut_free(), "{name}");
        let mode = proof.mode().unwrap_or(Mode::CLASSICAL);
        let mut taken = 0;
        let elimination = cut::eliminate(
            &proof,
            mode,
            None,
            &cut::Options::default(),
            &Limits::default(),
            |_| false,
            |before, step| {
                assert!(before.check(mode).is_ok(), "{name}: step {taken}");
                cases.push(step.case);
                taken += 1;
            },
        )
        .unwrap();
        assert_eq!(elimination.end, End::CutFree, "{name}");
        assert_eq!(elimination.steps.len(), taken, "{name}");
        assert!(elimination.proof.is_cut_free(), "{name}");
        assert_eq!(elimination.proof.check(mode), Ok(()), "{name}");
        assert_eq!(
            elimination.proof.sequent().to_string(),
            proof.sequent().to_string()
        );
        let net =
            ProofStructure::from_proof(&proof, Criterion::default(), &Limits::default(), |_| false);
        assert!(net.is_err(), "{name}");
    }
    for case in [
        Case::ForallExists,
        Case::TensorPar,
        Case::Axiom,
        Case::Commutative,
    ] {
        assert!(cases.contains(&case), "{case:?} not met");
    }
}

/// The first-order terms a sequent's atoms unfold to are bounded on every
/// reader by `limits.terms`: the text, the sequent's JSON and a proof's
/// instance table, each refused past it with its own code.
#[test]
fn the_term_limit_refuses_at_every_reader() {
    let text = "|- p(f(f(a)))";
    let sequent: Sequent = text.parse().unwrap();
    assert_eq!(sequent.fo_size(), 3);
    let tight = Limits::default().with_terms(Some(2));
    let error = Sequent::parse_within(text, &tight).unwrap_err();
    assert_eq!(error.code(), "too_many_terms", "{error}");
    assert!(Sequent::parse_within(text, &Limits::default().with_terms(Some(3))).is_ok());
    let json = serde_json::to_string(&sequent).unwrap();
    let mut document = serde_json::Deserializer::from_str(&json);
    let error = deduxit::wire::upgrade::<Sequent, _>(&mut document, &tight).unwrap_err();
    assert_eq!(error.code(), "too_many_terms", "{error}");
    // A proof whose sequent is within the bound and whose instance table
    // is not.
    let json = std::fs::read_to_string(
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/first-order/swap.json"),
    )
    .unwrap();
    let proof: Proof = serde_json::from_str(&json).unwrap();
    // Four members, four frames and two terms.
    assert_eq!(proof.instances().unwrap().len(), 4);
    assert_eq!(proof.sequent().fo_size(), 4);
    let limits = Limits::default().with_terms(Some(5));
    let mut document = serde_json::Deserializer::from_str(&json);
    let error = deduxit::wire::upgrade::<Proof, _>(&mut document, &limits).unwrap_err();
    assert_eq!(error.code(), "too_many_terms", "{error}");
    assert_eq!(error.setting(), Some("limits.terms"));
}

/// A cut formula of a document is closed as a root is: one with a loose
/// bound variable is refused when read, not left for the checker, which
/// would look past its instance's frame.
#[test]
fn a_cut_formula_with_a_loose_variable_is_refused() {
    let json = r#"{"version":7,"sequent":{"terms":[{"V":0},{"∀":0},"⊤",{"D":0},{"∃":3}],"roots":[2],"atoms":[{"P":[0,[0]]}],"symbols":[["p",1]],"fo":[{"B":1}],"binders":["x","x"],"antecedents":0,"cuts":[1]},"nodes":[{"ax":[5,6]}],"instances":{"members":[[2,0],[4,0]],"frames":[[null,1]],"terms":[{"E":0}]}}"#;
    let error = serde_json::from_str::<Proof>(json).unwrap_err();
    assert!(error.to_string().contains("bound variable"), "{error}");
}

/// What the verdict of the default search of `text` in `mode` is: `Some`
/// whether it is proved, its proof checked and holding an instance
/// table, or `None` for unknown.
fn decided(text: &str, mode: Mode, options: &Options) -> Option<bool> {
    let sequent: Sequent = text.parse().unwrap();
    let outcome = deduxit::linear::prove(&sequent, mode, options).unwrap();
    let engine = if mode.is_intuitionistic() {
        Engine::TwoSided
    } else {
        Engine::Focus
    };
    assert_eq!(outcome.engine, engine, "{text}");
    match outcome.verdict {
        Verdict::Proved(proof) => {
            assert_eq!(proof.check(mode), Ok(()), "{text}");
            assert!(proof.instances().is_some(), "{text}");
            Some(true)
        }
        Verdict::Unprovable(_) => Some(false),
        Verdict::Unknown(_) => None,
    }
}

/// The memo and the loop check key a first-order stable sequent by its
/// instance: a clause that leads back to the sequent it started from is
/// pruned as a repeat, the failures below are reused, and the search
/// ends exhaustive where without the memo every copy level is cut by the
/// budget; a sequent proved with the memo has its proof checked.
#[test]
fn the_memo_and_the_loop_check_key_first_order_sequents() {
    let looping = [
        "!(forall x. (p(x) -o p(x))), !(q -o r), !(r -o q), p(e) |- r",
        "!(a -o a), !(b -o c), !(c -o b), a |- forall z. c",
    ];
    let options = Options::default().with_copies(Some(6));
    for text in looping {
        let outcome =
            deduxit::linear::prove(&text.parse().unwrap(), Mode::INTUITIONISTIC, &options).unwrap();
        assert!(matches!(outcome.verdict, Verdict::Unprovable(_)), "{text}");
        assert!(outcome.statistics.memo_hits > 0, "{text}");
        let unkeyed = options.clone().with_memo_limit(0);
        let outcome =
            deduxit::linear::prove(&text.parse().unwrap(), Mode::INTUITIONISTIC, &unkeyed).unwrap();
        assert!(matches!(outcome.verdict, Verdict::Unknown(_)), "{text}");
    }
    let proved = "!(forall x. (p(x) -o p(x))), !(forall x. (p(x) -o q(x))), p(e) |- q(e)";
    assert_eq!(decided(proved, Mode::INTUITIONISTIC, &options), Some(true));
}

/// Under Mix with the memo, the parts of a stable sequent with a member
/// less are asked whether they are provable before its partitions are
/// searched: a part proved under a binding the whole sequent must not take
/// (`x := t` here, where only `x := s` proves it) leaves no binding behind.
#[test]
fn a_part_asked_about_leaves_no_binding() {
    let text = "|- exists x. ((~a(s) * 1) par a(x) par (~a(t) + 1))";
    let mix = Mode::CLASSICAL.with_mix();
    assert_eq!(decided(text, mix, &Options::default()), Some(true));
    assert_eq!(
        decided(text, mix, &Options::default().with_memo_limit(0)),
        Some(true)
    );
}

/// The focused engine decides first-order sequents in every classical
/// mode: the order of the quantifiers (the eigenvariable condition by
/// levels), a witness shared by both factors of a `⊗` whose first answer
/// fails (another answer asked for), the occurs check, a witness left
/// open (closed by a fresh constant), copies of a quantified hypothesis,
/// Mix, and weakening; every proof checked.
#[test]
fn the_focused_engine_decides_first_order_sequents() {
    let (classical, mix, affine) = (
        Mode::CLASSICAL,
        Mode::CLASSICAL.with_mix(),
        Mode::CLASSICAL.with_affine(),
    );
    let options = Options::default();
    for (text, mode, expected) in [
        ("forall x. p(x) |- p(a)", classical, true),
        ("forall x. p(x) |- exists y. p(y)", classical, true),
        ("exists x. p(x) |- forall y. p(y)", classical, false),
        (
            "exists y. forall x. r(x, y) |- forall x. exists y. r(x, y)",
            classical,
            true,
        ),
        (
            "forall x. exists y. r(x, y) |- exists y. forall x. r(x, y)",
            classical,
            false,
        ),
        (
            "p(a) & p(b), q(b) |- exists x. (p(x) * q(x))",
            classical,
            true,
        ),
        (
            "p(b) & p(a), q(b) |- exists x. (p(x) * q(x))",
            classical,
            true,
        ),
        (
            "p(a) & p(b), q(c) |- exists x. (p(x) * q(x))",
            classical,
            false,
        ),
        ("|- exists x. (~p(x) par p(f(x)))", classical, false),
        ("|- forall y. exists x. (~p(x) par p(y))", classical, true),
        ("|- exists x. forall y. (~p(x) par p(y))", classical, false),
        ("forall x. (p(x) & q(x)) |- p(a) & q(a)", classical, true),
        ("forall x. p(x) |- p(a) * p(b)", classical, false),
        ("!forall x. p(x) |- p(a) * p(b)", classical, true),
        (
            "p(z), !forall x. (p(x) -o p(s(x))) |- p(s(s(s(z))))",
            classical,
            true,
        ),
        (
            "|- exists x. (p(x) * q(x)), ~p(a), ~q(a), r, ~r",
            classical,
            false,
        ),
        ("|- exists x. (p(x) * q(x)), ~p(a), ~q(a), r, ~r", mix, true),
        ("forall x. p(x), q(b) |- p(a)", affine, true),
        ("forall x. p(x) |- q(a)", affine, false),
    ] {
        assert_eq!(
            decided(text, mode, &options),
            Some(expected),
            "{text} in {mode}"
        );
    }
}

/// The two-sided engine decides first-order sequents in the
/// intuitionistic modes: the order of the quantifiers, a `∃` on the left
/// opened by an eigenvariable, a quantified implication split by `⊸L`
/// with the goal on its consequent's side, a witness that the second
/// factor of a `⊗` on the right rejects (another answer asked for),
/// copies of a quantified hypothesis under `!`, a quantifier shifted
/// across `⊸` one way and refuted the other, and weakening; every proof
/// checked.
#[test]
fn the_two_sided_engine_decides_first_order_sequents() {
    let (linear, affine) = (Mode::INTUITIONISTIC, Mode::INTUITIONISTIC.with_affine());
    let options = Options::default();
    for (text, mode, expected) in [
        ("forall x. p(x) |- exists y. p(y)", linear, true),
        ("exists x. p(x) |- p(a)", linear, false),
        (
            "exists y. forall x. r(x, y) |- forall x. exists y. r(x, y)",
            linear,
            true,
        ),
        (
            "forall x. exists y. r(x, y) |- exists y. forall x. r(x, y)",
            linear,
            false,
        ),
        (
            "exists x. (p(x) * q(x)) |- exists y. (q(y) * p(y))",
            linear,
            true,
        ),
        ("forall x. (p(x) -o q(x)), p(a) |- q(a)", linear, true),
        ("forall x. (p(x) -o q(x)), p(a) |- q(b)", linear, false),
        ("p(a) & p(b), q(b) |- exists x. (p(x) * q(x))", linear, true),
        (
            "p(a) & p(b), q(c) |- exists x. (p(x) * q(x))",
            linear,
            false,
        ),
        (
            "p(z), !forall x. (p(x) -o p(s(x))) |- p(s(s(z)))",
            linear,
            true,
        ),
        (
            "exists x. (p(x) -o q) |- (forall x. p(x)) -o q",
            linear,
            true,
        ),
        (
            "(forall x. p(x)) -o q |- exists x. (p(x) -o q)",
            linear,
            false,
        ),
        ("forall x. p(x), q(b) |- p(a)", affine, true),
        ("forall x. p(x) |- q(a)", affine, false),
    ] {
        assert_eq!(
            decided(text, mode, &options),
            Some(expected),
            "{text} in {mode}"
        );
    }
}

/// A premise whose answer fails the other is asked for its next one:
/// the witness that a later factor needs is the last of its premise's
/// answers, provable with every proof checked, and refuted where no
/// answer serves, in both engines.
#[test]
fn a_premise_gives_its_answers_in_turn() {
    let options = Options::default();
    for (goal, provable) in [("q(a4)", true), ("q(b)", false)] {
        let ill = format!(
            "p(a1), p(a2), p(a3), p(a4), {goal} |- exists x. (p(x) * q(x)) * exists x. p(x) * exists x. p(x) * exists x. p(x)"
        );
        assert_eq!(
            decided(&ill, Mode::INTUITIONISTIC, &options),
            Some(provable),
            "{ill}"
        );
        let one_sided = format!(
            "|- ~p(a1), ~p(a2), ~p(a3), ~p(a4), ~{goal}, exists x. (p(x) * q(x)) * exists x. p(x) * exists x. p(x) * exists x. p(x)"
        );
        assert_eq!(
            decided(&one_sided, Mode::CLASSICAL, &options),
            Some(provable),
            "{one_sided}"
        );
    }
}

/// The first-order families with verdicts by construction: a witness
/// among `n` alternatives (`p(a₁) & … & p(aₙ), q(aₖ) ⊢ ∃x.(p(x) ⊗ q(x))`,
/// unprovable with `q(b)`), and a chain of `n` steps of a quantified
/// clause under `!`, provable within `n` copies and not within fewer
/// (`p(z), !∀x.(p(x) ⊸ p(s(x))) ⊢ p(sⁿ(z))`).
#[test]
fn the_first_order_families_have_their_verdicts() {
    for n in 1..=5 {
        let alternatives: Vec<String> = (1..=n).map(|i| format!("p(a{i})")).collect();
        let choice = alternatives.join(" & ");
        for k in 1..=n {
            let text = format!("{choice}, q(a{k}) |- exists x. (p(x) * q(x))");
            assert_eq!(
                decided(&text, Mode::CLASSICAL, &Options::default()),
                Some(true),
                "{text}"
            );
        }
        let text = format!("{choice}, q(b) |- exists x. (p(x) * q(x))");
        assert_eq!(
            decided(&text, Mode::CLASSICAL, &Options::default()),
            Some(false),
            "{text}"
        );
    }
    for n in 1..=4u32 {
        let mut goal = "z".to_owned();
        for _ in 0..n {
            goal = format!("s({goal})");
        }
        let text = format!("p(z), !forall x. (p(x) -o p(s(x))) |- p({goal})");
        let options = |copies| Options::default().with_copies(Some(copies));
        assert_eq!(
            decided(&text, Mode::CLASSICAL, &options(n)),
            Some(true),
            "{text}"
        );
        assert_eq!(
            decided(&text, Mode::CLASSICAL, &options(n - 1)),
            None,
            "{text}"
        );
    }
}

/// A first-order search counts the unifications of two literals it tried
/// and the metavariables it bound, one-sided and two-sided; a
/// propositional search counts neither, and its JSON leaves them out.
#[test]
fn a_first_order_search_counts_its_unifications() {
    let counted = |text: &str, mode: Mode| {
        let sequent: Sequent = text.parse().unwrap();
        deduxit::linear::prove(&sequent, mode, &Options::default())
            .unwrap()
            .statistics
    };
    for mode in [Mode::CLASSICAL, Mode::INTUITIONISTIC] {
        let statistics = counted("p(a), p(b) & q(c) |- exists x. (p(x) * p(b))", mode);
        assert!(statistics.unifications >= 2, "{mode}: {statistics:?}");
        assert!(statistics.bindings >= 1, "{mode}: {statistics:?}");
    }
    let statistics = counted("a, b |- a * b", Mode::CLASSICAL);
    assert_eq!((statistics.unifications, statistics.bindings), (0, 0));
    let written = serde_json::to_value(statistics).unwrap();
    assert!(written.get("unifications").is_none() && written.get("bindings").is_none());
}

/// Each first-order bound stops a search that reaches it, with its own
/// reason, and one more lets the search through: a witness deeper than
/// the witness depth, an instance past the bound on instances.
#[test]
fn the_first_order_bounds_stop_the_search() {
    use deduxit::linear::Reason;
    let deep = "|- exists x. p(x), ~p(f(f(f(a))))";
    let outcome = |text: &str, options: &Options| {
        deduxit::linear::prove(&text.parse().unwrap(), Mode::CLASSICAL, options)
            .unwrap()
            .verdict
    };
    let depth = |d| Options::default().with_witness_depth(d);
    let Verdict::Unknown(reason) = outcome(deep, &depth(2)) else {
        panic!("{deep} past the witness depth");
    };
    assert!(matches!(reason, Reason::WitnessDepth { depth: 2, .. }));
    assert_eq!(reason.setting(), Some("search.witness_depth"));
    assert!(matches!(outcome(deep, &depth(3)), Verdict::Proved(_)));
    let two = "|- exists x. exists y. (p(x) * p(y)), ~p(a), ~p(b)";
    let instances = |n| Options::default().with_instances(n);
    let Verdict::Unknown(reason) = outcome(two, &instances(1)) else {
        panic!("{two} past the instances");
    };
    assert!(matches!(reason, Reason::Instances { instances: 1, .. }));
    assert_eq!(reason.setting(), Some("search.instances"));
    assert!(matches!(outcome(two, &instances(2)), Verdict::Proved(_)));
    // Every copy level cut at once by the instances, none bounding the
    // copies: the levels are work, and the work bound ends them, in
    // either mode.
    let cut = "exists x. p(x), exists x. !p(x) |- q";
    let limits = Limits::default().with_work(Some(1 << 20));
    for mode in [Mode::CLASSICAL, Mode::INTUITIONISTIC] {
        let options = instances(1).with_copies(None);
        let outcome =
            deduxit::linear::prove_within(&cut.parse().unwrap(), mode, &options, &limits, |_| {
                false
            })
            .unwrap();
        assert!(matches!(outcome.verdict, Verdict::Unknown(_)), "{mode}");
    }
}

/// The counts carry over to quantifiers: a predicate with an open atom is
/// counted over all its atoms, and refuted so by a kind of its own, which
/// the check accepts and the JSON reads back; an atom of a predicate with
/// only closed atoms is counted alone, as before; the count equation
/// counts a quantifier as its body; the classical refutation, which has
/// no domain, gives nothing.
#[test]
fn the_counts_refute_first_order_sequents() {
    use deduxit::linear::Refutation;
    let refuted = |text: &str| {
        let sequent: Sequent = text.parse().unwrap();
        match deduxit::linear::prove(&sequent, Mode::CLASSICAL, &Options::default())
            .unwrap()
            .verdict
        {
            Verdict::Unprovable(disproof) => *disproof,
            other => panic!("{text}: {other:?}"),
        }
    };
    let symbol = refuted("forall x. p(x), p(a) |- p(b)");
    assert!(
        matches!(symbol.refutation(), Refutation::UnbalancedSymbol(_)),
        "{symbol:?}"
    );
    assert_eq!(symbol.check(), Ok(()));
    assert!(
        symbol
            .to_string()
            .contains("p(…) occurs 1 more time on the left than on the right"),
        "{symbol}"
    );
    let json = serde_json::to_string(&symbol).unwrap();
    assert!(json.contains("\"kind\":\"unbalanced_symbol\""), "{json}");
    let read: Disproof = serde_json::from_str(&json).unwrap();
    assert_eq!(read.check(), Ok(()));
    let atom = refuted("forall x. p(x) |- p(a) * q(b)");
    assert!(
        matches!(atom.refutation(), Refutation::Unbalanced(_)),
        "{atom:?}"
    );
    assert_eq!(atom.check(), Ok(()));
    let equation = refuted("forall x. (p(x) * q(x)) |- p(a) par q(a)");
    assert!(
        matches!(equation.refutation(), Refutation::Equation(_)),
        "{equation:?}"
    );
    assert_eq!(equation.check(), Ok(()));
    // An undecided search stays so: no assignment refutes a quantifier.
    let open = refuted("|- exists x. forall y. (~p(x) par p(y))");
    assert!(
        matches!(open.refutation(), Refutation::Exhausted),
        "{open:?}"
    );
}

/// A witness as deep as its terms go, here a hundred thousand
/// applications around an eigenvariable, is closed into the proof's
/// instance table and checked without a recursion per level, which ran
/// out of the search's stack.
#[test]
fn a_deep_witness_closes_without_recursion() {
    let n = 100_000;
    let text = format!(
        "|- forall z. (~p({}z{}) par (exists y. p(y)))",
        "f(".repeat(n),
        ")".repeat(n)
    );
    let options = Options::default().with_witness_depth(u32::MAX);
    assert_eq!(decided(&text, Mode::CLASSICAL, &options), Some(true));
}

/// Unifying deep terms is work the search counts and polls its stop on:
/// one split search whose every step unifies terms two thousand deep ends
/// at a bound on work, where it used to count none of it and run to its
/// end between two polls.
#[test]
fn a_deep_unification_is_counted_work() {
    use deduxit::linear::Reason;
    let deep = format!("{}z{}", "f(".repeat(2000), ")".repeat(2000));
    let literals: Vec<String> = (0..6).map(|i| format!("~p(g{i}({deep}))")).collect();
    let text = format!(
        "|- forall z. ({} par ~q(a) par (exists y. (p(y) * q(y))))",
        literals.join(" par ")
    );
    let sequent: Sequent = text.parse().unwrap();
    let options = Options::default().with_witness_depth(u32::MAX);
    let limits = Limits::default().with_work(Some(20_000));
    let outcome = deduxit::linear::prove_within(
        &sequent,
        Mode::CLASSICAL.with_affine(),
        &options,
        &limits,
        |_| false,
    )
    .unwrap();
    assert!(
        matches!(outcome.verdict, Verdict::Unknown(Reason::WorkLimit { .. })),
        "{:?}",
        outcome.verdict
    );
}

/// The keys of first-order stable sequents are charged and counted: the
/// keys of every stable sequent on the branch live while its subtree is
/// searched, so a tower of quantifiers over many literals reaches the
/// memory bound within little work, and writing them is work, which a
/// tower of instances makes grow with its height.
#[test]
fn the_first_order_keys_are_charged_and_counted() {
    use deduxit::linear::Reason;
    let tower = |height: usize, inner: String| {
        (0..height).rev().fold(inner, |body, i| {
            format!("exists x{i}. (forall y{i}. {body})")
        })
    };
    let literals: Vec<String> = (0..150).map(|t| format!("q{t}(x39, y39)")).collect();
    let duals: Vec<String> = (0..150).map(|t| format!("~q{t}(a, b)")).collect();
    let wide = format!(
        "|- {}, {}, ~r",
        tower(
            40,
            format!("({} par {})", literals.join(" par "), tower(60, "r".into()))
        ),
        duals.join(", ")
    );
    let limits = Limits::default()
        .with_memory_bytes(Some(2 << 20))
        .with_work(Some(500_000));
    let outcome = deduxit::linear::prove_within(
        &wide.parse().unwrap(),
        Mode::CLASSICAL.with_mix(),
        &Options::default(),
        &limits,
        |_| false,
    )
    .unwrap();
    assert!(
        matches!(
            outcome.verdict,
            Verdict::Unknown(Reason::MemoryLimit { .. })
        ),
        "{:?}",
        outcome.verdict
    );
    let variables: Vec<String> = (0..100).map(|i| format!("x{i}")).collect();
    let high = format!(
        "|- {}, ~p({}, b)",
        tower(100, format!("p({}, x0)", variables.join(", "))),
        vec!["a"; 100].join(", ")
    );
    let work = |memo_limit| {
        let options = Options::default().with_memo_limit(memo_limit);
        let outcome =
            deduxit::linear::prove(&high.parse().unwrap(), Mode::CLASSICAL, &options).unwrap();
        assert!(matches!(outcome.verdict, Verdict::Unprovable(_)));
        outcome.statistics.work
    };
    // About three times the memo-free search's work at this height, where
    // writing the keys went uncounted at a third more.
    assert!(work(1 << 20) > 2 * work(0));
}

/// A witness built over a chain of bindings is one word of a key, not
/// its length: on a chain whose every level is a new instance, which no
/// memo answers, the memo's keys cost little beside the search.
#[test]
fn a_deep_witness_is_one_word_of_a_key() {
    let n = 64;
    let chain: Sequent = "p(z), !forall x. (p(x) -o p(s(x))) |- p(b)"
        .parse()
        .unwrap();
    let work = move |memo_limit| {
        let options = Options::default()
            .with_copies(Some(n))
            .with_witness_depth(n - 1)
            .with_memo_limit(memo_limit);
        let outcome = deduxit::linear::prove(&chain, Mode::CLASSICAL, &options).unwrap();
        assert!(matches!(outcome.verdict, Verdict::Unknown(_)));
        outcome.statistics.work
    };
    // The search recurses as deep as the chain, as the command's does on
    // a thread of this stack.
    let works = std::thread::Builder::new()
        .stack_size(Limits::default().stack_bytes())
        .spawn(move || (work(1 << 20), work(0)))
        .unwrap()
        .join()
        .unwrap();
    // 6 % more, where keys that wrote every witness out cost 31 % more.
    assert!(works.0 * 20 < works.1 * 23, "{works:?}");
}

/// The position in a goal of the formula written `text`.
fn at(state: &Interactive, goal: GoalId, text: &str) -> usize {
    let goal = state.goal(goal).unwrap();
    goal.iter()
        .position(|&m| state.formula(m).to_string() == text)
        .unwrap_or_else(|| {
            let shown: Vec<String> = goal.iter().map(|&m| state.formula(m).to_string()).collect();
            panic!("no {text} among {shown:?}")
        })
}

/// Applies a step on the formula written `text` of the session's only
/// open goal and returns the goals it opens.
fn step(state: &mut Interactive, text: &str, rule: Rule, witness: Option<&str>) -> Vec<GoalId> {
    let goal = state.goals().next().expect("an open goal");
    let mut step = Step::new(at(state, goal, text), rule);
    if let Some(witness) = witness {
        step = step.with_witness(state.witness(witness).unwrap());
    }
    state.apply(goal, &step).unwrap()
}

/// A session proves a first-order sequent with the four quantifier rules:
/// `∃L` and `∀R` with fresh eigenvariables, `∀L` with a witness left open
/// and `∃R` with one given as text; the axiom binds the open witness,
/// undo unbinds it, the session's JSON reads back as itself before and
/// after, and the finished proof passes the checker.
#[test]
fn a_session_proves_with_the_quantifier_rules() {
    let sequent: Sequent = "exists y. forall x. r(x, y) |- forall x. exists y. r(x, y)"
        .parse()
        .unwrap();
    let mode = Mode::INTUITIONISTIC;
    let mut state = Interactive::new(&sequent, mode).unwrap();
    let root = state.goals().next().unwrap();
    let rules = state
        .rules(root, at(&state, root, "∃y. (∀x. r(x, y))"))
        .unwrap();
    assert_eq!(rules[0].rule.to_string(), "∃L");
    // A witness only where the rule takes one.
    let given = Witness::Term(vec![TermNode::Eigen(Eigen::new(0))]);
    let error = state
        .apply(
            root,
            &Step::new(at(&state, root, "∃y. (∀x. r(x, y))"), Rule::Forall).with_witness(given),
        )
        .unwrap_err();
    assert!(matches!(error, StepError::NoWitness { .. }), "{error}");
    step(&mut state, "∃y. (∀x. r(x, y))", Rule::Forall, None);
    step(&mut state, "∀x. (∃y. r(x, y))", Rule::Forall, None);
    let goal = state.goals().next().unwrap();
    let rules = state.rules(goal, at(&state, goal, "∀x. r(x, a)")).unwrap();
    assert_eq!(
        (rules[0].rule.to_string(), rules[0].needs),
        ("∀L".to_owned(), Needs::Witness)
    );
    // A witness of the sequent's terms.
    assert!(matches!(
        state.witness("r(a)"),
        Err(StepError::Witness { .. })
    ));
    assert!(matches!(state.witness("c"), Err(StepError::Witness { .. })));
    step(&mut state, "∀x. r(x, a)", Rule::Exists, None);
    step(&mut state, "∃y. r(b, y)", Rule::Exists, Some("a"));
    let goal = state.goals().next().unwrap();
    let open: Vec<String> = state
        .goal(goal)
        .unwrap()
        .iter()
        .map(|&m| state.formula(m).to_string())
        .collect();
    assert_eq!(open, ["r($1, a)", "r(b, a)"]);
    // An open witness's name reads back as nothing, in either surface.
    for text in ["|- r($1, a)", "|- $1", "r($1, a) |- r(b, a)"] {
        assert!(text.parse::<Sequent>().is_err(), "{text}");
        assert!(
            text.parse::<deduxit::linear::IllSequent>().is_err(),
            "{text}"
        );
    }
    let json = serde_json::to_string(&state).unwrap();
    let back: Interactive = serde_json::from_str(&json).unwrap();
    assert_eq!(serde_json::to_string(&back).unwrap(), json);
    state.apply(goal, &Step::new(0, Rule::Ax)).unwrap();
    assert!(state.is_complete());
    let derivation = state.derivation().unwrap().to_string();
    assert!(derivation.contains("r(b, a) ⊢ r(b, a)"), "{derivation}");
    let json = serde_json::to_string(&state).unwrap();
    assert!(json.contains(r#""bindings":"#), "{json}");
    let back: Interactive = serde_json::from_str(&json).unwrap();
    assert_eq!(serde_json::to_string(&back).unwrap(), json);
    let proof = back.proof(&Limits::default(), |_| false).unwrap();
    assert_eq!(proof.check(mode), Ok(()));
    assert_eq!(state.undo(), Some(goal));
    let open: Vec<String> = state
        .goal(goal)
        .unwrap()
        .iter()
        .map(|&m| state.formula(m).to_string())
        .collect();
    assert_eq!(open, ["r($1, a)", "r(b, a)"]);
    state.apply(goal, &Step::new(0, Rule::Ax)).unwrap();
    let proof = state.proof(&Limits::default(), |_| false).unwrap();
    assert_eq!(proof.check(mode), Ok(()));
}

/// The eigenvariable condition holds in a session: an open witness made
/// before a `∀` step's eigenvariable is never bound to it, and a witness
/// given names only the eigenvariables of the `∀` steps below its goal.
#[test]
fn a_session_keeps_the_eigenvariable_condition() {
    let sequent: Sequent = "forall x. exists y. r(x, y) |- exists y. forall x. r(x, y)"
        .parse()
        .unwrap();
    let mut state = Interactive::new(&sequent, Mode::INTUITIONISTIC).unwrap();
    step(&mut state, "∃y. (∀x. r(x, y))", Rule::Exists, None);
    step(&mut state, "∀x. r(x, $1)", Rule::Forall, None);
    step(&mut state, "∀x. (∃y. r(x, y))", Rule::Exists, Some("a"));
    step(&mut state, "∃y. r(a, y)", Rule::Forall, None);
    let goal = state.goals().next().unwrap();
    let error = state.apply(goal, &Step::new(0, Rule::Ax)).unwrap_err();
    assert!(
        matches!(&error, StepError::Eigenvariable { name, .. } if name == "b"),
        "{error}"
    );
    let sequent: Sequent = "forall x. p(x), forall x. q(x) |- (forall x. p(x)) * (forall x. q(x))"
        .parse()
        .unwrap();
    let mut state = Interactive::new(&sequent, Mode::INTUITIONISTIC).unwrap();
    let root = state.goals().next().unwrap();
    let tensor = at(&state, root, "(∀x. p(x)) ⊗ (∀x. q(x))");
    let left = at(&state, root, "∀x. p(x)");
    let goals = state
        .apply(root, &Step::new(tensor, Rule::Tensor).left(&[left]))
        .unwrap();
    // The factor, after the hypothesis of the same formula.
    let factor = state.goal(goals[0]).unwrap().len() - 1;
    let opened = state
        .apply(goals[0], &Step::new(factor, Rule::Forall))
        .unwrap();
    assert_eq!(opened.len(), 1);
    // `a` is the left premise's: the right one is not in its scope.
    let error = state
        .apply(
            goals[1],
            &Step::new(at(&state, goals[1], "∀x. q(x)"), Rule::Exists)
                .with_witness(state.witness("a").unwrap()),
        )
        .unwrap_err();
    assert!(
        matches!(&error, StepError::Eigenvariable { name, .. } if name == "a"),
        "{error}"
    );
}

/// The search closes a goal of a session: an open witness it fills is
/// bound, as a later axiom would bind it, and undo unbinds it; a goal
/// with eigenvariables is proved with them as the session's; a goal whose
/// open witness was made before an eigenvariable it would need is not
/// proved; every finished proof passes the checker.
#[test]
fn the_search_closes_a_session_goal() {
    let (options, view, limits) = (
        Options::default(),
        deduxit::linear::ViewOptions::default(),
        Limits::default(),
    );
    let mode = Mode::INTUITIONISTIC;
    let sequent: Sequent = "forall x. p(x) |- p(f(a))".parse().unwrap();
    let mut state = Interactive::new(&sequent, mode).unwrap();
    step(&mut state, "∀x. p(x)", Rule::Exists, None);
    let goal = state.goals().next().unwrap();
    let closed = state
        .close(goal, &options, &view, &limits, |_| false)
        .unwrap();
    assert!(matches!(closed.outcome.verdict, Verdict::Proved(_)));
    assert_eq!(closed.grafted, Ok(()));
    assert!(state.is_complete());
    let derivation = state.derivation().unwrap().to_string();
    assert!(derivation.contains("p(f(a)) ⊢ p(f(a))"), "{derivation}");
    let json = serde_json::to_string(&state).unwrap();
    let back: Interactive = serde_json::from_str(&json).unwrap();
    assert_eq!(serde_json::to_string(&back).unwrap(), json);
    assert_eq!(state.proof(&limits, |_| false).unwrap().check(mode), Ok(()));
    assert_eq!(state.undo(), Some(goal));
    let open: Vec<String> = state
        .goal(goal)
        .unwrap()
        .iter()
        .map(|&m| state.formula(m).to_string())
        .collect();
    assert_eq!(open, ["p(f(a))", "p($1)"]);

    let sequent: Sequent = "exists y. forall x. r(x, y) |- forall x. exists y. r(x, y)"
        .parse()
        .unwrap();
    let mut state = Interactive::new(&sequent, mode).unwrap();
    step(&mut state, "∃y. (∀x. r(x, y))", Rule::Forall, None);
    step(&mut state, "∀x. (∃y. r(x, y))", Rule::Forall, None);
    let goal = state.goals().next().unwrap();
    let closed = state
        .close(goal, &options, &view, &limits, |_| false)
        .unwrap();
    assert!(matches!(closed.outcome.verdict, Verdict::Proved(_)));
    assert!(state.is_complete());
    assert_eq!(state.proof(&limits, |_| false).unwrap().check(mode), Ok(()));

    let sequent: Sequent = "forall x. exists y. r(x, y) |- exists y. forall x. r(x, y)"
        .parse()
        .unwrap();
    let mut state = Interactive::new(&sequent, mode).unwrap();
    step(&mut state, "∃y. (∀x. r(x, y))", Rule::Exists, None);
    step(&mut state, "∀x. r(x, $1)", Rule::Forall, None);
    let goal = state.goals().next().unwrap();
    let closed = state
        .close(goal, &options, &view, &limits, |_| false)
        .unwrap();
    assert!(
        matches!(closed.outcome.verdict, Verdict::Unprovable(_)),
        "{:?}",
        closed.outcome.verdict
    );
    assert!(!state.is_complete());

    // A goal without a binder or an open witness left, and the empty goal
    // of a classical mode, are searched as sequents of their own too.
    let sequent: Sequent = "forall x. p(x) |- p(c)".parse().unwrap();
    let mut state = Interactive::new(&sequent, mode).unwrap();
    step(&mut state, "∀x. p(x)", Rule::Exists, Some("c"));
    let goal = state.goals().next().unwrap();
    let closed = state
        .close(goal, &options, &view, &limits, |_| false)
        .unwrap();
    assert!(matches!(closed.outcome.verdict, Verdict::Proved(_)));
    assert_eq!(state.proof(&limits, |_| false).unwrap().check(mode), Ok(()));
    let sequent: Sequent = "|- (exists x. p(x)) * bot".parse().unwrap();
    let mut state = Interactive::new(&sequent, Mode::CLASSICAL).unwrap();
    let goals = step(&mut state, "(∃x. p(x)) ⊗ ⊥", Rule::Tensor, None);
    let bot = state.apply(goals[1], &Step::new(0, Rule::Bot)).unwrap();
    let closed = state
        .close(bot[0], &options, &view, &limits, |_| false)
        .unwrap();
    assert!(matches!(closed.outcome.verdict, Verdict::Unprovable(_)));
}
/// A witness nested 100 000 deep goes through a session without
/// recursion: built flat, printed, written for the search and decided;
/// and a session read from JSON holds no more table entries than
/// `limits.terms`.
#[test]
fn a_session_holds_deep_witnesses_and_bounds_its_table() {
    let sequent: Sequent = "forall x. p(x) |- p(f(c))".parse().unwrap();
    let symbol = |name: &str| {
        let index = sequent
            .symbols()
            .iter()
            .position(|(n, _)| n == name)
            .unwrap();
        deduxit::linear::sequents::Symbol::new(u32::try_from(index).unwrap())
    };
    let mut nodes = vec![TermNode::App(symbol("c"), vec![])];
    for i in 0..100_000u32 {
        nodes.push(TermNode::App(symbol("f"), vec![i]));
    }
    let mut state = Interactive::new(&sequent, Mode::INTUITIONISTIC).unwrap();
    let root = state.goals().next().unwrap();
    let position = at(&state, root, "∀x. p(x)");
    let deep = Step::new(position, Rule::Exists).with_witness(Witness::Term(nodes));
    let goals = state.apply(root, &deep).unwrap();
    let deep = state.formula(state.goal(goals[0]).unwrap()[1]).to_string();
    // `p(`, a hundred thousand `f(`, `c` and as many brackets and one.
    assert_eq!(deep.len(), 2 + 200_000 + 1 + 100_001);
    assert!(deep.starts_with("p(f(f(") && deep.contains("f(f(c))"));
    let view = deduxit::linear::ViewOptions::default();
    let closed = state
        .close(
            goals[0],
            &Options::default(),
            &view,
            &Limits::default(),
            |_| false,
        )
        .unwrap();
    assert!(matches!(closed.outcome.verdict, Verdict::Unprovable(_)));
    assert_eq!(state.undo(), Some(root));
    step(&mut state, "∀x. p(x)", Rule::Exists, Some("f(c)"));
    let json = serde_json::to_string(&state).unwrap();
    // A member and a frame: undo dropped the deep witness's entries.
    let limits = Limits::default().with_terms(Some(1));
    let error = <Interactive as deduxit::wire::Readable>::read(
        &mut serde_json::Deserializer::from_str(&json),
        &limits,
    )
    .unwrap_err();
    assert!(error.to_string().contains("terms"), "{error}");
}

/// `undo` takes back what its step made: the open witnesses `close`
/// bound, and the eigenvariables, constants and entries the step added,
/// so that the session reads as it did before the step.
#[test]
fn undo_drops_what_its_step_made() {
    let sequent: Sequent = "|- exists x. exists y. (p(x) -o p(y))".parse().unwrap();
    let mut state = Interactive::new(&sequent, Mode::CLASSICAL).unwrap();
    step(&mut state, "∃x. (∃y. (~p(x) ⅋ p(y)))", Rule::Exists, None);
    let before = serde_json::to_string(&state).unwrap();
    let goal = state.goals().next().unwrap();
    let (options, view, limits) = (
        Options::default(),
        deduxit::linear::ViewOptions::default(),
        Limits::default(),
    );
    for _ in 0..3 {
        let closed = state
            .close(goal, &options, &view, &limits, |_| false)
            .unwrap();
        assert!(matches!(closed.outcome.verdict, Verdict::Proved(_)));
        assert_eq!(state.undo(), Some(goal));
    }
    assert_eq!(serde_json::to_string(&state).unwrap(), before);
    assert!(matches!(state.witness("a"), Err(StepError::Witness { .. })));
}

/// `undo` after a session is written and read back truncates its table as
/// it does in the session written: steps, undos and steps again, each
/// through the JSON, give the eigenvariable letters, the table and the
/// document of the session that never left memory, and a forged mark is
/// refused.
#[test]
fn a_session_read_back_undoes_as_it_was_written() {
    let sequent: Sequent = "|- forall x. exists y. p(f(x), y) -o p(f(x), y)"
        .parse()
        .unwrap();
    let mut live = Interactive::new(&sequent, Mode::CLASSICAL).unwrap();
    let mut json = serde_json::to_string(&live).unwrap();
    let forall = "∀x. (∃y. (~p(f(x), y) ⅋ p(f(x), y)))";
    let exists = "∃y. (~p(f(a), y) ⅋ p(f(a), y))";
    for round in 0..3 {
        let witness = if round == 1 { None } else { Some("f(a)") };
        let ops: [&dyn Fn(&mut Interactive); 5] = [
            &|state| drop(step(state, forall, Rule::Forall, None)),
            &|state| drop(step(state, exists, Rule::Exists, witness)),
            &|state| assert!(state.undo().is_some()),
            &|state| assert!(state.undo().is_some()),
            &|state| drop(step(state, forall, Rule::Forall, None)),
        ];
        for op in ops {
            op(&mut live);
            let mut read: Interactive = serde_json::from_str(&json).unwrap();
            op(&mut read);
            json = serde_json::to_string(&read).unwrap();
            assert_eq!(json, serde_json::to_string(&live).unwrap(), "round {round}");
        }
        let goal = live.goals().next().unwrap();
        assert_eq!(at(&live, goal, exists), 0);
        assert!(live.undo().is_some());
        let mut read: Interactive = serde_json::from_str(&json).unwrap();
        assert!(read.undo().is_some());
        json = serde_json::to_string(&read).unwrap();
    }
    assert_eq!(json, serde_json::to_string(&live).unwrap());
    assert_eq!(
        json,
        serde_json::to_string(&Interactive::new(&sequent, Mode::CLASSICAL).unwrap()).unwrap()
    );

    // A mark that would drop the eigenvariable its step's goal names.
    step(&mut live, forall, Rule::Forall, None);
    step(&mut live, exists, Rule::Exists, Some("f(a)"));
    let json = serde_json::to_string(&live).unwrap();
    assert!(
        json.contains(r#""marks":[[0,0,0,0,0,0],[1,1,1,1,1,0]]"#),
        "{json}"
    );
    let forged = json.replace("[1,1,1,1,1,0]", "[1,1,1,0,1,0]");
    let error = serde_json::from_str::<Interactive>(&forged).unwrap_err();
    assert!(error.to_string().contains("mark"), "{error}");
}

/// Reads a cut formula in a mode's syntax.
fn cut_formula(text: &str, mode: Mode) -> CutFormula {
    CutFormula::parse_within(text, mode, &InputOptions::default(), &Limits::default()).unwrap()
}

/// A first-order session cuts after its quantifier steps: the members past
/// the forest move past the cut formula's trees and keep their instances
/// and letters, both premises are proved with the quantifier rules, the
/// session reads back from its JSON before and after, undo takes the cut
/// back to the session before it, and the finished proof passes the
/// checker; a cut formula that names a symbol the sequent lacks is
/// refused by name, and a session without quantifiers gains them with its
/// cut formula's.
#[test]
fn a_first_order_session_cuts() {
    let mode = Mode::INTUITIONISTIC;
    let sequent: Sequent = "forall x. p(x) |- forall y. p(y)".parse().unwrap();
    let mut state = Interactive::new(&sequent, mode).unwrap();
    step(&mut state, "∀y. p(y)", Rule::Forall, None);
    let goal = state.goals().next().unwrap();
    let before = serde_json::to_string(&state).unwrap();
    let error = state
        .cut(goal, &cut_formula("q", mode), &[0], &Limits::default())
        .unwrap_err();
    assert!(
        matches!(&error, Error::Step(StepError::CutSymbol { name, .. }) if name == "q"),
        "{error}"
    );
    let left = at(&state, goal, "∀x. p(x)");
    let [first, second] = state
        .cut(
            goal,
            &cut_formula("forall z. p(z)", mode),
            &[left],
            &Limits::default(),
        )
        .unwrap();
    let shown = |state: &Interactive, goal: GoalId| -> Vec<String> {
        let goal = state.goal(goal).unwrap();
        goal.iter().map(|&m| state.formula(m).to_string()).collect()
    };
    assert_eq!(shown(&state, first), ["∀x. p(x)", "∀z. p(z)"]);
    // The dual is the arena's equal term, with its bound variable's name.
    assert_eq!(shown(&state, second), ["∀x. p(x)", "p(a)"]);
    let json = serde_json::to_string(&state).unwrap();
    let back: Interactive = serde_json::from_str(&json).unwrap();
    assert_eq!(serde_json::to_string(&back).unwrap(), json);
    let mut cut = state.clone();
    assert_eq!(cut.undo(), Some(goal));
    assert_eq!(serde_json::to_string(&cut).unwrap(), before);
    let mut read: Interactive = serde_json::from_str(&json).unwrap();
    assert_eq!(read.undo(), Some(goal));
    assert_eq!(
        serde_json::to_string(&read).unwrap(),
        serde_json::to_string(&cut).unwrap()
    );
    // `∀z. p(z) ⊢ p(a)` by `∀L` with `a`, `∀x. p(x) ⊢ ∀z. p(z)` by `∀R` and
    // `∀L` with the open witness the axiom binds.
    let ax = |state: &mut Interactive| {
        let goal = state.goals().next().unwrap();
        state.apply(goal, &Step::new(0, Rule::Ax)).unwrap();
    };
    let goal = |state: &Interactive, n: usize| state.goals().nth(n).unwrap();
    let g = goal(&state, 1);
    let p = at(&state, g, "∀x. p(x)");
    let a = state.witness("a").unwrap();
    state
        .apply(g, &Step::new(p, Rule::Exists).with_witness(a))
        .unwrap();
    let g = goal(&state, 1);
    state.apply(g, &Step::new(0, Rule::Ax)).unwrap();
    step(&mut state, "∀z. p(z)", Rule::Forall, None);
    step(&mut state, "∀x. p(x)", Rule::Exists, None);
    assert_eq!(
        shown(&state, goal(&state, 0)),
        ["p(b)", "p($1)"],
        "the eigenvariable after the cut is the next letter"
    );
    ax(&mut state);
    assert!(state.is_complete());
    let json = serde_json::to_string(&state).unwrap();
    let back: Interactive = serde_json::from_str(&json).unwrap();
    assert_eq!(serde_json::to_string(&back).unwrap(), json);
    for state in [&state, &back] {
        let proof = state.proof(&Limits::default(), |_| false).unwrap();
        assert_eq!(proof.check(mode), Ok(()));
    }

    // A cut formula that adds terms to the arena after the table has its
    // own: the table's terms are numbered past the larger arena.
    let sequent: Sequent = "forall x. p(x) |- forall y. exists w. p(f(w))"
        .parse()
        .unwrap();
    let mut state = Interactive::new(&sequent, mode).unwrap();
    step(&mut state, "∀y. (∃w. p(f(w)))", Rule::Forall, None);
    let goal = state.goals().next().unwrap();
    let uncut = serde_json::to_string(&state).unwrap();
    let left = at(&state, goal, "∀x. p(x)");
    let formula = cut_formula("forall z. p(f(f(z)))", mode);
    let [first, second] = state
        .cut(goal, &formula, &[left], &Limits::default())
        .unwrap();
    assert_eq!(shown(&state, second), ["∀z. p(f(f(z)))", "∃w. p(f(w))"]);
    let apply = |state: &mut Interactive, g: GoalId, text: &str, witness: &str| {
        let witness = state.witness(witness).unwrap();
        let p = at(state, g, text);
        state
            .apply(g, &Step::new(p, Rule::Exists).with_witness(witness))
            .unwrap()[0]
    };
    let g = apply(&mut state, second, "∃w. p(f(w))", "f(a)");
    let g = apply(&mut state, g, "∀z. p(f(f(z)))", "a");
    assert_eq!(shown(&state, g), ["p(f(f(a)))", "p(f(f(a)))"]);
    state.apply(g, &Step::new(0, Rule::Ax)).unwrap();
    assert_eq!(state.goals().next(), Some(first));
    step(&mut state, "∀z. p(f(f(z)))", Rule::Forall, None);
    step(&mut state, "∀x. p(x)", Rule::Exists, Some("f(f(b))"));
    ax(&mut state);
    let json = serde_json::to_string(&state).unwrap();
    let back: Interactive = serde_json::from_str(&json).unwrap();
    assert_eq!(serde_json::to_string(&back).unwrap(), json);
    let proof = back.proof(&Limits::default(), |_| false).unwrap();
    assert_eq!(proof.check(mode), Ok(()));
    let mut back = back;
    while back.steps() > 1 {
        back.undo();
    }
    assert_eq!(serde_json::to_string(&back).unwrap(), uncut);

    // A cut formula holding a closed term the table made before, a
    // witness: the session reads back.
    let sequent: Sequent = "forall x. p(f(x)), q(c) |- exists y. p(y) * q(c)"
        .parse()
        .unwrap();
    let mut state = Interactive::new(&sequent, mode).unwrap();
    let opened = step(&mut state, "∀x. p(f(x))", Rule::Exists, Some("f(c)"));
    assert!(shown(&state, opened[0]).contains(&"p(f(f(c)))".to_owned()));
    state
        .cut(
            opened[0],
            &cut_formula("q(f(c))", mode),
            &[],
            &Limits::default(),
        )
        .unwrap();
    let json = serde_json::to_string(&state).unwrap();
    let back: Interactive = serde_json::from_str(&json).unwrap();
    assert_eq!(serde_json::to_string(&back).unwrap(), json);

    // A ground sequent cut on a quantified formula, classical as written.
    let mode = Mode::CLASSICAL;
    let sequent: Sequent = "p(a) |- exists x. p(x)".parse().unwrap();
    let mut state = Interactive::new(&sequent, mode).unwrap();
    let root = state.goals().next().unwrap();
    let left = at(&state, root, "~p(a)");
    let [first, _] = state
        .cut(
            root,
            &cut_formula("exists y. p(y)", mode),
            &[left],
            &Limits::default(),
        )
        .unwrap();
    assert_eq!(shown(&state, first), ["~p(a)", "∃y. p(y)"]);
    let a = state.witness("a").unwrap();
    state
        .apply(first, &Step::new(1, Rule::Exists).with_witness(a))
        .unwrap();
    loop {
        let Some(g) = state.goals().next() else {
            break;
        };
        let formulas = shown(&state, g);
        if formulas.iter().any(|f| f.starts_with("∀")) {
            let p = formulas.iter().position(|f| f.starts_with("∀")).unwrap();
            state.apply(g, &Step::new(p, Rule::Forall)).unwrap();
        } else if let Some(p) = formulas.iter().position(|f| f.starts_with("∃")) {
            state.apply(g, &Step::new(p, Rule::Exists)).unwrap();
        } else {
            state.apply(g, &Step::new(0, Rule::Ax)).unwrap();
        }
    }
    let proof = state.proof(&Limits::default(), |_| false).unwrap();
    assert_eq!(proof.check(mode), Ok(()));
    let json = serde_json::to_string(&state).unwrap();
    let mut back: Interactive = serde_json::from_str(&json).unwrap();
    while back.undo().is_some() {}
    assert_eq!(
        serde_json::to_string(&back).unwrap(),
        serde_json::to_string(&Interactive::new(&sequent, mode).unwrap()).unwrap()
    );
}

/// A cut formula may name the eigenvariables of the `∀` steps below its
/// goal: the cut is on the instance of a closed formula's body, both
/// premises hold the instance, the finished proof passes the checker, the
/// session reads back and undo takes the cut back; an eigenvariable of
/// another branch is refused in words, as a witness's is.
#[test]
fn a_cut_formula_names_the_goals_eigenvariables() {
    let mode = Mode::INTUITIONISTIC;
    let sequent: Sequent = "forall x. (p(x) -o q(x)), forall x. p(x) |- forall y. q(y)"
        .parse()
        .unwrap();
    let mut state = Interactive::new(&sequent, mode).unwrap();
    step(&mut state, "∀y. q(y)", Rule::Forall, None);
    let goal = state.goals().next().unwrap();
    let before = serde_json::to_string(&state).unwrap();
    let left = at(&state, goal, "∀x. p(x)");
    let [first, second] = state
        .cut(
            goal,
            &cut_formula("p(a)", mode),
            &[left],
            &Limits::default(),
        )
        .unwrap();
    let shown = |state: &Interactive, goal: GoalId| -> Vec<String> {
        let goal = state.goal(goal).unwrap();
        goal.iter().map(|&m| state.formula(m).to_string()).collect()
    };
    assert_eq!(shown(&state, first), ["∀x. p(x)", "p(a)"]);
    assert_eq!(shown(&state, second), ["∀x. (p(x) ⊸ q(x))", "q(a)", "p(a)"]);
    let json = serde_json::to_string(&state).unwrap();
    let mut back: Interactive = serde_json::from_str(&json).unwrap();
    assert_eq!(serde_json::to_string(&back).unwrap(), json);
    assert_eq!(back.undo(), Some(goal));
    assert_eq!(serde_json::to_string(&back).unwrap(), before);
    let (options, view, limits) = (
        Options::default(),
        deduxit::linear::ViewOptions::default(),
        Limits::default(),
    );
    for goal in [first, second] {
        let closed = state
            .close(goal, &options, &view, &limits, |_| false)
            .unwrap();
        assert!(matches!(closed.outcome.verdict, Verdict::Proved(_)));
    }
    assert!(state.is_complete());
    let derivation = state.derivation().unwrap().to_string();
    assert!(derivation.contains("∀x. p(x) ⊢ p(a)"), "{derivation}");
    let json = serde_json::to_string(&state).unwrap();
    let back: Interactive = serde_json::from_str(&json).unwrap();
    assert_eq!(serde_json::to_string(&back).unwrap(), json);
    for state in [&state, &back] {
        let proof = state.proof(&Limits::default(), |_| false).unwrap();
        assert_eq!(proof.check(mode), Ok(()));
    }

    // A second cut on an instance while the first stands: the first's
    // member moves past the second's trees with every other.
    let sequent: Sequent = "forall x. (p(x) -o q(x)), forall x. p(x) |- forall y. q(y)"
        .parse()
        .unwrap();
    let fresh = serde_json::to_string(&Interactive::new(&sequent, mode).unwrap()).unwrap();
    let mut state: Interactive = serde_json::from_str(&fresh).unwrap();
    step(&mut state, "∀y. q(y)", Rule::Forall, None);
    let goal = state.goals().next().unwrap();
    let left = at(&state, goal, "∀x. p(x)");
    let [_, second] = state
        .cut(
            goal,
            &cut_formula("p(a)", mode),
            &[left],
            &Limits::default(),
        )
        .unwrap();
    let left = at(&state, second, "∀x. (p(x) ⊸ q(x))");
    state
        .cut(
            second,
            &cut_formula("p(a) -o q(a)", mode),
            &[left],
            &Limits::default(),
        )
        .unwrap();
    let json = serde_json::to_string(&state).unwrap();
    let back: Interactive = serde_json::from_str(&json).unwrap();
    assert_eq!(serde_json::to_string(&back).unwrap(), json);
    let goals: Vec<GoalId> = state.goals().collect();
    for goal in goals {
        let closed = state
            .close(goal, &options, &view, &limits, |_| false)
            .unwrap();
        assert!(matches!(closed.outcome.verdict, Verdict::Proved(_)));
    }
    let proof = state.proof(&Limits::default(), |_| false).unwrap();
    assert_eq!(proof.check(mode), Ok(()));
    let mut back: Interactive =
        serde_json::from_str(&serde_json::to_string(&state).unwrap()).unwrap();
    while back.undo().is_some() {}
    assert_eq!(serde_json::to_string(&back).unwrap(), fresh);

    // `a` belongs to the left premise of the `⊗`.
    let sequent: Sequent = "forall x. p(x), forall x. q(x) |- (forall y. p(y)) * (forall y. q(y))"
        .parse()
        .unwrap();
    let mut state = Interactive::new(&sequent, mode).unwrap();
    let root = state.goals().next().unwrap();
    let tensor = at(&state, root, "(∀y. p(y)) ⊗ (∀y. q(y))");
    let left = at(&state, root, "∀x. p(x)");
    let goals = state
        .apply(root, &Step::new(tensor, Rule::Tensor).left(&[left]))
        .unwrap();
    let factor = at(&state, goals[0], "∀y. p(y)");
    state
        .apply(goals[0], &Step::new(factor, Rule::Forall))
        .unwrap();
    let error = state
        .cut(
            goals[1],
            &cut_formula("q(a)", mode),
            &[0],
            &Limits::default(),
        )
        .unwrap_err();
    assert!(
        matches!(&error, Error::Step(StepError::Eigenvariable { name, .. }) if name == "a"),
        "{error}"
    );
    assert!(error.to_string().contains("eigenvariable a"), "{error}");
}

/// Undoing a cut keeps every arena term and symbol the session's table
/// still names: in a session read without its marks, whose undone step
/// left a witness naming a term the cut brought, and in one whose
/// sequent, read from JSON, has a symbol no atom uses but a witness does.
#[test]
fn undoing_a_cut_keeps_what_the_table_names() {
    let mode = Mode::INTUITIONISTIC;
    let sequent: Sequent = "p(f(c)) |- exists y. p(y)".parse().unwrap();
    let mut state = Interactive::new(&sequent, mode).unwrap();
    let root = state.goals().next().unwrap();
    let [_, second] = state
        .cut(
            root,
            &cut_formula("p(f(f(c)))", mode),
            &[],
            &Limits::default(),
        )
        .unwrap();
    let p = at(&state, second, "∃y. p(y)");
    let witness = state.witness("f(f(c))").unwrap();
    state
        .apply(second, &Step::new(p, Rule::Exists).with_witness(witness))
        .unwrap();
    let mut json: serde_json::Value = serde_json::to_value(&state).unwrap();
    json["instances"].as_object_mut().unwrap().remove("marks");
    let mut read: Interactive = serde_json::from_value(json).unwrap();
    assert!(read.undo().is_some() && read.undo().is_some());
    let again = serde_json::to_string(&read).unwrap();
    serde_json::from_str::<Interactive>(&again).unwrap();

    let mut sequent =
        serde_json::to_value("p(c) |- exists y. p(y)".parse::<Sequent>().unwrap()).unwrap();
    sequent["symbols"]
        .as_array_mut()
        .unwrap()
        .push(serde_json::json!(["g", 1]));
    let sequent: Sequent = serde_json::from_value(sequent).unwrap();
    let mut state = Interactive::new(&sequent, mode).unwrap();
    let root = state.goals().next().unwrap();
    let p = at(&state, root, "∃y. p(y)");
    let witness = state.witness("g(c)").unwrap();
    let goal = state
        .apply(root, &Step::new(p, Rule::Exists).with_witness(witness))
        .unwrap()[0];
    let before = serde_json::to_string(&state).unwrap();
    state
        .cut(goal, &cut_formula("p(c)", mode), &[], &Limits::default())
        .unwrap();
    assert_eq!(state.undo(), Some(goal));
    assert_eq!(serde_json::to_string(&state).unwrap(), before);
}

/// A session refuses what none of its steps could make: a witness that
/// unfolds past `limits.terms` (a term of shared halves, a hundred
/// thousand nodes written out to 2⁴⁰), and in its JSON a binding at a
/// step that closes no goal and an open witness whose level admits an
/// eigenvariable made after it.
#[test]
fn a_session_refuses_what_no_step_could_make() {
    let sequent: Sequent = "forall x. p(x) |- p(g(c, c))".parse().unwrap();
    let index = |name: &str| {
        let i = sequent
            .symbols()
            .iter()
            .position(|(n, _)| n == name)
            .unwrap();
        deduxit::linear::sequents::Symbol::new(u32::try_from(i).unwrap())
    };
    let mut nodes = vec![TermNode::App(index("c"), vec![])];
    for i in 0..40u32 {
        nodes.push(TermNode::App(index("g"), vec![i, i]));
    }
    let mut state = Interactive::new(&sequent, Mode::INTUITIONISTIC).unwrap();
    let root = state.goals().next().unwrap();
    let position = at(&state, root, "∀x. p(x)");
    let error = state
        .apply(
            root,
            &Step::new(position, Rule::Exists).with_witness(Witness::Term(nodes)),
        )
        .unwrap_err();
    assert!(
        matches!(&error, StepError::Witness { reason, .. } if reason.contains("unfold")),
        "{error}"
    );
    assert_eq!(state.steps(), 0);

    // The session measures what its reader measures: under a limit of 4
    // a witness of 11 terms is refused, and a session within the limit
    // reads back under it.
    let sequent: Sequent = "|- exists x. p(x), ~p(a), q(g(b))".parse().unwrap();
    let limits = Limits::default().with_terms(Some(4));
    let mut state = Interactive::within(&sequent, Mode::CLASSICAL, &limits).unwrap();
    let root = state.goals().next().unwrap();
    let deep = state.witness("g(g(g(g(g(g(g(g(g(g(a))))))))))").unwrap();
    let error = state
        .apply(root, &Step::new(0, Rule::Exists).with_witness(deep))
        .unwrap_err();
    assert!(matches!(error, StepError::Witness { .. }), "{error}");
    let a = state.witness("a").unwrap();
    state
        .apply(root, &Step::new(0, Rule::Exists).with_witness(a))
        .unwrap();
    let json = serde_json::to_string(&state).unwrap();
    <Interactive as deduxit::wire::Readable>::read(
        &mut serde_json::Deserializer::from_str(&json),
        &limits,
    )
    .unwrap();

    // A binding moved onto the `∀L` step that opened its witness.
    let sequent: Sequent = "forall x. p(x) |- p(c)".parse().unwrap();
    let mut state = Interactive::new(&sequent, Mode::INTUITIONISTIC).unwrap();
    let goals = step(&mut state, "∀x. p(x)", Rule::Exists, None);
    state.apply(goals[0], &Step::new(0, Rule::Ax)).unwrap();
    let json = serde_json::to_string(&state).unwrap();
    let forged = json.replace(r#""bindings":[[0,1,1]]"#, r#""bindings":[[0,1,0]]"#);
    assert_ne!(forged, json, "{json}");
    assert!(serde_json::from_str::<Interactive>(&json).is_ok());
    let error = serde_json::from_str::<Interactive>(&forged).unwrap_err();
    assert!(error.to_string().contains("binding"), "{error}");

    // An open witness made before the eigenvariables `a` and `b`, given
    // a level that admits them.
    let sequent: Sequent = "forall x. exists y. r(x, y) |- exists y. forall x. r(x, y)"
        .parse()
        .unwrap();
    let mut state = Interactive::new(&sequent, Mode::INTUITIONISTIC).unwrap();
    step(&mut state, "∃y. (∀x. r(x, y))", Rule::Exists, None);
    step(&mut state, "∀x. r(x, $1)", Rule::Forall, None);
    step(&mut state, "∀x. (∃y. r(x, y))", Rule::Exists, Some("a"));
    step(&mut state, "∃y. r(a, y)", Rule::Forall, None);
    let json = serde_json::to_string(&state).unwrap();
    let forged = json.replace(r#""metas":[0]"#, r#""metas":[2]"#);
    assert_ne!(forged, json, "{json}");
    assert!(serde_json::from_str::<Interactive>(&json).is_ok());
    let error = serde_json::from_str::<Interactive>(&forged).unwrap_err();
    assert!(error.to_string().contains("level"), "{error}");

    // A mark that drops the constant `close` made, keeping the
    // eigenvariable it is.
    let sequent: Sequent = "|- (exists x. 1) & (forall y. 1)".parse().unwrap();
    let mut state = Interactive::new(&sequent, Mode::CLASSICAL).unwrap();
    let root = state.goals().next().unwrap();
    let goals = state.apply(root, &Step::new(0, Rule::With)).unwrap();
    let opened = state.apply(goals[0], &Step::new(0, Rule::Exists)).unwrap();
    let closed = state
        .close(
            opened[0],
            &Options::default(),
            &deduxit::linear::ViewOptions::default(),
            &Limits::default(),
            |_| false,
        )
        .unwrap();
    assert!(closed.grafted.is_ok());
    let goal = state.goals().next().unwrap();
    state.apply(goal, &Step::new(0, Rule::Forall)).unwrap();
    let json = serde_json::to_string(&state).unwrap();
    let forged = json.replace("[3,1,1,2,1,1]", "[3,1,1,2,1,0]");
    assert_ne!(forged, json, "{json}");
    let error = serde_json::from_str::<Interactive>(&forged).unwrap_err();
    assert!(error.to_string().contains("mark"), "{error}");
}