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
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! Step-by-step proving: build a derivation from the sequent upwards, one
//! rule at a time.
//!
//! An [`Interactive`] session starts with the whole sequent as its one open
//! goal (a sequent still to prove). You name a goal, a formula in it by its
//! position and a rule ([`Step`]). The session checks that the rule applies
//! there in its mode, and returns the goals the rule opens: its premises.
//! The search can close any goal ([`Interactive::close`]), and
//! [`Interactive::undo`] takes back the last step. When no goal is open,
//! [`Interactive::proof`] turns the derivation into a proof term and runs
//! the checker on it, so a session is trusted no more than a search engine.
//!
#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
//! use deduxit::Limits;
//! use deduxit::linear::{Interactive, Mode, Rule, Sequent, Step};
//!
//! let sequent: Sequent = "|- a par ~a".parse()?;
//! let mut session = Interactive::new(&sequent, Mode::CLASSICAL)?;
//! let root = session.goals().next().unwrap();
//! // ⅋ on formula 0 opens one goal: ⊢ a, ~a.
//! let opened = session.apply(root, &Step::new(0, Rule::Par))?;
//! assert_eq!(session.goals().collect::<Vec<_>>(), opened);
//! // The axiom on formula 0 closes it and opens none.
//! assert_eq!(session.apply(opened[0], &Step::new(0, Rule::Ax))?, []);
//! assert!(session.is_complete());
//! // `|_| false` is a stop that never fires.
//! let proof = session.proof(&Limits::default(), |_| false)?;
//! # Ok::<(), deduxit::Error>(())
//! ```
//!
//! The inferences are those of the derivation view, with its sequents
//! (occurrence ids in ascending order, with repeats) and its rule names. An
//! open goal is an inference with [`Rule::Open`] and no premises. The
//! session stores its inferences top-down: the root is inference 0, and a
//! step appends the goals it opens at the end. So a premise has a larger
//! index than its conclusion, the reverse of a [`Derivation`];
//! [`Interactive::derivation`] renumbers them.
//!
//! Needs the cargo feature `interactive` (on by default).

// A rule added to `Rule` must not fall into an existing arm.
#![deny(clippy::wildcard_enum_match_arm)]

mod cut;
mod expand;
mod handover;
mod invert;
mod quantified;
#[cfg(feature = "serialize")]
mod replay;
mod terms;
mod witness;

pub use cut::CutFormula;
#[cfg(all(test, feature = "parse"))]
pub(crate) use cut::with_cuts;
pub use invert::{Inverted, Options};
#[cfg(feature = "serialize")]
pub(crate) use quantified::{PartTerm, Parts};

use crate::Error;
use crate::limits::{Limits, Phase, Progress, Refusal};
use crate::linear::fragment::Mode;
use crate::linear::occurrences::{ClassicalSequent, Forest, Member, OccId, Reading, Side, Written};
use crate::linear::proofs::derivation::{Derivation, InfId, Inference, ViewOptions};
use crate::linear::proofs::size::Size;
use crate::linear::proofs::{Named, Rule};
use crate::linear::search::Outcome;
use crate::linear::sequents::{Eigen, Sequent, Symbol};
use quantified::Quantified;
use std::fmt::{Display, Formatter, Result as FmtResult};

/// Why a step does not apply to a goal. Positions are those in the goal's
/// sequent, as the caller gave them.
///
/// Needs the cargo feature `interactive` (on by default).
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize),
    serde(tag = "kind", rename_all = "snake_case")
)]
#[non_exhaustive]
pub enum StepError {
    /// No open goal has this id.
    #[non_exhaustive]
    NoGoal {
        /// The id asked for.
        goal: GoalId,
    },
    /// The goal has no formula at the position; it has `len` formulas.
    #[non_exhaustive]
    NoFormula {
        /// The position asked for.
        position: usize,
        /// How many formulas the goal has.
        len: usize,
    },
    /// The rule does not act on the formula at the position: the formula
    /// has another connective, or in intuitionistic mode the rule is for
    /// the other side of `⊢`.
    #[non_exhaustive]
    Rule {
        /// The rule asked for.
        rule: Named,
        /// The position of the formula.
        position: usize,
        /// The formula as the session writes it
        /// ([`Interactive::formula`]), cut after 4 096 characters with
        /// `…`.
        formula: Box<str>,
    },
    /// The rule is not available in the mode. Weakening a formula that is
    /// not a `?` formula needs affine mode, and Mix needs a mode with Mix.
    /// An ordered mode has only the axiom, `⊗` and `⅋`.
    #[non_exhaustive]
    Mode {
        /// The rule asked for.
        rule: Named,
        /// The mode of the proof.
        mode: Mode,
    },
    /// The rule needs the formula alone in the goal (`1`), or alone with its
    /// dual (`ax`). In affine mode, weaken the other formulas first.
    #[non_exhaustive]
    NotAlone {
        /// The rule asked for.
        rule: Named,
        /// The position of the formula.
        position: usize,
    },
    /// The axiom needs the goal to be the literal and its dual, and the
    /// other formula is not its dual.
    #[non_exhaustive]
    NoDual {
        /// The position of the literal.
        position: usize,
    },
    /// Promotion needs every other formula to be a `?` formula, and the one
    /// at the position is not.
    #[non_exhaustive]
    NotQuest {
        /// The position of a formula that is not a `?` formula.
        position: usize,
    },
    /// A position of the split is out of range, repeated, or the formula the
    /// rule acts on.
    #[non_exhaustive]
    Split {
        /// The position at fault.
        position: usize,
    },
    /// A split was given to a rule that takes none.
    #[non_exhaustive]
    NoSplit {
        /// The rule asked for.
        rule: Named,
    },
    /// In intuitionistic mode, a premise would have `count` formulas on the
    /// right of `⊢` instead of one.
    #[non_exhaustive]
    Succedents {
        /// How many formulas would stand right of `⊢`.
        count: usize,
    },
    /// In intuitionistic mode, the formula on the right of `⊢` cannot be
    /// weakened.
    #[non_exhaustive]
    Output {
        /// The position of the formula.
        position: usize,
    },
    /// A Mix whose split leaves a premise without a formula. No rule
    /// concludes the empty sequent, so nothing could close that premise.
    EmptyPremise,
    /// In an ordered mode, the split is not the two arcs on either side of
    /// the `⊗`. Going round from the `⊗`, the formulas going right must
    /// come first and those going left after them. Any other split needs
    /// an exchange, which an ordered mode does not have.
    #[non_exhaustive]
    Exchange {
        /// The position of a formula going left that comes before one
        /// going right.
        position: usize,
    },
    /// In the Lambek calculus without empty antecedents, a premise would
    /// have no formula left of `⊢`, which no proof in that calculus has.
    EmptyAntecedent,
    /// A witness was given to a rule that takes none. Only `∃R` and `∀L`
    /// take one (`∃` in a one-sided session).
    #[non_exhaustive]
    NoWitness {
        /// The rule asked for.
        rule: Named,
    },
    /// The witness is not a closed term built from the sequent's function
    /// symbols and the session's eigenvariables, or the session would grow
    /// past its bound on terms.
    #[non_exhaustive]
    Witness {
        /// What is wrong with it.
        reason: String,
    },
    /// The step breaks the eigenvariable condition. An eigenvariable (the
    /// fresh name a `∀` step introduces; two-sided, a `∀R` or `∃L` step)
    /// may stand only above the step that introduced it. This step would
    /// put it elsewhere: into a witness of a goal with no such step below
    /// it, or into an open witness made before the eigenvariable.
    #[non_exhaustive]
    Eigenvariable {
        /// The eigenvariable, as the session writes it.
        name: String,
    },
    /// A cut formula names a symbol that the sequent has with another
    /// arity or role. Or, in a session with quantifiers, it names a symbol
    /// the sequent does not have and that is not an eigenvariable's letter
    /// used as a term.
    #[non_exhaustive]
    CutSymbol {
        /// The name, as written.
        name: String,
    },
}

impl Display for StepError {
    /// Writes the refusal as a phrase, naming rules and positions.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match self {
            StepError::NoGoal { goal: id } => write!(f, "there is no open goal {}", id.get()),
            StepError::NoFormula { position, len } => {
                write!(
                    f,
                    "the goal has no formula {position}: it has {}",
                    crate::errors::counted(*len, "formula", "formulas")
                )
            }
            StepError::Rule {
                rule,
                position,
                formula,
            } => write!(
                f,
                "the rule {rule} does not act on formula {position}, {formula}"
            ),
            StepError::Mode { rule, mode } => {
                write!(f, "the rule {rule} is not available in {mode} mode")
            }
            StepError::NotAlone { rule, position } => write!(
                f,
                "the rule {rule} needs formula {position} without other formulas in the goal"
            ),
            StepError::NoDual { position } => write!(
                f,
                "the axiom needs formula {position} together with its dual literal and nothing else"
            ),
            StepError::NotQuest { position } => write!(
                f,
                "promotion needs every other formula to be a ? formula, and formula {position} is not"
            ),
            StepError::Split { position } => write!(
                f,
                "position {position} cannot go to the left premise: it is out of range, repeated, or the formula the rule acts on"
            ),
            StepError::NoSplit { rule } => write!(f, "the rule {rule} takes no split"),
            StepError::Succedents { count: n } => write!(
                f,
                "a premise would have {n} formulas right of ⊢ instead of one"
            ),
            StepError::Output { position } => write!(
                f,
                "formula {position} is the one right of ⊢ and cannot be weakened"
            ),
            StepError::EmptyPremise => {
                f.write_str("the split leaves a premise without a formula, which no rule concludes")
            }
            StepError::EmptyAntecedent => f.write_str(
                "a premise would have no formula left of ⊢, which the Lambek calculus without \
                 empty antecedents forbids",
            ),
            StepError::NoWitness { rule } => write!(f, "the rule {rule} takes no witness"),
            StepError::Witness { reason } => write!(f, "the witness is not a term here: {reason}"),
            StepError::Eigenvariable { name } => write!(
                f,
                "the eigenvariable {name} cannot be used here: either no step below this goal \
                 introduced it (a ∀ step, or ∀R or ∃L two-sided), or it was made after the \
                 open witness it would fill"
            ),
            StepError::CutSymbol { name } => write!(
                f,
                "the cut formula names {name}, which the sequent does not have with this arity \
                 and role: in a session with quantifiers, a cut formula may use only the \
                 sequent's symbols and the goal's eigenvariables"
            ),
            StepError::Exchange { position } => write!(
                f,
                "formula {position} goes left but comes before a formula that goes right, which \
                 would need an exchange: the left premise takes the formulas just before the ⊗, \
                 going round"
            ),
        }
    }
}

impl std::error::Error for StepError {}

impl StepError {
    /// The most characters of a formula a [`Rule`](Self::Rule) refusal
    /// carries: a formula of a session read from JSON can unfold to more
    /// text than any memory holds.
    const SHOWN: usize = 1 << 12;
}

/// The number of an inference of a session, in the session's own order:
/// the root is `0`, and every step's premises come after it.
///
/// It names the goals that [`Interactive::apply`],
/// [`close`](Interactive::close) and [`undo`](Interactive::undo) take and
/// return. The session's [`Derivation`] numbers its inferences otherwise
/// ([`InfId`]); [`Interactive::derivation_ids`] maps one to the other.
///
/// Needs the cargo feature `interactive` (on by default).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize), serde(transparent))]
pub struct GoalId(u32);

impl GoalId {
    /// Wraps a raw goal number.
    pub const fn new(raw: u32) -> Self {
        Self(raw)
    }

    /// Returns the raw goal number.
    pub const fn get(self) -> u32 {
        self.0
    }

    /// Returns the number as a `usize`.
    pub const fn index(self) -> usize {
        self.0 as usize
    }

    /// Returns the goal as the index of its inference in the session.
    const fn inf(self) -> InfId {
        InfId::new(self.0)
    }

    /// Returns the goal that an inference of the session is.
    const fn of(id: InfId) -> Self {
        Self(id.get())
    }
}

/// A step of a session: the rule applied to the formula at a position of
/// a goal, and the split a `⊗` or Mix needs.
///
/// Needs the cargo feature `interactive` (on by default).
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Step {
    /// The position of the formula in the goal's sequent.
    pub position: usize,
    /// The rule, by its classical name or, in intuitionistic mode, by its
    /// two-sided one.
    pub rule: Named,
    /// How the context is split between two premises.
    pub split: Split,
    /// The witness of an `∃R` or `∀L` step, open unless given.
    pub witness: Witness,
}

impl Step {
    /// Returns the step of `rule` on the formula at `position`, with no
    /// split and an open witness.
    pub fn new(position: usize, rule: impl Into<Named>) -> Self {
        Self {
            position,
            rule: rule.into(),
            split: Split::None,
            witness: Witness::Open,
        }
    }

    /// Returns the step with the witness given, for `∃R` or `∀L`.
    #[must_use]
    pub fn with_witness(self, witness: Witness) -> Self {
        Self { witness, ..self }
    }

    /// Returns the step with the formulas at `positions` sent to the left
    /// premise of a `⊗` or Mix, the rest to the right; for Mix the formula
    /// the step names goes left too.
    #[must_use]
    pub fn left(self, positions: &[usize]) -> Self {
        Self {
            split: Split::Left {
                positions: positions.to_vec(),
            },
            ..self
        }
    }

    /// Returns the step with the context split at a cut point of the
    /// goal's cyclic order, as an ordered mode reads it.
    ///
    /// Going round from the formula the step names, the formulas before
    /// `position` go to the right premise and those from `position` on to
    /// the left one. So `position` is the first formula going left, and the
    /// step's own position sends none left. In an ordered mode these are
    /// the only splits a `⊗` allows; in a commutative mode this is a split
    /// like any other.
    #[must_use]
    pub fn at(self, position: usize) -> Self {
        Self {
            split: Split::At { position },
            ..self
        }
    }

    /// Returns the positions going left in a goal of `len` formulas (none
    /// without a split), or refuses a cut point outside the goal.
    fn left_positions(&self, len: usize) -> Result<Vec<usize>, StepError> {
        match &self.split {
            Split::None => Ok(Vec::new()),
            Split::Left { positions } => Ok(positions.clone()),
            &Split::At { position } if position >= len => Err(StepError::Split { position }),
            // From the cut point round to the step's formula.
            &Split::At { position } => Ok((position..len)
                .chain(0..position)
                .take_while(|&p| p != self.position)
                .collect()),
        }
    }
}

/// How a step splits its goal's context between two premises.
///
/// Needs the cargo feature `interactive` (on by default).
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum Split {
    /// No split: the rule has one premise or none.
    #[default]
    None,
    /// The formulas at these positions go to the left premise, the rest to
    /// the right.
    #[non_exhaustive]
    Left {
        /// The positions in the goal's sequent.
        positions: Vec<usize>,
    },
    /// The goal's formulas from this position round to the step's formula
    /// go to the left premise, the others to the right ([`Step::at`]).
    #[non_exhaustive]
    At {
        /// The position of the first formula going left.
        position: usize,
    },
}

/// The term an `∃R` or `∀L` step puts for the bound variable: open, or a
/// closed term given.
///
/// An open witness is a placeholder (a metavariable) that a later axiom or
/// [`Interactive::close`] fills in.
///
/// Needs the cargo feature `interactive` (on by default).
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum Witness {
    /// Left open, as a metavariable. It may be filled only with terms of
    /// the eigenvariables made before it.
    #[default]
    Open,
    /// A closed term, given as a flat list of nodes. Each node is a
    /// function symbol of the sequent applied to nodes before it, or an
    /// eigenvariable in the goal's scope; the last node is the term.
    /// [`Interactive::witness`] reads one from text.
    Term(Vec<TermNode>),
}

/// A node of a witness term given flat ([`Witness::Term`]).
///
/// Needs the cargo feature `interactive` (on by default).
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TermNode {
    /// A function symbol of the sequent applied to earlier nodes, named by
    /// their index in the list, as many as its arity (none for a constant).
    App(Symbol, Vec<u32>),
    /// An eigenvariable of the session.
    Eigen(Eigen),
}

/// A rule that can act on a formula of a goal, and what a step of it needs
/// beyond the formula's position.
///
/// Needs the cargo feature `interactive` (on by default).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Applicable {
    /// The rule, named as the session records it.
    pub rule: Named,
    /// What the step needs.
    pub needs: Needs,
}

/// What [`Interactive::close`] did: the search's outcome, and whether the
/// derivation of the proof it found was grafted onto the goal.
///
/// Needs the cargo feature `interactive` (on by default).
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct Closed {
    /// The search's outcome. A proof in it proves the goal alone, and is
    /// there to export even when its graft was refused.
    pub outcome: Outcome,
    /// `Ok` when the proof was grafted or there was none to graft.
    /// Otherwise why the graft was refused (its size or the stop), and the
    /// goal is still open.
    pub grafted: Result<(), Refusal>,
}

/// What a step of a rule needs beyond the formula's position.
///
/// Needs the cargo feature `interactive` (on by default).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Needs {
    /// Nothing.
    Nothing,
    /// A split of the context between the two premises: `⊗` and Mix.
    Split,
    /// A witness for the bound variable, or none to leave it open: `∃R`
    /// and `∀L`.
    Witness,
}

/// A proof in progress: a derivation built step by step from its
/// conclusion, with the goals still open as its leaves.
///
/// A session starts with the sequent as its one open goal. Each step
/// applies a rule to a formula of a goal, named by its position
/// ([`apply`](Self::apply)); [`rules`](Self::rules) lists the rules that
/// act on a formula. The search can close a goal
/// ([`close`](Self::close)), and [`undo`](Self::undo) takes back the last
/// step (or keep a clone). Once no goal is open, [`proof`](Self::proof)
/// returns the proof, checked.
///
/// # Examples
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// use deduxit::linear::proofs::interactive::Needs;
/// use deduxit::{Limits, linear::{Interactive, Mode, Named, Rule, Sequent, Step}};
///
/// // ⊢ ~A, A ⊗ ~B, B: the goal's formulas are 0: ~A, 1: A ⊗ ~B, 2: B.
/// let sequent: Sequent = "A, A -o B |- B".parse()?;
/// let mut state = Interactive::new(&sequent, Mode::CLASSICAL)?;
/// let root = state.goals().next().unwrap();
/// let rules = state.rules(root, 1)?;
/// assert_eq!((rules[0].rule, rules[0].needs), (Named::from(Rule::Tensor), Needs::Split));
/// // ⊗ on formula 1, with formula 0 going to the left premise.
/// let goals = state.apply(root, &Step::new(1, Rule::Tensor).left(&[0]))?;
/// // Two goals are open: ⊢ ~A, A and ⊢ ~B, B.
/// assert_eq!(state.goals().collect::<Vec<_>>(), goals);
/// state.apply(goals[0], &Step::new(0, Rule::Ax))?;
/// state.apply(goals[1], &Step::new(0, Rule::Ax))?;
/// assert!(state.is_complete());
/// let proof = state.proof(&Limits::default(), |_| false)?;
/// assert_eq!(proof.nodes().len(), 3);
/// # Ok::<(), deduxit::Error>(())
/// ```
///
/// # JSON
///
/// With the feature `serialize`, a session is written as
/// `{"version": 1, "sequent": …, "mode": "intuitionistic", "inferences":
/// […], "history": […]}` ([`wire`](crate::wire)), the mode by its name.
///
/// - `inferences` are in the session's own order, the conclusion first.
///   Each is `{"sequent": [ids], "rule": name, "principal": position,
///   "premises": [indices]}`, with the rule's [`name`](Rule::name). An open
///   goal is its sequent alone.
/// - `history` lists the inferences the steps closed, in order.
/// - A session that keeps how its sequent was written
///   ([`writing`](Self::writing)) also has `"written": {"inputs": [ids],
///   "implications": [ids]}`: the occurrences written on the input side
///   and those written as an implication, ascending.
///
/// Reading a session back replays every inference, so a session read is
/// as sound as one built through [`apply`](Self::apply). A front end keeps
/// this between requests, and the command's session saves it.
///
/// Needs the cargo feature `interactive` (on by default).
#[derive(Clone, Debug)]
pub struct Interactive {
    /// The forest of the sequent being proved.
    forest: Forest,
    /// The mode.
    mode: Mode,
    /// In intuitionistic mode, the reading's sides and goal, kept so that
    /// [`reading`](Self::reading) takes constant time: computing it per
    /// call costs time linear in the sequent.
    reading: Option<(Box<[Side]>, OccId)>,
    /// How the sequent was written, for a session started from a
    /// classical sequent as written.
    writing: Option<Box<[Written]>>,
    /// The inferences, top-down: the root first, then the goals each step
    /// opened, in order. An open goal has [`Rule::Open`].
    inferences: Vec<Inference>,
    /// The goals the steps closed, in order, for undo.
    history: Vec<InfId>,
    /// For a sequent with quantifiers, the instances, eigenvariables and
    /// open witnesses of the steps.
    fo: Option<Box<Quantified>>,
}

impl Interactive {
    /// Starts a proof of the sequent in the mode, with the whole sequent as
    /// the one open goal.
    ///
    /// The sequent's cut formulas are left out: a session's cut formulas
    /// are those of its own cuts ([`cut`](Self::cut)), added as they are
    /// made.
    ///
    /// # Errors
    ///
    /// [`Error::NotIntuitionistic`] in intuitionistic mode for a sequent
    /// without an intuitionistic reading, [`Error::IntuitionisticMix`] for
    /// intuitionistic mode with Mix, [`Error::OrderedMode`] for a mode
    /// [`Mode::check`] refuses otherwise, [`Error::OrderedFragment`] in an
    /// ordered mode for a sequent beyond unit-free MLL, and
    /// [`Refusal::Occurrences`] past the default
    /// bound.
    pub fn new(sequent: &Sequent, mode: Mode) -> Result<Self, Error> {
        Self::within(sequent, mode, &Limits::default())
    }

    /// Starts a proof as [`new`](Self::new) does, within the caller's
    /// limits: the sequent may unfold to at most `limits.occurrences`
    /// occurrences, and the terms of a session with quantifiers are
    /// bounded by `limits.terms`.
    ///
    /// # Errors
    ///
    /// As [`new`](Self::new) does, the bound being `limits.occurrences`.
    pub fn within(sequent: &Sequent, mode: Mode, limits: &Limits) -> Result<Self, Error> {
        if !sequent.cuts().is_empty() {
            let mut conclusion = sequent.clone();
            while !conclusion.cuts().is_empty() {
                conclusion.pop_cut();
            }
            return Self::within(&conclusion, mode, limits);
        }
        let forest = Forest::within(sequent, limits)?;
        let mut state = Self::from_forest(forest, mode)?;
        if let Some(q) = state.fo.as_mut() {
            q.limit = limits.terms;
        }
        Ok(state)
    }

    /// Starts a proof over a forest built already.
    fn from_forest(forest: Forest, mode: Mode) -> Result<Self, Error> {
        mode.check()?;
        let fragment = forest.sequent().fragment();
        if mode.is_ordered() && !crate::linear::Fragment::MLL.contains(fragment) {
            return Err(Error::OrderedFragment { fragment, mode });
        }
        let reading = if mode.intuitionistic {
            let reading = Reading::of_mode(&forest, mode).map_err(Error::NotIntuitionistic)?;
            Some(reading.into_parts())
        } else {
            None
        };
        let root = Inference {
            sequent: forest.roots().iter().copied().map(Member::from).collect(),
            rule: Rule::Open.into(),
            principal: None,
            premises: vec![],
            times: 1,
            cut: None,
            node: None,
        };
        let fo = forest
            .has_binders()
            .then(|| Box::new(Quantified::new(&forest)));
        Ok(Self {
            forest,
            mode,
            reading,
            writing: None,
            inferences: vec![root],
            history: vec![],
            fo,
        })
    }

    /// Starts a proof as [`within`](Self::within) does, of a classical
    /// sequent as it was written. The session keeps how it was written
    /// ([`writing`](Self::writing)), so that its derivation can be drawn
    /// two-sided ([`TwoSided`](crate::linear::TwoSided)) at any point.
    ///
    /// # Errors
    ///
    /// As [`within`](Self::within) does.
    pub fn of_classical(
        sequent: &ClassicalSequent,
        mode: Mode,
        limits: &Limits,
    ) -> Result<Self, Error> {
        let mut state = Self::within(sequent.sequent(), mode, limits)?;
        state.writing = Some(sequent.writing().into());
        Ok(state)
    }

    /// Returns how the sequent was written, by occurrence, for a session
    /// started from a classical sequent as written, and `None` otherwise.
    pub fn writing(&self) -> Option<&[Written]> {
        self.writing.as_deref()
    }

    /// Returns the formula a member stands for as the session's sequent was
    /// written, its negation included (`A ⊸ B`, `~(A ⊗ B)`), and a cut
    /// formula as it was typed.
    ///
    /// Returns `None` for a session that does not keep how its sequent was
    /// written ([`writing`](Self::writing)), and for an instance of a
    /// formula under a binder.
    pub fn formula_as_written(&self, member: Member) -> Option<impl Display + '_> {
        use crate::linear::occurrences::written;
        let writing = self.writing.as_deref()?;
        // An instance has no record of how it was written.
        let o = member.occurrence(&self.forest)?;
        Some(written::Shown {
            forest: &self.forest,
            writing,
            o,
            negated: written::negated(&self.forest, writing, o),
        })
    }

    /// Keeps how the sequent was written, from a session read back, after
    /// checking that it fits the forest.
    #[cfg(feature = "serialize")]
    pub(crate) fn keep_writing(&mut self, writing: Box<[Written]>) -> Result<(), Error> {
        if let Some(reason) = crate::linear::occurrences::written::fault(&self.forest, &writing) {
            return Err(Error::InconsistentSession { reason });
        }
        self.writing = Some(writing);
        Ok(())
    }

    /// Returns the forest of the sequent being proved.
    pub fn forest(&self) -> &Forest {
        &self.forest
    }

    /// Returns the occurrence a member of the session stands for: the
    /// member itself below the forest's length, and the instance's
    /// occurrence past it.
    pub fn occurrence(&self, member: Member) -> OccId {
        match &self.fo {
            Some(fo) => fo.instance(member).0,
            None => member.occ(),
        }
    }

    /// Returns the formula a member of the session stands for, as text.
    ///
    /// In an intuitionistic mode the formula is written two-sided, as the
    /// session's reading has it (`A ⊸ B` for a hypothesis the one-sided
    /// sequent holds as `A ⊗ ~B`); otherwise one-sided. An instance has
    /// its terms in place of its bound variables, an eigenvariable is
    /// written by its letter, and an open witness as `$1`, `$2`, ….
    ///
    /// # Panics
    ///
    /// For a member past the forest that the session does not number. No
    /// goal of the session holds one.
    pub fn formula(&self, member: Member) -> impl Display + '_ {
        if let Some(fo) = &self.fo
            && member.index() >= self.forest.len()
        {
            let framing = crate::linear::occurrences::instances::Framing::new(
                &self.forest.sequent().fo,
                &fo.shown,
            );
            let mut text = String::new();
            crate::linear::sequents::notation::TEXT
                .instance(
                    &mut text,
                    &self.forest,
                    self.reading().as_ref(),
                    &framing,
                    member,
                    None,
                )
                .expect("writing into a string cannot fail");
            return text;
        }
        match self.reading() {
            Some(reading) => reading.formula(member.occ()).to_string(),
            None => self.forest.formula(member.occ()).to_string(),
        }
    }

    /// Returns the sequent being proved.
    pub fn sequent(&self) -> &Sequent {
        self.forest.sequent()
    }

    /// Returns the mode.
    pub fn mode(&self) -> Mode {
        self.mode
    }

    /// Returns the intuitionistic reading of the sequent in intuitionistic
    /// mode, and `None` in classical mode. The reading says on which side
    /// of `⊢` to show each formula.
    pub fn reading(&self) -> Option<Reading<'_>> {
        let (position, goal) = self.reading.as_ref()?;
        Some(Reading::of_parts(
            &self.forest,
            position,
            *goal,
            self.mode.is_ordered(),
        ))
    }

    /// Returns every inference, the root first and then in the order the
    /// steps opened them. An open goal is an inference with [`Rule::Open`].
    #[cfg(feature = "serialize")]
    pub(crate) fn inferences(&self) -> &[Inference] {
        &self.inferences
    }

    /// Returns the open goals, in the order they were opened.
    pub fn goals(&self) -> impl Iterator<Item = GoalId> + '_ {
        self.inferences
            .iter()
            .enumerate()
            .filter(|(_, inference)| inference.rule.rule == Rule::Open)
            .map(|(i, _)| GoalId(i as u32))
    }

    /// Returns the sequent of an open goal: its members, in ascending
    /// order. A step names a formula by its position here.
    ///
    /// # Errors
    ///
    /// [`StepError::NoGoal`] if the id is not an open goal.
    pub fn goal(&self, id: GoalId) -> Result<&[Member], StepError> {
        self.inferences
            .get(id.index())
            .filter(|inference| inference.rule.rule == Rule::Open)
            .map(|inference| inference.sequent.as_slice())
            .ok_or(StepError::NoGoal { goal: id })
    }

    /// Returns whether no goal is open.
    pub fn is_complete(&self) -> bool {
        self.goals().next().is_none()
    }

    /// Returns how many steps were taken (rules applied, cuts made and
    /// goals closed by the search), less those undone.
    pub fn steps(&self) -> usize {
        self.history.len()
    }

    /// Returns the goals the steps closed, in order.
    #[cfg(feature = "serialize")]
    pub(crate) fn history(&self) -> &[InfId] {
        &self.history
    }

    /// Returns the written form of the first-order part, for a sequent
    /// with quantifiers.
    #[cfg(feature = "serialize")]
    pub(crate) fn parts(&self) -> Option<Parts> {
        self.fo.as_ref().map(|q| q.parts(&self.forest))
    }

    /// Returns the derivation so far, two-sided in intuitionistic mode, with
    /// the open goals as leaves of [`Rule::Open`].
    ///
    /// The derivation numbers its inferences premises before conclusions,
    /// so its ids are not the session's;
    /// [`derivation_ids`](Self::derivation_ids) maps them.
    ///
    /// # Errors
    ///
    /// [`Refusal::Output`] for a derivation past the default
    /// [`Limits::derivation_bytes`].
    pub fn derivation(&self) -> Result<Derivation<'_>, Error> {
        self.derivation_within(&ViewOptions::default(), &Limits::default(), |_| false)
    }

    /// Returns the derivation so far as [`derivation`](Self::derivation)
    /// does, within the caller's limits and until `stop` fires.
    ///
    /// The size estimate decides, as for a proof's derivation, whether it
    /// fits `limits.derivation_bytes`. Its inferences are the session's
    /// own, never compacted, whatever `view` says.
    ///
    /// # Errors
    ///
    /// [`Refusal::Output`] past `limits.derivation_bytes`, and
    /// [`Refusal::Stopped`] when `stop` fired.
    pub fn derivation_within(
        &self,
        view: &ViewOptions,
        limits: &Limits,
        mut stop: impl FnMut(Progress) -> bool,
    ) -> Result<Derivation<'_>, Error> {
        let _ = view;
        // The size estimate's measure: the inferences and the characters
        // of their sequents.
        let weights =
            super::size::Weights::of_members(&self.forest, self.fo.as_ref().map(|q| &q.shown));
        let estimate = self.inferences.iter().fold(0u64, |sum, inference| {
            let characters = inference.sequent.iter().fold(0u64, |sum, m| {
                sum.saturating_add(u64::from(weights.get(*m)))
            });
            sum.saturating_add(Size::BYTES_PER_INFERENCE)
                .saturating_add(characters.saturating_mul(Size::BYTES_PER_CHARACTER))
        });
        if let Some(limit) = limits.derivation_bytes
            && estimate > limit
        {
            return Err(Error::Refused(Refusal::Output {
                what: "derivation",
                estimate_bytes: estimate,
                limit_bytes: limit,
                least_bytes: None,
            }));
        }
        if stop(Progress::new(Phase::View, 0, 0)) {
            return Err(Error::Refused(Refusal::Stopped { phase: Phase::View }));
        }
        let order = self.postorder();
        let mut new_id = vec![InfId::new(u32::MAX); self.inferences.len()];
        for (i, id) in order.iter().enumerate() {
            new_id[id.index()] = InfId::new(i as u32);
        }
        let inferences = order
            .iter()
            .map(|&id| {
                let inference = &self.inferences[id.index()];
                Inference {
                    sequent: inference.sequent.clone(),
                    rule: inference.rule,
                    principal: inference.principal,
                    cut: inference.cut,
                    node: None,
                    premises: inference
                        .premises
                        .iter()
                        .map(|&p| new_id[p.index()])
                        .collect(),
                    times: inference.times,
                }
            })
            .collect();
        let derivation =
            Derivation::from_parts(&self.forest, self.reading(), inferences, self.mode);
        Ok(match &self.fo {
            Some(q) => derivation.with_framing(&q.shown),
            None => derivation,
        })
    }

    /// Returns, for every inference of [`derivation`](Self::derivation) by
    /// its id, the id of the same inference in this session.
    ///
    /// It turns the inference `n` of a drawing (the SVG's `i<n>`) into the
    /// goal that [`apply`](Self::apply) and [`close`](Self::close) take.
    pub fn derivation_ids(&self) -> Vec<GoalId> {
        self.postorder().into_iter().map(GoalId::of).collect()
    }
}

#[cfg(all(test, feature = "parse"))]
mod tests {
    use super::*;
    use crate::linear::proofs::{Node, NodeId, Proof};
    use crate::linear::search::{self, Options, Reason, Verdict};

    /// Parses `input`.
    fn sequent(input: &str) -> Sequent {
        input.parse().unwrap_or_else(|e| panic!("{input:?}: {e}"))
    }

    /// Returns the rules of applicable steps.
    fn names(rules: Vec<Applicable>) -> Vec<Named> {
        rules.into_iter().map(|a| a.rule).collect()
    }

    /// Returns the rule named `name`.
    fn named(name: &str) -> Named {
        name.parse().unwrap()
    }

    /// Starts a proof of `input` in `mode` and returns it with its goal.
    fn start(input: &str, mode: Mode) -> (Interactive, GoalId) {
        let state = Interactive::new(&sequent(input), mode).unwrap();
        let goal = state.goals().next().unwrap();
        (state, goal)
    }

    /// A derivation forty thousand rules high becomes a proof term, and the
    /// term is checked, on a stack that a recursion over its height would
    /// overflow.
    #[test]
    fn a_high_derivation_needs_no_stack() {
        const DEPTH: usize = 20_000;
        let text = format!("|- {}1{}", "bot | (".repeat(DEPTH), ")".repeat(DEPTH));
        let proved = std::thread::Builder::new()
            .stack_size(256 * 1024)
            .spawn(move || {
                let (mut state, mut goal) = start(&text, Mode::CLASSICAL);
                for _ in 0..DEPTH {
                    goal = state.apply(goal, &Step::new(0, Rule::Par)).unwrap()[0];
                    goal = state.apply(goal, &Step::new(0, Rule::Bot)).unwrap()[0];
                }
                assert_eq!(state.apply(goal, &Step::new(0, Rule::One)).unwrap(), []);
                state
                    .proof(&Limits::default(), |_| false)
                    .unwrap()
                    .nodes()
                    .len()
            })
            .unwrap()
            .join()
            .unwrap();
        assert_eq!(proved, 2 * DEPTH + 1);
    }

    /// Returns the position in the goal of the first formula printed as
    /// `text`.
    fn at(state: &Interactive, goal: GoalId, text: &str) -> usize {
        let sequent = state.goal(goal).unwrap();
        sequent
            .iter()
            .position(|&o| state.forest().formula(o.occ()).to_string() == text)
            .unwrap_or_else(|| panic!("no {text} in goal {}", goal.get()))
    }

    /// Applies `rule` to the formula printed as `text` and returns the
    /// goals opened.
    fn step(
        state: &mut Interactive,
        goal: GoalId,
        text: &str,
        rule: Rule,
        left: &[&str],
    ) -> Vec<GoalId> {
        let position = at(state, goal, text);
        let left: Vec<usize> = left.iter().map(|t| at(state, goal, t)).collect();
        state
            .apply(goal, &Step::new(position, rule).left(&left))
            .unwrap_or_else(|e| panic!("{rule} on {text}: {e}"))
    }

    /// Every rule applied once through the interface, in a proof the
    /// checker accepts, per fragment and mode.
    #[test]
    fn every_rule_once() {
        use Rule::*;
        let classical = Mode::CLASSICAL;
        // ⅋, ⊗ with a split, ax.
        let (mut s, g) = start("|- ~a par ~b, a * b", classical);
        let [g] = step(&mut s, g, "~a ⅋ ~b", Par, &[])[..] else {
            panic!()
        };
        let [l, r] = step(&mut s, g, "a ⊗ b", Tensor, &["~a"])[..] else {
            panic!()
        };
        assert_eq!(s.goals().collect::<Vec<_>>(), [l, r]);
        step(&mut s, l, "a", Ax, &[]);
        assert_eq!(names(s.rules(r, 0).unwrap()), [Named::from(Ax)]);
        step(&mut s, r, "b", Ax, &[]);
        assert!(s.is_complete());
        let proof = s.proof(&Limits::default(), |_| false).unwrap();
        assert_eq!(proof.nodes().len(), 4);
        assert_eq!(
            s.derivation().unwrap().to_string(),
            proof.derivation().unwrap().to_string()
        );
        // ⊥ and 1.
        let (mut s, g) = start("|- bot, 1", classical);
        let [g] = step(&mut s, g, "⊥", Bot, &[])[..] else {
            panic!()
        };
        step(&mut s, g, "1", One, &[]);
        s.proof(&Limits::default(), |_| false).unwrap();
        // &, ⊕₁, ⊕₂ and ⊤.
        let (mut s, g) = start("|- a & b, ~a + ~b", classical);
        let [l, r] = step(&mut s, g, "a & b", With, &[])[..] else {
            panic!()
        };
        let [l] = step(&mut s, l, "~a ⊕ ~b", PlusLeft, &[])[..] else {
            panic!()
        };
        step(&mut s, l, "a", Ax, &[]);
        let [r] = step(&mut s, r, "~a ⊕ ~b", PlusRight, &[])[..] else {
            panic!()
        };
        step(&mut s, r, "~b", Ax, &[]);
        s.proof(&Limits::default(), |_| false).unwrap();
        let (mut s, g) = start("|- top, 0", classical);
        assert_eq!(names(s.rules(g, at(&s, g, "0")).unwrap()), []);
        step(&mut s, g, "⊤", Top, &[]);
        s.proof(&Limits::default(), |_| false).unwrap();
        // ?c, ?d, ! and ?w.
        let (mut s, g) = start("!a |- a * a", classical);
        let [g] = step(&mut s, g, "?~a", Contraction, &[])[..] else {
            panic!()
        };
        let [l, r] = step(&mut s, g, "a ⊗ a", Tensor, &["?~a"])[..] else {
            panic!()
        };
        for g in [l, r] {
            let [g] = step(&mut s, g, "?~a", Dereliction, &[])[..] else {
                panic!()
            };
            step(&mut s, g, "~a", Ax, &[]);
        }
        let proof = s.proof(&Limits::default(), |_| false).unwrap();
        assert_eq!(
            proof.derivation().unwrap().to_string(),
            "─────── ax    ─────── ax\n\
             ⊢ ~a, a       ⊢ ~a, a\n\
             ──────── ?d   ──────── ?d\n\
             ⊢ ?~a, a      ⊢ ?~a, a\n\
             ────────────────────── ⊗\n\
            \x20 ⊢ ?~a, ?~a, a ⊗ a\n\
            \x20 ───────────────── ?c\n\
            \x20   ⊢ ?~a, a ⊗ a"
        );
        let (mut s, g) = start("!a |- !a", classical);
        let [g] = step(&mut s, g, "!a", Promotion, &[])[..] else {
            panic!()
        };
        let [g] = step(&mut s, g, "?~a", Dereliction, &[])[..] else {
            panic!()
        };
        step(&mut s, g, "~a", Ax, &[]);
        s.proof(&Limits::default(), |_| false).unwrap();
        let (mut s, g) = start("|- ?a, 1", classical);
        let [g] = step(&mut s, g, "?a", Weakening, &[])[..] else {
            panic!()
        };
        step(&mut s, g, "1", One, &[]);
        s.proof(&Limits::default(), |_| false).unwrap();
        // wk in affine mode, and Mix.
        let (mut s, g) = start("a, b |- a", classical.with_affine());
        assert_eq!(
            names(s.rules(g, at(&s, g, "~b")).unwrap()),
            [Named::from(Ax), Named::from(AffineWeakening)]
        );
        let [g] = step(&mut s, g, "~b", AffineWeakening, &[])[..] else {
            panic!()
        };
        step(&mut s, g, "~a", Ax, &[]);
        s.proof(&Limits::default(), |_| false).unwrap();
        let (mut s, g) = start("|- a, ~a, b, ~b", classical.with_mix());
        assert_eq!(
            names(s.rules(g, 0).unwrap()),
            [Named::from(Ax), Named::from(Mix)]
        );
        let [l, r] = step(&mut s, g, "a", Mix, &["~a"])[..] else {
            panic!()
        };
        step(&mut s, l, "a", Ax, &[]);
        step(&mut s, r, "b", Ax, &[]);
        assert_eq!(s.steps(), 3);
        s.proof(&Limits::default(), |_| false).unwrap();
    }

    /// A rule that does not apply is refused with what it needed, and the
    /// state is unchanged.
    #[test]
    fn rejections() {
        use Rule::*;
        let (mut s, g) = start("|- ~a par ~b, a * b, 1, !c, ?d, top", Mode::CLASSICAL);
        let before = s.clone();
        let p = |s: &Interactive, text: &str| at(s, g, text);
        let cases: Vec<(&str, Named, Vec<usize>, StepError)> = vec![
            (
                "~a ⅋ ~b",
                Named::from(Tensor),
                vec![],
                StepError::Rule {
                    rule: Named::from(Tensor),
                    position: p(&s, "~a ⅋ ~b"),
                    formula: "~a ⅋ ~b".into(),
                },
            ),
            (
                "1",
                Named::from(AffineWeakening),
                vec![],
                StepError::Mode {
                    rule: Named::from(AffineWeakening),
                    mode: Mode::CLASSICAL,
                },
            ),
            (
                "1",
                Named::from(Mix),
                vec![],
                StepError::Mode {
                    rule: Named::from(Mix),
                    mode: Mode::CLASSICAL,
                },
            ),
            (
                "1",
                Named::from(One),
                vec![],
                StepError::NotAlone {
                    rule: Named::from(One),
                    position: p(&s, "1"),
                },
            ),
            (
                "!c",
                Named::from(Promotion),
                vec![],
                StepError::NotQuest { position: 0 },
            ),
            (
                "~a ⅋ ~b",
                Named::from(Par),
                vec![1],
                StepError::NoSplit {
                    rule: Named::from(Par),
                },
            ),
            (
                "a ⊗ b",
                Named::from(Tensor),
                vec![9],
                StepError::Split { position: 9 },
            ),
            (
                "a ⊗ b",
                Named::from(Tensor),
                vec![0, 0],
                StepError::Split { position: 0 },
            ),
            (
                "a ⊗ b",
                Named::from(Tensor),
                vec![p(&s, "a ⊗ b")],
                StepError::Split {
                    position: p(&s, "a ⊗ b"),
                },
            ),
            (
                "1",
                named("⊸L"),
                vec![],
                StepError::Rule {
                    rule: named("⊸L"),
                    position: p(&s, "1"),
                    formula: "1".into(),
                },
            ),
        ];
        for (text, rule, left, refusal) in cases {
            let position = p(&s, text);
            assert_eq!(
                s.apply(g, &Step::new(position, rule).left(&left)),
                Err(refusal),
                "{rule} on {text}"
            );
        }
        assert_eq!(
            s.apply(g, &Step::new(99, Par)),
            Err(StepError::NoFormula {
                position: 99,
                len: 6
            })
        );
        assert_eq!(
            s.apply(GoalId::new(7), &Step::new(0, Par)),
            Err(StepError::NoGoal {
                goal: GoalId::new(7)
            })
        );
        assert_eq!(
            s.rules(GoalId::new(7), 0),
            Err(StepError::NoGoal {
                goal: GoalId::new(7)
            })
        );
        assert_eq!(s.inferences(), before.inferences());
        assert_eq!(s.steps(), 0);
        // The axiom needs the dual and nothing else.
        let (mut s, g) = start("|- a, ~a, b", Mode::CLASSICAL);
        assert_eq!(
            s.apply(g, &Step::new(0, Ax)),
            Err(StepError::NotAlone {
                rule: Named::from(Ax),
                position: 0
            })
        );
        let (mut s, g) = start("|- a, b", Mode::CLASSICAL);
        assert_eq!(
            s.apply(g, &Step::new(0, Ax)),
            Err(StepError::NoDual { position: 0 })
        );
        assert_eq!(
            s.apply(g, &Step::new(0, Ax)).unwrap_err().to_string(),
            "the axiom needs formula 0 together with its dual literal and nothing else"
        );
        // Intuitionistic mode: one goal per premise, the goal never weakened,
        // and the two-sided names.
        let i = Mode::INTUITIONISTIC;
        let (mut s, g) = start("a, a -o b |- b", i);
        let imp = at(&s, g, "a ⊗ ~b");
        assert_eq!(names(s.rules(g, imp).unwrap()), [named("⊸L")]);
        assert_eq!(
            s.apply(g, &Step::new(imp, named("⊗R"))),
            Err(StepError::Rule {
                rule: named("⊗R"),
                position: imp,
                formula: "a ⊸ b".into(),
            })
        );
        // The goal b with the antecedent a: two on the right.
        let b = at(&s, g, "b");
        assert_eq!(
            s.apply(g, &Step::new(imp, named("⊸L")).left(&[b])),
            Err(StepError::Succedents { count: 2 })
        );
        let (mut s, g) = start("a, b |- a", i.with_affine());
        let goal = at(&s, g, "a");
        assert_eq!(
            s.apply(g, &Step::new(goal, AffineWeakening)),
            Err(StepError::Output { position: goal })
        );
        assert!(Interactive::new(&sequent("|- a par b"), i).is_err());
        assert!(matches!(
            Interactive::new(&sequent("a |- a"), i.with_mix()),
            Err(Error::IntuitionisticMix)
        ));
    }

    /// In intuitionistic mode the rules carry their two-sided names, the
    /// classical name is accepted, and the derivation is the two-sided one.
    #[test]
    fn intuitionistic() {
        use Rule::*;
        let i = Mode::INTUITIONISTIC;
        let (mut s, g) = start("a, a -o b |- b", i);
        let imp = at(&s, g, "a ⊗ ~b");
        let a = at(&s, g, "~a");
        let [l, r] = s.apply(g, &Step::new(imp, Tensor).left(&[a])).unwrap()[..] else {
            panic!()
        };
        assert_eq!(s.inferences()[g.index()].rule, named("⊸L"));
        assert_eq!(
            s.derivation().unwrap().to_string(),
            "a ⊢ a   b ⊢ b\n\
             ───────────── ⊸L\n\
             a, a ⊸ b ⊢ b"
        );
        s.apply(l, &Step::new(0, Ax)).unwrap();
        s.apply(r, &Step::new(0, Ax)).unwrap();
        let proof = s.proof(&Limits::default(), |_| false).unwrap();
        assert_eq!(proof.check(i), Ok(()));
        assert_eq!(
            s.derivation().unwrap().to_string(),
            proof.two_sided().unwrap().to_string()
        );
        // !L, !c and !R by their two-sided names.
        let (mut s, g) = start("!a |- !(a * a)", i);
        let [g] = s
            .apply(g, &Step::new(at(&s, g, "!(a ⊗ a)"), named("!R")))
            .unwrap()[..]
        else {
            panic!()
        };
        let [g] = s
            .apply(g, &Step::new(at(&s, g, "?~a"), named("!c")))
            .unwrap()[..]
        else {
            panic!()
        };
        assert_eq!(
            names(s.rules(g, at(&s, g, "?~a")).unwrap()),
            [named("!L"), named("!c"), named("!w")]
        );
        let [l, r] = s
            .apply(
                g,
                &Step::new(at(&s, g, "a ⊗ a"), named("⊗R")).left(&[at(&s, g, "?~a")]),
            )
            .unwrap()[..]
        else {
            panic!()
        };
        for g in [l, r] {
            let [g] = s
                .apply(g, &Step::new(at(&s, g, "?~a"), named("!L")))
                .unwrap()[..]
            else {
                panic!()
            };
            s.apply(g, &Step::new(0, Ax)).unwrap();
        }
        assert_eq!(
            s.proof(&Limits::default(), |_| false).unwrap().check(i),
            Ok(())
        );
    }

    /// The search closes a goal that repeats an occurrence, as a
    /// contraction leaves it, and in affine mode goals that need a
    /// weakening; every proof the session ends with passes the checker.
    #[test]
    fn search_closes_repeated_and_affine_goals() {
        use Rule::*;
        let close_all = |s: &mut Interactive| {
            let outcomes = s.close_all(
                &Options::default(),
                &ViewOptions::default(),
                &Limits::default(),
                |_| false,
            );
            assert!(s.is_complete(), "{outcomes:?}");
            s.proof(&Limits::default(), |_| false).unwrap()
        };
        let (mut s, g) = start("|- ?(a par ~a)", Mode::CLASSICAL);
        let [repeated] = step(&mut s, g, "?(a ⅋ ~a)", Contraction, &[])[..] else {
            panic!()
        };
        assert_eq!(s.goal(repeated).unwrap().len(), 2);
        assert_eq!(close_all(&mut s).check(Mode::CLASSICAL), Ok(()));
        let affine = Mode::CLASSICAL.with_affine();
        let (mut s, g) = start("|- a * b, ~a, ~b, c", affine);
        step(&mut s, g, "a ⊗ b", Tensor, &["~a"]);
        assert_eq!(close_all(&mut s).check(affine), Ok(()));
    }

    /// The search closes one goal or every goal, grafting its derivation,
    /// and the result passes the checker; an unprovable goal stays open.
    #[test]
    fn search_closes_goals() {
        use Rule::*;
        let options = Options::default();
        let (mut s, g) = start("|- (a & b) * c, ~a + ~b, ~c", Mode::CLASSICAL);
        let t = at(&s, g, "(a & b) ⊗ c");
        let [l, r] = s
            .apply(g, &Step::new(t, Tensor).left(&[at(&s, g, "~a ⊕ ~b")]))
            .unwrap()[..]
        else {
            panic!()
        };
        let outcome = s
            .close(
                l,
                &options,
                &ViewOptions::default(),
                &crate::Limits::default(),
                |_| false,
            )
            .unwrap()
            .outcome;
        assert!(matches!(outcome.verdict, Verdict::Proved(_)));
        assert_eq!(outcome.engine, crate::linear::search::Engine::Additive);
        assert_eq!(s.goals().collect::<Vec<_>>(), [r]);
        assert_eq!(s.steps(), 2);
        let outcomes = s.close_all(
            &options,
            &ViewOptions::default(),
            &crate::Limits::default(),
            |_| false,
        );
        assert_eq!(outcomes.len(), 1);
        assert_eq!(outcomes[0].0, r);
        assert!(s.is_complete());
        let proof = s.proof(&Limits::default(), |_| false).unwrap();
        assert_eq!(proof.check(Mode::CLASSICAL), Ok(()));
        assert!(s.derivation().unwrap().to_string().contains("⊕₂"));

        // An unprovable goal stays open, a stopped search too.
        let (mut s, g) = start("|- a * b, ~a, ~b", Mode::CLASSICAL);
        let [l, r] = s
            .apply(
                g,
                &Step::new(at(&s, g, "a ⊗ b"), Tensor).left(&[at(&s, g, "~b")]),
            )
            .unwrap()[..]
        else {
            panic!()
        };
        let outcome = s
            .close(
                l,
                &options,
                &ViewOptions::default(),
                &crate::Limits::default(),
                |_| false,
            )
            .unwrap()
            .outcome;
        assert!(matches!(outcome.verdict, Verdict::Unprovable(_)));
        let outcome = s
            .close(
                r,
                &options,
                &ViewOptions::default(),
                &crate::Limits::default(),
                |_| true,
            )
            .unwrap()
            .outcome;
        assert!(matches!(outcome.verdict, Verdict::Unknown(Reason::Stopped)));
        assert_eq!(s.goals().collect::<Vec<_>>(), [l, r]);
        assert!(matches!(
            s.proof(&Limits::default(), |_| false),
            Err(Error::OpenGoals { count: 2 })
        ));
        assert!(matches!(
            s.close(
                g,
                &options,
                &ViewOptions::default(),
                &crate::Limits::default(),
                |_| false
            ),
            Err(Error::Step(StepError::NoGoal { .. }))
        ));

        // Two-sided: the grafted derivation carries the two-sided names.
        let (mut s, g) = start("a & b, !(a -o c) |- c", Mode::INTUITIONISTIC);
        let [g] = s
            .apply(g, &Step::new(at(&s, g, "~a ⊕ ~b"), named("&L₁")))
            .unwrap()[..]
        else {
            panic!()
        };
        let outcome = s
            .close(
                g,
                &options,
                &ViewOptions::default(),
                &crate::Limits::default(),
                |_| false,
            )
            .unwrap()
            .outcome;
        assert!(matches!(outcome.verdict, Verdict::Proved(_)));
        assert!(s.derivation().unwrap().to_string().contains("!L"));
        assert_eq!(
            s.proof(&Limits::default(), |_| false)
                .unwrap()
                .check(Mode::INTUITIONISTIC),
            Ok(())
        );
    }

    /// In the cyclic mode a `⊗` splits its goal into the two arcs on
    /// either side of it, at a cut point or by positions that make arcs,
    /// any other split needing an exchange; the search closes a goal off
    /// the roots; and a sequent beyond unit-free MLL has no session.
    #[test]
    fn cyclic() {
        let cyclic = Mode::CYCLIC;
        // 0 ⊗, 1 a ⊗ b, 2 a, 3 b, 4 c, 5 ~c, 6 ~b, 7 ~a.
        let (mut s, g) = start("|- (a * b) * c, ~c, ~b, ~a", cyclic);
        assert_eq!(
            s.apply(g, &Step::new(0, Rule::Tensor).left(&[1])),
            Err(StepError::Exchange { position: 1 })
        );
        let goals = s.apply(g, &Step::new(0, Rule::Tensor).at(2)).unwrap();
        let (left, right) = (goals[0], goals[1]);
        let members = |s: &Interactive, g| {
            s.goal(g)
                .unwrap()
                .iter()
                .map(|m| m.get())
                .collect::<Vec<_>>()
        };
        assert_eq!(
            (members(&s, left), members(&s, right)),
            (vec![1, 6, 7], vec![4, 5])
        );
        s.apply(right, &Step::new(0, Rule::Ax)).unwrap();
        let options = Options::default();
        let closed = s
            .close(
                left,
                &options,
                &ViewOptions::default(),
                &Limits::default(),
                |_| false,
            )
            .unwrap();
        assert!(matches!(closed.outcome.verdict, Verdict::Proved(_)) && closed.grafted.is_ok());
        assert_eq!(s.goals().count(), 0);
        let proof = s.proof(&Limits::default(), |_| false).unwrap();
        assert_eq!(proof.check(cyclic), Ok(()));
        // The step's own position as the cut point sends nothing left.
        let (mut s, g) = start("|- a * (~a par b), ~b", cyclic);
        let goals = s.apply(g, &Step::new(0, Rule::Tensor).at(0)).unwrap();
        assert_eq!(members(&s, goals[0]), [1]);
        assert!(matches!(
            Interactive::new(&sequent("|- a & b, ~a"), cyclic),
            Err(Error::OrderedFragment { .. })
        ));
    }

    /// In the Lambek calculus a rule on a division is named by it, a split
    /// that would leave a premise without a hypothesis is refused unless
    /// empty antecedents are allowed, and the search closes a goal off the
    /// roots in the order.
    #[test]
    fn lambek() {
        let ordered = |input: &str| {
            Sequent::parse_ordered(input, crate::linear::Order::Cyclic, &Limits::default()).unwrap()
        };
        let lambek = Mode::LAMBEK;
        // 0 ~a, 1 a ⊗ ~b, 2 a, 3 ~b, 4 b: b / a, a ⊢ b.
        let mut s = Interactive::new(&ordered("b / a, a |- b"), lambek).unwrap();
        let g = s.goals().next().unwrap();
        let slash = "/L".parse::<Named>().unwrap();
        assert_eq!(names(s.rules(g, 1).unwrap()), [slash]);
        assert!(matches!(
            s.apply(g, &Step::new(1, "⊸L".parse::<Named>().unwrap()).at(0)),
            Err(StepError::Rule { .. })
        ));
        let goals = s.apply(g, &Step::new(1, slash).at(0)).unwrap();
        assert_eq!(
            goals
                .iter()
                .map(|&g| s.goal(g).unwrap().len())
                .collect::<Vec<_>>(),
            [2, 2]
        );
        s.apply(goals[0], &Step::new(0, Rule::Ax)).unwrap();
        let options = Options::default();
        let closed = s
            .close(
                goals[1],
                &options,
                &ViewOptions::default(),
                &Limits::default(),
                |_| false,
            )
            .unwrap();
        assert!(matches!(closed.outcome.verdict, Verdict::Proved(_)) && closed.grafted.is_ok());
        let proof = s.proof(&Limits::default(), |_| false).unwrap();
        assert_eq!(proof.check(lambek), Ok(()));
        assert_eq!(
            s.derivation().unwrap().to_string(),
            "───── ax   ───── ax\n\
             a ⊢ a      b ⊢ b\n\
             ──────────────── /L\n  \
             b / a, a ⊢ b"
        );
        // 0 ~e, 1 e ⊗ (~a ⅋ a), 2 e, 3 ~a ⅋ a, 4 ~a, 5 a: e ⊢ e ⊗ (a \ a),
        // whose `⊗R` leaves ⊢ a \ a without a hypothesis.
        let sequent = ordered("e |- e * (a \\ a)");
        let step = Step::new(1, Rule::Tensor).at(0);
        let (mut s, mut star) = (
            Interactive::new(&sequent, lambek).unwrap(),
            Interactive::new(&sequent, lambek.with_empty_antecedents()).unwrap(),
        );
        let (g, h) = (s.goals().next().unwrap(), star.goals().next().unwrap());
        assert_eq!(s.apply(g, &step), Err(StepError::EmptyAntecedent));
        assert_eq!(star.apply(h, &step).map(|goals| goals.len()), Ok(2));
        assert!(matches!(
            Interactive::new(&ordered("|- a \\ a"), lambek),
            Err(Error::NotIntuitionistic(_))
        ));
    }

    /// A proof of an equal sequent made elsewhere fills a goal, its
    /// conclusions in another order. A proof of other formulas is refused,
    /// saying which on each side; the checker refuses one of another mode's
    /// rules; and a member outside the forest is refused. Each refusal
    /// leaves the goal open.
    #[test]
    fn fill_carries_a_proof_of_an_equal_sequent() {
        let (view, limits) = (ViewOptions::default(), Limits::default());
        let proof_of = |input: &str, mode: Mode| {
            let outcome = search::prove(&sequent(input), mode, &Options::default()).unwrap();
            let Verdict::Proved(proof) = outcome.verdict else {
                panic!("{input}: {:?}", outcome.verdict)
            };
            proof
        };
        let after_par = || {
            let (mut s, g) = start("A * B |- B * A", Mode::CLASSICAL);
            let par = at(&s, g, "~A ⅋ ~B");
            let goal = s.apply(g, &Step::new(par, Rule::Par)).unwrap()[0];
            (s, goal)
        };
        let (mut s, goal) = after_par();
        let elsewhere = proof_of("|- B * A, ~A, ~B", Mode::CLASSICAL);
        s.fill(goal, &elsewhere, &view, &limits, |_| false).unwrap();
        assert!(s.is_complete());
        s.proof(&limits, |_| false).unwrap();

        let (mut s, goal) = after_par();
        let other = proof_of("|- A * B, ~A, ~B", Mode::CLASSICAL);
        let refused = s.fill(goal, &other, &view, &limits, |_| false).unwrap_err();
        let Error::SequentMismatch { proof, goal: held } = &refused else {
            panic!("{refused:?}")
        };
        assert_eq!(
            (proof, held),
            (&vec!["A ⊗ B".to_owned()], &vec!["B ⊗ A".to_owned()])
        );
        assert_eq!(refused.code(), "sequent_mismatch");
        let fewer = proof_of("|- ~A, A", Mode::CLASSICAL);
        let refused = s.fill(goal, &fewer, &view, &limits, |_| false).unwrap_err();
        let Error::SequentMismatch { proof, goal: held } = &refused else {
            panic!("{refused:?}")
        };
        assert_eq!((proof.len(), held.len()), (1, 2), "{refused}");
        assert_eq!(s.goals().collect::<Vec<_>>(), [goal]);

        let (mut s, g) = start("|- A, ~A, B, ~B", Mode::CLASSICAL);
        let mixed = proof_of("|- B, ~B, A, ~A", Mode::CLASSICAL.with_mix());
        assert!(matches!(
            s.fill(g, &mixed, &view, &limits, |_| false),
            Err(Error::Check(crate::linear::proofs::CheckError::Invalid(_)))
        ));
        assert_eq!(s.goals().collect::<Vec<_>>(), [g]);
        let past = Member::new(u32::try_from(s.forest().len()).unwrap());
        assert!(matches!(
            mixed.onto(s.forest().clone(), &[past]),
            Err(Error::IndexOutOfBounds { .. })
        ));
    }

    /// A goal is closed only by a proof over the session's sequent that
    /// passes the checker in the session's mode. A proof of another
    /// sequent, larger or smaller, a weakening in a linear session and a
    /// proof of another goal are refused, and the session stays as it was.
    #[test]
    fn close_with_refuses_a_foreign_proof() {
        let view = ViewOptions::default();
        let (mut s, g) = start("A, A -o B |- B", Mode::CLASSICAL);
        for other in ["|- A, B, C, D, top", "|- top"] {
            let forest = Forest::new(&sequent(other)).unwrap();
            let top = *forest.roots().last().unwrap();
            let proof =
                Proof::new(forest, vec![Node::Top(Member::from(top))], NodeId::new(0)).unwrap();
            assert!(matches!(
                s.close_with(g, &proof, &view, &crate::Limits::default(), |_| false),
                Err(Error::ForeignProof)
            ));
        }
        assert_eq!(s.goals().collect::<Vec<_>>(), [g]);

        let (mut s, g) = start("A, B |- A", Mode::CLASSICAL);
        let affine = search::prove_goal(
            search::Goal::new(s.forest(), s.goal(g).unwrap()).unwrap(),
            Mode::CLASSICAL.with_affine(),
            &Options::default(),
            &Limits::default(),
            |_| false,
        )
        .unwrap();
        let Verdict::Proved(proof) = affine.verdict else {
            panic!("{:?}", affine.verdict)
        };
        assert!(matches!(
            s.close_with(g, &proof, &view, &crate::Limits::default(), |_| false),
            Err(Error::Check(crate::linear::proofs::CheckError::Invalid(_)))
        ));
        assert_eq!(s.goals().collect::<Vec<_>>(), [g]);

        // A proof of the sequent closes the root's goal and no other.
        let (mut s, g) = start("A, B |- A * B", Mode::CLASSICAL);
        let outcome = search::prove(s.sequent(), Mode::CLASSICAL, &Options::default()).unwrap();
        let Verdict::Proved(whole) = outcome.verdict else {
            panic!("{:?}", outcome.verdict)
        };
        let tensor = at(&s, g, "A ⊗ B");
        let premises = s
            .apply(g, &Step::new(tensor, Rule::Tensor).left(&[at(&s, g, "~A")]))
            .unwrap();
        assert!(matches!(
            s.close_with(premises[0], &whole, &view, &Limits::default(), |_| false),
            Err(Error::GoalMismatch)
        ));
    }

    /// `split_passes` says which splits the focused engine's counts
    /// refuse.
    #[test]
    fn split_helper() {
        let (s, g) = start("|- a * b, ~a, ~b", Mode::CLASSICAL);
        let t = at(&s, g, "a ⊗ b");
        assert!(
            s.split_passes(g, &Step::new(t, Rule::Tensor).left(&[at(&s, g, "~a")]))
                .unwrap()
        );
        assert!(
            !s.split_passes(g, &Step::new(t, Rule::Tensor).left(&[at(&s, g, "~b")]))
                .unwrap()
        );
        assert!(
            !s.split_passes(g, &Step::new(t, Rule::Tensor).left(&[]))
                .unwrap()
        );
        assert_eq!(
            s.split_passes(g, &Step::new(t, Rule::Tensor).left(&[t])),
            Err(StepError::Split { position: t })
        );
        let (s, g) = start("|- a, ~a, b, ~b", Mode::CLASSICAL.with_mix());
        assert!(
            s.split_passes(g, &Step::new(0, Rule::Tensor).left(&[at(&s, g, "~a")]))
                .unwrap()
        );
        assert!(
            !s.split_passes(g, &Step::new(0, Rule::Tensor).left(&[at(&s, g, "b")]))
                .unwrap()
        );
    }

    /// Undo retracts a rule application and a grafted search alike,
    /// restoring the goals, and there is nothing to undo at the start.
    #[test]
    fn undo_restores_goals() {
        use Rule::*;
        let (mut s, g) = start("|- ~a par ~b, a * b", Mode::CLASSICAL);
        assert_eq!(s.undo(), None);
        let start_state = s.clone();
        let [g1] = s.apply(g, &Step::new(at(&s, g, "~a ⅋ ~b"), Par)).unwrap()[..] else {
            panic!()
        };
        let after_par = s.clone();
        let [l, _] = s
            .apply(
                g1,
                &Step::new(at(&s, g1, "a ⊗ b"), Tensor).left(&[at(&s, g1, "~a")]),
            )
            .unwrap()[..]
        else {
            panic!()
        };
        s.close(
            l,
            &Options::default(),
            &ViewOptions::default(),
            &crate::Limits::default(),
            |_| false,
        )
        .unwrap();
        assert_eq!(s.undo(), Some(l));
        assert_eq!(s.goals().count(), 2);
        assert_eq!(s.undo(), Some(g1));
        assert_eq!(s.inferences(), after_par.inferences());
        assert_eq!(s.undo(), Some(g));
        assert_eq!(s.inferences(), start_state.inferences());
        assert_eq!(s.undo(), None);
        let outcome = s
            .close(
                g,
                &Options::default(),
                &ViewOptions::default(),
                &crate::Limits::default(),
                |_| false,
            )
            .unwrap()
            .outcome;
        assert!(matches!(outcome.verdict, Verdict::Proved(_)));
        assert!(s.is_complete());
        assert_eq!(s.undo(), Some(g));
        assert_eq!(s.inferences(), start_state.inferences());
    }

    /// The derivation of a proof in progress draws open goals as bare
    /// sequents.
    #[test]
    fn open_goals_render() {
        use Rule::*;
        let (mut s, g) = start("|- ~a par ~b, a * b", Mode::CLASSICAL);
        let [g] = s.apply(g, &Step::new(at(&s, g, "~a ⅋ ~b"), Par)).unwrap()[..] else {
            panic!()
        };
        s.apply(
            g,
            &Step::new(at(&s, g, "a ⊗ b"), Tensor).left(&[at(&s, g, "~a")]),
        )
        .unwrap();
        assert_eq!(
            s.derivation().unwrap().to_string(),
            "⊢ ~a, a   ⊢ ~b, b\n\
             ───────────────── ⊗\n\
            \x20⊢ ~a, ~b, a ⊗ b\n\
            \x20──────────────── ⅋\n\
            \x20⊢ ~a ⅋ ~b, a ⊗ b"
        );
        let d = s.derivation().unwrap();
        assert_eq!(d.inference(d.root()).rule, Named::from(Par));
        assert_eq!(d.inference(InfId::new(0)).rule, Named::from(Open));
    }

    /// Mix on a goal that repeats the formula it is applied at keeps both
    /// copies.
    #[test]
    fn mix_keeps_repeated_formulas() {
        use Rule::*;
        let (mut s, g) = start("|- ?(a par ~a)", Mode::CLASSICAL.with_mix());
        let [g] = step(&mut s, g, "?(a ⅋ ~a)", Contraction, &[])[..] else {
            panic!()
        };
        let [g] = step(&mut s, g, "?(a ⅋ ~a)", Dereliction, &[])[..] else {
            panic!()
        };
        let [g] = step(&mut s, g, "?(a ⅋ ~a)", Dereliction, &[])[..] else {
            panic!()
        };
        let [l, r] = step(&mut s, g, "a ⅋ ~a", Mix, &[])[..] else {
            panic!()
        };
        assert_eq!(s.goal(l), s.goal(r));
        // A Mix of the goal's one formula: the right premise would be
        // empty, which nothing closes.
        assert_eq!(s.goal(l).map(<[Member]>::len), Ok(1));
        assert_eq!(s.apply(l, &Step::new(0, Mix)), Err(StepError::EmptyPremise));
        // Each goal gets its own result.
        let closed = s.close_all(
            &Options::default(),
            &ViewOptions::default(),
            &crate::Limits::default(),
            |_| false,
        );
        assert_eq!(closed.iter().map(|(g, _)| *g).collect::<Vec<_>>(), [l, r]);
        assert!(
            closed
                .iter()
                .all(|(_, c)| c.as_ref().is_ok_and(|c| c.grafted.is_ok()))
        );
        assert!(s.is_complete());
    }
}