deduxit 0.4.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
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

use super::search::Why;
use crate::Error;
use crate::limits::{Limits, Refusal, Space};
use crate::linear::proofs::InfId;
use crate::ordinary::{
    Derivation, Evidence, Formulas, Inference, Logic, Node, NodeId, Outcome, Rule, Search, Sequent,
    Side, Translation, Verdict, bound, ljt,
};
#[cfg(feature = "interactive")]
use crate::ordinary::{Interactive, Parts};
use crate::wire::{self, Readable};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

impl Serialize for Rule {
    /// Serializes the rule as its name, such as `"→L"`.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.name())
    }
}

impl<'a> Deserialize<'a> for Rule {
    /// Deserializes a rule from its name, refusing one no rule has.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        let name = <std::borrow::Cow<'a, str>>::deserialize(deserializer)?;
        Rule::ALL
            .into_iter()
            .find(|rule| rule.name() == name)
            .ok_or_else(|| serde::de::Error::custom(format!("no rule of LK or LJ is named {name}")))
    }
}

/// The serialized form of an ordinary formula: its connective, with its
/// operands as indices of formulas before it. Its tags are part of the
/// interchange format.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
enum FormulaForm {
    /// An atom, by its index among the names.
    #[serde(rename = "V")]
    Atom(u32),
    /// `⊤`
    #[serde(rename = "⊤")]
    True,
    /// `⊥`
    #[serde(rename = "⊥")]
    False,
    /// `¬A`
    #[serde(rename = "¬")]
    Not(u32),
    /// `A ∧ B`
    #[serde(rename = "∧")]
    And(u32, u32),
    /// `A ∨ B`
    #[serde(rename = "∨")]
    Or(u32, u32),
    /// `A → B`
    #[serde(rename = "→")]
    Implies(u32, u32),
    /// `A ↔ B`
    #[serde(rename = "↔")]
    Iff(u32, u32),
}

impl From<Node> for FormulaForm {
    /// Writes a node as its form. The arena's ids are the form's indices.
    fn from(node: Node) -> Self {
        let i = |k: NodeId| k.index() as u32;
        match node {
            Node::Atom(a) => Self::Atom(a),
            Node::True => Self::True,
            Node::False => Self::False,
            Node::Not(a) => Self::Not(i(a)),
            Node::And(a, b) => Self::And(i(a), i(b)),
            Node::Or(a, b) => Self::Or(i(a), i(b)),
            Node::Implies(a, b) => Self::Implies(i(a), i(b)),
            Node::Iff(a, b) => Self::Iff(i(a), i(b)),
        }
    }
}

/// The serialized form of an ordinary sequent: the formulas, the atom
/// names and the two sides.
#[derive(Clone, Debug, Serialize, Deserialize)]
struct SequentForm {
    /// The wire level, written only at the top of a document.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "wire::version"
    )]
    version: Option<u32>,
    /// The formulas, every operand before the formula built from it.
    formulas: Vec<FormulaForm>,
    /// The atom names.
    atoms: Vec<String>,
    /// The hypotheses, as indices of formulas, in the order written.
    left: Vec<u32>,
    /// The formulas right of `⊢`, as indices, in the order written.
    right: Vec<u32>,
}

impl SequentForm {
    /// Returns the form of the sequent `left ⊢ right` over the formulas.
    fn of(formulas: &Formulas, left: &[NodeId], right: &[NodeId]) -> Self {
        let ids = |list: &[NodeId]| list.iter().map(|k| k.index() as u32).collect();
        Self {
            version: None,
            formulas: formulas
                .nodes()
                .iter()
                .map(|&n| FormulaForm::from(n))
                .collect(),
            atoms: formulas.atom_names().to_vec(),
            left: ids(left),
            right: ids(right),
        }
    }

    /// Returns the formulas the form holds, the id among them of every
    /// index of the form, and the two sides. Both the form's formulas and
    /// the sequent's unfolding must be within `limits.occurrences`.
    fn within(self, limits: &Limits) -> Result<(Read, Vec<NodeId>, Vec<NodeId>), Error> {
        if let Some(limit) = limits.occurrences
            && self.formulas.len() as u64 > limit
        {
            return Err(Error::Refused(Refusal::Occurrences {
                occurrences: self.formulas.len() as u64,
                limit,
            }));
        }
        let mut formulas = Formulas::default();
        let mut ids: Vec<NodeId> = Vec::with_capacity(self.formulas.len());
        for (n, form) in self.formulas.iter().enumerate() {
            let at = |k: u32| {
                ids.get(k as usize).copied().ok_or(Error::IndexOutOfBounds {
                    space: Space::Formula,
                    index: k as usize,
                    len: n,
                })
            };
            let id = match *form {
                FormulaForm::Atom(a) => {
                    let name = self.atoms.get(a as usize).ok_or(Error::IndexOutOfBounds {
                        space: Space::Atom,
                        index: a as usize,
                        len: self.atoms.len(),
                    })?;
                    formulas.atom(name)?
                }
                FormulaForm::True => formulas.add(Node::True)?,
                FormulaForm::False => formulas.add(Node::False)?,
                FormulaForm::Not(a) => formulas.add(Node::Not(at(a)?))?,
                FormulaForm::And(a, b) => formulas.add(Node::And(at(a)?, at(b)?))?,
                FormulaForm::Or(a, b) => formulas.add(Node::Or(at(a)?, at(b)?))?,
                FormulaForm::Implies(a, b) => formulas.add(Node::Implies(at(a)?, at(b)?))?,
                FormulaForm::Iff(a, b) => formulas.add(Node::Iff(at(a)?, at(b)?))?,
            };
            ids.push(id);
        }
        let read = Read { formulas, ids };
        let left = read.ids(&self.left)?;
        let right = read.ids(&self.right)?;
        bound(&read.formulas, &left, &right, limits)?;
        Ok((read, left, right))
    }
}

/// The formulas a form held, and the id of each of its indices.
struct Read {
    /// The formulas.
    formulas: Formulas,
    /// The id of each index of the form.
    ids: Vec<NodeId>,
}

impl Read {
    /// Returns the ids of the indices given.
    fn ids(&self, indices: &[u32]) -> Result<Vec<NodeId>, Error> {
        indices
            .iter()
            .map(|&k| {
                self.ids
                    .get(k as usize)
                    .copied()
                    .ok_or(Error::IndexOutOfBounds {
                        space: Space::Formula,
                        index: k as usize,
                        len: self.ids.len(),
                    })
            })
            .collect()
    }
}

impl Serialize for Sequent {
    /// Serializes the sequent as a document at level 8, the level of
    /// ordinary logic.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut form = SequentForm::of(self.formulas(), self.left(), self.right());
        form.version = Some(wire::ORDINARY);
        form.serialize(serializer)
    }
}

impl<'a> Deserialize<'a> for Sequent {
    /// Deserializes a sequent within the default limits, as
    /// [`wire::upgrade`] does.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Self::read(deserializer, &Limits::default())
    }
}

impl crate::sealed::Readable for Sequent {}

impl Readable for Sequent {
    const FORM: &'static str = "ordinary sequent";

    /// Reads a sequent, its formulas and sides within the limits.
    fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
        let form = SequentForm::deserialize(deserializer)?;
        sequent(form, limits).map_err(wire::fail)
    }
}

/// Returns the sequent a form holds, within the limits.
fn sequent(form: SequentForm, limits: &Limits) -> Result<Sequent, Error> {
    let (read, left, right) = form.within(limits)?;
    Sequent::new(read.formulas, left, right)
}

/// The serialized form of an inference: its two sides as indices of
/// formulas, its rule, the side and position of its principal formula,
/// and its premises. An open goal of a proof in progress is its sides
/// alone.
#[derive(Clone, Debug, Serialize, Deserialize)]
struct InferenceForm {
    /// The hypotheses.
    left: Vec<u32>,
    /// The formulas right of `⊢`.
    right: Vec<u32>,
    /// The rule, absent for an open goal of a proof in progress.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    rule: Option<Rule>,
    /// The side and position of the principal formula, absent for an
    /// axiom and an open goal.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    principal: Option<(Side, usize)>,
    /// The premises, as indices of inferences; absent for a leaf.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    premises: Vec<u32>,
}

impl InferenceForm {
    /// Returns the form of an inference. Where `open` is set, an open goal
    /// is written without its rule.
    fn of(inference: &Inference, open: bool) -> Self {
        let ids = |list: &[NodeId]| list.iter().map(|k| k.index() as u32).collect();
        Self {
            left: ids(&inference.left),
            right: ids(&inference.right),
            rule: (!(open && inference.rule == Rule::Open)).then_some(inference.rule),
            principal: inference.principal,
            premises: inference.premises.iter().map(|p| p.get()).collect(),
        }
    }

    /// Returns the inference the form holds, its formulas by the ids that
    /// `read` gives. Refuses a premise at `len` or past it, and a
    /// principal position past its side.
    fn read(self, read: &Read, len: usize) -> Result<Inference, Error> {
        let premises = self
            .premises
            .iter()
            .map(|&p| match p as usize {
                p if p < len => Ok(InfId::new(p as u32)),
                index => Err(Error::IndexOutOfBounds {
                    space: Space::Inference,
                    index,
                    len,
                }),
            })
            .collect::<Result<_, _>>()?;
        let inference = Inference {
            left: read.ids(&self.left)?,
            right: read.ids(&self.right)?,
            rule: self.rule.unwrap_or(Rule::Open),
            principal: self.principal,
            premises,
        };
        if let Some((side, at)) = inference.principal
            && at >= inference.side(side).len()
        {
            return Err(Error::IndexOutOfBounds {
                space: Space::Formula,
                index: at,
                len: inference.side(side).len(),
            });
        }
        Ok(inference)
    }
}

/// The serialized form of a derivation of LK or LJ: the logic, the
/// sequent with every formula the inferences name, and the inferences.
/// Premises come before their conclusions, and the root is last.
#[derive(Clone, Debug, Serialize, Deserialize)]
struct DerivationForm {
    /// The wire level, written only at the top of a document.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "wire::version"
    )]
    version: Option<u32>,
    /// The logic.
    logic: Logic,
    /// The sequent derived.
    sequent: SequentForm,
    /// The inferences.
    inferences: Vec<InferenceForm>,
}

impl From<&Derivation> for DerivationForm {
    /// Writes the derivation's form, every rule named.
    fn from(derivation: &Derivation) -> Self {
        let (left, right) = derivation.sequent();
        Self {
            version: None,
            logic: derivation.logic(),
            sequent: SequentForm::of(derivation.formulas(), left, right),
            inferences: derivation
                .inferences()
                .iter()
                .map(|i| InferenceForm::of(i, false))
                .collect(),
        }
    }
}

impl DerivationForm {
    /// Returns the derivation the form holds, its sequent within the
    /// limits. Refuses a form without the shape every derivation has:
    /// - at least one inference;
    /// - every premise before its conclusion, and the premise of exactly
    ///   one inference;
    /// - the root last.
    ///
    /// Whether it is a derivation of its logic is for
    /// [`Derivation::check`] to say.
    fn within(self, limits: &Limits) -> Result<Derivation, Error> {
        let (read, left, right) = self.sequent.within(limits)?;
        let len = self.inferences.len();
        let mut parents = vec![0u8; len];
        let mut inferences = Vec::with_capacity(len);
        for (n, form) in self.inferences.into_iter().enumerate() {
            let inference = form.read(&read, n)?;
            // An open goal is a leaf with no principal formula, as the
            // drawings draw it.
            if inference.rule == Rule::Open
                && (inference.principal.is_some() || !inference.premises.is_empty())
            {
                return Err(Error::Json {
                    form: "ordinary derivation",
                    message: format!("inference {n} is an open goal with a principal or premises"),
                });
            }
            for p in &inference.premises {
                parents[p.index()] = parents[p.index()].saturating_add(1);
            }
            inferences.push(inference);
        }
        let shaped = parents
            .split_last()
            .is_some_and(|(&root, rest)| root == 0 && rest.iter().all(|&n| n == 1));
        if !shaped {
            return Err(Error::Json {
                form: "ordinary derivation",
                message: "the inferences are no tree with its root last".to_owned(),
            });
        }
        Ok(
            Derivation::from_parts(self.logic, read.formulas, (left, right), inferences)
                .untrusted(),
        )
    }
}

impl Serialize for Derivation {
    /// Serializes the derivation as a document: at level 9 where an
    /// inference is a cut, else at level 8.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut form = DerivationForm::from(self);
        form.version = Some(level(self.inferences()));
        form.serialize(serializer)
    }
}

impl<'a> Deserialize<'a> for Derivation {
    /// Deserializes a derivation within the default limits, as
    /// [`wire::upgrade`] does.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Self::read(deserializer, &Limits::default())
    }
}

impl crate::sealed::Readable for Derivation {}

impl Readable for Derivation {
    const FORM: &'static str = "ordinary derivation";

    /// Reads a derivation that has the shape every derivation has, its
    /// sequent within the limits.
    fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
        let form = DerivationForm::deserialize(deserializer)?;
        form.within(limits).map_err(wire::fail)
    }
}

/// The serialized form of the outcome of deciding an ordinary sequent:
/// the verdict, the logic, the search that decided it, and the evidence
/// of a valid sequent.
#[derive(Serialize)]
struct OutcomeForm<'a> {
    /// The wire level.
    version: u32,
    /// The crate's version, which wrote the outcome.
    deduxit: &'static str,
    /// `valid`, `not_valid` or `unknown`.
    verdict: &'static str,
    /// Why the search could not decide.
    #[serde(skip_serializing_if = "Option::is_none")]
    reason: Option<Why>,
    /// The logic decided.
    logic: Logic,
    /// How the sequent was searched, tagged by its method.
    search: SearchForm<'a>,
    /// The derivation, for `valid` by a derivation.
    #[serde(skip_serializing_if = "Option::is_none")]
    derivation: Option<DerivationForm>,
    /// The clausal proof, for `valid` by one.
    #[cfg(feature = "sat")]
    #[serde(skip_serializing_if = "Option::is_none")]
    clausal_proof: Option<&'a crate::ordinary::sat::ClausalProof>,
    /// The Kripke model that refutes the sequent, for `not_valid` by one.
    #[serde(skip_serializing_if = "Option::is_none")]
    countermodel: Option<CountermodelForm>,
}

/// The serialized form of a countermodel: the sequent refuted and the
/// model.
#[derive(Serialize, Deserialize)]
struct CountermodelForm {
    /// The sequent refuted.
    sequent: SequentForm,
    /// The model.
    model: super::kripke::ModelForm,
}

/// How an ordinary sequent was searched, as an outcome writes it: an
/// object tagged by `method`, the method's name.
#[derive(Serialize)]
#[serde(tag = "method", rename_all = "snake_case")]
enum SearchForm<'a> {
    /// Through the embedding: the translation and the image's outcome.
    Embedding {
        /// The translation the image was made by.
        translation: Translation,
        /// The outcome of the image's search, with its proof or disproof.
        image: super::search::Nested<'a>,
    },
    /// By LJT, and what its search cost.
    Ljt {
        /// LJT's statistics.
        statistics: &'a ljt::Statistics,
    },
    /// By the SAT solver, and what its search cost.
    #[cfg(feature = "sat")]
    Sat {
        /// The SAT solver's statistics.
        statistics: &'a crate::ordinary::sat::Statistics,
    },
    /// By the truth table.
    Table {
        /// The table.
        table: TableForm,
    },
    /// By a tableau.
    #[cfg(feature = "interactive")]
    Tableau {
        /// The tableau.
        tableau: TableauForm,
    },
}

impl Serialize for Outcome {
    /// Serializes the outcome as a document at level 12: its verdict, with
    /// the reason of an unknown one and the evidence of a valid sequent,
    /// and the search that decided it, the image's outcome nested under
    /// the embedding.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let (verdict, reason, derivation) = match &self.verdict {
            Verdict::Valid(Evidence::Derivation(d)) => {
                ("valid", None, Some(DerivationForm::from(&**d)))
            }
            #[cfg(feature = "sat")]
            Verdict::Valid(Evidence::Clausal(_)) => ("valid", None, None),
            Verdict::Valid(Evidence::Image | Evidence::Table) => ("valid", None, None),
            Verdict::NotValid => ("not_valid", None, None),
            Verdict::Unknown(r) => ("unknown", Some(Why::from(*r)), None),
        };
        let search = match &self.search {
            Search::Embedding {
                translation,
                linear,
            } => SearchForm::Embedding {
                translation: *translation,
                image: super::search::Nested(linear),
            },
            Search::Ljt(statistics) => SearchForm::Ljt { statistics },
            #[cfg(feature = "sat")]
            Search::Sat(statistics) => SearchForm::Sat { statistics },
            Search::Table(table) => SearchForm::Table {
                table: TableForm::from(&**table),
            },
            #[cfg(feature = "interactive")]
            Search::Tableau(tableau) => SearchForm::Tableau {
                tableau: TableauForm::from(&**tableau),
            },
        };
        // A reader of level 12 does not know the methods `table` and
        // `tableau`, so an outcome of either is at level 14.
        let version = match &self.search {
            Search::Table(_) => wire::TABLES,
            #[cfg(feature = "interactive")]
            Search::Tableau(_) => wire::TABLES,
            Search::Embedding { .. } | Search::Ljt(_) => wire::SEARCH,
            #[cfg(feature = "sat")]
            Search::Sat(_) => wire::SEARCH,
        };
        let countermodel = self.countermodel.as_ref().map(|c| CountermodelForm {
            sequent: SequentForm::of(c.sequent.formulas(), c.sequent.left(), c.sequent.right()),
            model: super::kripke::ModelForm::from(&c.model),
        });
        // A reader of level 12 may ignore the countermodel without
        // misreading the verdict, so it raises no level.
        OutcomeForm {
            version,
            deduxit: env!("CARGO_PKG_VERSION"),
            verdict,
            reason,
            logic: self.logic,
            search,
            derivation,
            #[cfg(feature = "sat")]
            clausal_proof: match &self.verdict {
                Verdict::Valid(Evidence::Clausal(proof)) => Some(proof),
                Verdict::Valid(Evidence::Derivation(_) | Evidence::Image | Evidence::Table)
                | Verdict::NotValid
                | Verdict::Unknown(_) => None,
            },
            countermodel,
        }
        .serialize(serializer)
    }
}

/// The verdict of an ordinary outcome read, by its word.
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum VerdictWord {
    /// `valid`.
    Valid,
    /// `not_valid`.
    NotValid,
    /// `unknown`.
    Unknown,
}

/// How an ordinary sequent was searched, as an outcome is read.
#[derive(Deserialize)]
#[serde(tag = "method", rename_all = "snake_case")]
enum SearchRead {
    /// Through the embedding.
    Embedding {
        /// The translation the image was made by.
        translation: Translation,
        /// The image's outcome.
        image: Box<super::search::OutcomeForm>,
    },
    /// By LJT.
    Ljt {
        /// LJT's statistics.
        statistics: ljt::Statistics,
    },
    /// By the SAT solver.
    #[cfg(feature = "sat")]
    Sat {
        /// The SAT solver's statistics.
        statistics: crate::ordinary::sat::Statistics,
    },
    /// By the truth table.
    Table {
        /// The table.
        table: TableForm,
    },
    /// By a tableau.
    #[cfg(feature = "interactive")]
    Tableau {
        /// The tableau.
        tableau: TableauForm,
    },
}

/// The keys an ordinary outcome is read from. `deduxit`, the writer's
/// version, is not read.
#[derive(Deserialize)]
struct OutcomeRead {
    /// The wire level, read to refuse one above this build's.
    #[serde(default, deserialize_with = "wire::version")]
    version: Option<u32>,
    /// `valid`, `not_valid` or `unknown`.
    verdict: VerdictWord,
    /// Why the search could not decide, for `unknown`.
    #[serde(default)]
    reason: Option<Why>,
    /// The logic decided.
    logic: Logic,
    /// How the sequent was searched; absent below level 12.
    #[serde(default)]
    search: Option<SearchRead>,
    /// The derivation, for `valid` by a derivation.
    #[serde(default)]
    derivation: Option<DerivationForm>,
    /// The clausal proof's counts, for `valid` by one.
    #[serde(default)]
    clausal_proof: Option<serde::de::IgnoredAny>,
    /// The Kripke model that refutes the sequent, for `not_valid`.
    #[serde(default)]
    countermodel: Option<CountermodelForm>,
}

impl OutcomeRead {
    /// Returns the outcome the form holds, its derivation and the image's
    /// proof or disproof read within `limits`, neither checked. Refuses an
    /// outcome below level 12, which has no `search`; one valid by a
    /// clausal proof, whose document holds the proof's counts alone; and
    /// one whose verdict the image's outcome does not bear out.
    fn within(self, limits: &Limits) -> Result<Outcome, Error> {
        let refuse = |message: &str| Error::Json {
            form: "ordinary outcome",
            message: message.to_owned(),
        };
        let search = match self.search {
            Some(search) => search,
            None if self.version.unwrap_or(wire::BASE) < wire::SEARCH => {
                return Err(refuse(
                    "an ordinary outcome below level 12 has no `search` and is not read back",
                ));
            }
            None => return Err(refuse("missing field `search`")),
        };
        let search = match search {
            SearchRead::Embedding { translation, image } => Search::Embedding {
                translation,
                linear: Box::new(image.within(limits)?),
            },
            SearchRead::Ljt { statistics } => Search::Ljt(statistics),
            #[cfg(feature = "sat")]
            SearchRead::Sat { statistics } => Search::Sat(statistics),
            SearchRead::Table { table } => Search::Table(Box::new(table.within(limits)?)),
            #[cfg(feature = "interactive")]
            SearchRead::Tableau { tableau } => Search::Tableau(Box::new(tableau.within(limits)?)),
        };
        let image = match &search {
            Search::Embedding { linear, .. } => Some(&linear.verdict),
            #[cfg(feature = "sat")]
            Search::Sat(_) => None,
            Search::Ljt(_) | Search::Table(_) => None,
            #[cfg(feature = "interactive")]
            Search::Tableau(_) => None,
        };
        use crate::linear::search::Verdict as Linear;
        let borne = match (&self.verdict, image) {
            (_, None)
            | (VerdictWord::Valid, Some(Linear::Proved(_)))
            | (VerdictWord::NotValid, Some(Linear::Unprovable(_)))
            | (VerdictWord::Unknown, Some(Linear::Unknown(_))) => true,
            (_, Some(_)) => false,
        };
        if !borne {
            return Err(refuse("the verdict is not the image's outcome's"));
        }
        // A table or a tableau bears its verdict out itself.
        let shown = match (&self.verdict, &search) {
            (VerdictWord::Valid, Search::Table(table)) => table.falsifying().is_empty(),
            (VerdictWord::NotValid, Search::Table(table)) => !table.falsifying().is_empty(),
            #[cfg(feature = "interactive")]
            (VerdictWord::Valid, Search::Tableau(tableau)) => tableau.is_closed(),
            #[cfg(feature = "interactive")]
            (VerdictWord::NotValid, Search::Tableau(tableau)) => !tableau.is_closed(),
            _ => true,
        };
        if !shown {
            return Err(refuse("the verdict is not its table's or its tableau's"));
        }
        let verdict = match self.verdict {
            VerdictWord::Valid if self.clausal_proof.is_some() => {
                return Err(refuse(
                    "a clausal proof is written as its counts, which hold no proof to read back",
                ));
            }
            VerdictWord::Valid => match self.derivation {
                Some(form) => Verdict::Valid(Evidence::Derivation(Box::new(form.within(limits)?))),
                None if image.is_some() => Verdict::Valid(Evidence::Image),
                None if matches!(search, Search::Table(_)) => Verdict::Valid(Evidence::Table),
                None => return Err(refuse("missing field `derivation`")),
            },
            VerdictWord::NotValid => Verdict::NotValid,
            VerdictWord::Unknown => match self.reason {
                Some(reason) => Verdict::Unknown(reason.into()),
                None => return Err(refuse("missing field `reason`")),
            },
        };
        let countermodel = match (self.countermodel, &verdict) {
            (None, _) => None,
            (Some(form), Verdict::NotValid) => Some(crate::ordinary::Countermodel::new(
                sequent(form.sequent, limits)?,
                form.model.within(limits)?,
            )),
            (Some(_), _) => {
                return Err(refuse(
                    "a countermodel beside a verdict other than not_valid",
                ));
            }
        };
        Ok(Outcome {
            verdict,
            logic: self.logic,
            search,
            countermodel,
        })
    }
}

impl<'a> Deserialize<'a> for Outcome {
    /// Deserializes an ordinary outcome within the default limits, as
    /// [`wire::upgrade`] does.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Self::read(deserializer, &Limits::default())
    }
}

impl crate::sealed::Readable for Outcome {}

impl Readable for Outcome {
    const FORM: &'static str = "ordinary outcome";

    /// Reads an ordinary outcome: its derivation and the image's proof or
    /// disproof as their own readers read them, neither checked.
    fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
        OutcomeRead::deserialize(deserializer)?
            .within(limits)
            .map_err(wire::fail)
    }
}

/// The serialized form of a proof in progress of an ordinary sequent: the
/// logic, the sequent with every formula the inferences name, the
/// inferences with the root first, and the inferences the steps closed.
#[cfg(feature = "interactive")]
#[derive(Clone, Debug, Serialize, Deserialize)]
struct SessionForm {
    /// The wire level, written only at the top of a document.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "wire::version"
    )]
    version: Option<u32>,
    /// The logic.
    logic: Logic,
    /// The sequent being proved.
    sequent: SequentForm,
    /// The inferences.
    inferences: Vec<InferenceForm>,
    /// The steps, each the inference it closed.
    history: Vec<u32>,
}

#[cfg(feature = "interactive")]
impl Serialize for Interactive {
    /// Serializes the proof in progress as a document: at level 9 where an
    /// inference is a cut, else at level 8.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let (logic, formulas, inferences, history) = self.parts();
        let (left, right) = self.sequent();
        SessionForm {
            version: Some(level(inferences)),
            logic,
            sequent: SequentForm::of(formulas, left, right),
            inferences: inferences
                .iter()
                .map(|i| InferenceForm::of(i, true))
                .collect(),
            history: history.iter().map(|h| h.get()).collect(),
        }
        .serialize(serializer)
    }
}

#[cfg(feature = "interactive")]
impl<'a> Deserialize<'a> for Interactive {
    /// Deserializes a proof in progress within the default limits, as
    /// [`wire::upgrade`] does.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Self::read(deserializer, &Limits::default())
    }
}

#[cfg(feature = "interactive")]
impl crate::sealed::Readable for Interactive {}

#[cfg(feature = "interactive")]
impl Readable for Interactive {
    const FORM: &'static str = "ordinary session";

    /// Reads a proof in progress, its sequent within the limits, and
    /// checks it as one built step by step is checked.
    fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
        let form = SessionForm::deserialize(deserializer)?;
        session(form, limits).map_err(wire::fail)
    }
}

/// Returns the proof in progress a form holds, within the limits.
#[cfg(feature = "interactive")]
fn session(form: SessionForm, limits: &Limits) -> Result<Interactive, Error> {
    let (read, left, right) = form.sequent.within(limits)?;
    let len = form.inferences.len();
    let inferences = form
        .inferences
        .into_iter()
        .map(|i| i.read(&read, len))
        .collect::<Result<Vec<_>, _>>()?;
    if inferences
        .first()
        .is_some_and(|root| root.left != left || root.right != right)
    {
        return Err(Error::InconsistentSession {
            reason: "the root does not conclude the sequent",
        });
    }
    let history = form
        .history
        .iter()
        .map(|&h| match h as usize {
            h if h < len => Ok(InfId::new(h as u32)),
            index => Err(Error::IndexOutOfBounds {
                space: Space::Inference,
                index,
                len,
            }),
        })
        .collect::<Result<_, _>>()?;
    Interactive::from_parts(
        Parts {
            logic: form.logic,
            formulas: read.formulas,
            inferences,
            history,
        },
        limits,
    )
}

/// Returns the level of a form of ordinary logic with these inferences:
/// 9 where one is a cut, else 8, the level of ordinary logic.
fn level(inferences: &[Inference]) -> u32 {
    if inferences.iter().any(|i| i.rule() == Rule::Cut) {
        wire::ORDINARY_CUT
    } else {
        wire::ORDINARY
    }
}

/// The serialized form of a truth table: the sequent, a row per
/// assignment as a `T` or `F` per formula of the sequent's form, and the
/// rows that falsify the sequent.
#[derive(Serialize, Deserialize)]
struct TableForm {
    /// The wire level, written only at the top of a document.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "wire::version"
    )]
    version: Option<u32>,
    /// The sequent.
    sequent: SequentForm,
    /// The rows, from every atom true to every atom false.
    rows: Vec<String>,
    /// The rows that falsify the sequent.
    falsifying: Vec<u64>,
}

impl From<&crate::ordinary::TruthTable> for TableForm {
    /// Writes the table's form, nested: without its level.
    fn from(table: &crate::ordinary::TruthTable) -> Self {
        let sequent = table.sequent();
        Self {
            version: None,
            sequent: SequentForm::of(sequent.formulas(), sequent.left(), sequent.right()),
            rows: (0..table.rows())
                .map(|row| {
                    table
                        .row(row)
                        .map(|value| if value { 'T' } else { 'F' })
                        .collect()
                })
                .collect(),
            falsifying: table.falsifying().to_vec(),
        }
    }
}

impl TableForm {
    /// Returns the table of the form's sequent, computed again within
    /// `limits`; refuses rows or falsifying rows that are not that
    /// table's.
    fn within(self, limits: &Limits) -> Result<crate::ordinary::TruthTable, Error> {
        let (read, left, right) = self.sequent.within(limits)?;
        let ids = read.ids.clone();
        let sequent = Sequent::new(read.formulas, left, right)?;
        let table = crate::ordinary::truth_table(&sequent, limits, |_| false)?;
        let matches = self.rows.len() as u64 == table.rows()
            && self.rows.iter().enumerate().all(|(row, text)| {
                text.chars().count() == ids.len()
                    && text.chars().zip(&ids).all(|(c, &id)| {
                        (c == 'T') == table.value(row as u64, id) && "TF".contains(c)
                    })
            })
            && self.falsifying == table.falsifying();
        if !matches {
            return Err(Error::Json {
                form: "truth table",
                message: "the rows are not the sequent's truth table".to_owned(),
            });
        }
        Ok(table)
    }
}

impl Serialize for crate::ordinary::TruthTable {
    /// Serializes the table as a document at level 14.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut form = TableForm::from(self);
        form.version = Some(wire::TABLES);
        form.serialize(serializer)
    }
}

impl<'a> Deserialize<'a> for crate::ordinary::TruthTable {
    /// Deserializes a table within the default limits, as
    /// [`wire::upgrade`] does.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Self::read(deserializer, &Limits::default())
    }
}

impl crate::sealed::Readable for crate::ordinary::TruthTable {}

impl Readable for crate::ordinary::TruthTable {
    const FORM: &'static str = "truth table";

    /// Reads a truth table, computed again from its sequent.
    fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
        TableForm::deserialize(deserializer)?
            .within(limits)
            .map_err(wire::fail)
    }
}

/// A sign as a tableau's form writes it.
#[cfg(feature = "interactive")]
#[derive(Clone, Copy, Serialize, Deserialize)]
enum SignForm {
    /// True.
    T,
    /// False.
    F,
}

/// How a branch ends, as a tableau's form writes it, tagged by `kind`.
#[cfg(feature = "interactive")]
#[derive(Clone, Copy, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum EndForm {
    /// Closed by a formula true at one line and false at another.
    Closed {
        /// The line where it is true.
        true_line: u32,
        /// The line where it is false.
        false_line: u32,
    },
    /// Closed by `⊥` true.
    Falsity {
        /// The line.
        line: u32,
    },
    /// Closed by `⊤` false.
    Truth {
        /// The line.
        line: u32,
    },
    /// Open and finished.
    Open,
    /// Open and not expanded.
    Unexpanded,
}

/// The serialized form of a tableau's node.
#[cfg(feature = "interactive")]
#[derive(Serialize, Deserialize)]
struct TableauNodeForm {
    /// The lines, each a sign and a formula's index.
    lines: Vec<(SignForm, u32)>,
    /// The line the children expand and the rule, absent for a leaf.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    expands: Option<(u32, Rule)>,
    /// The children, by index; absent for a leaf.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    children: Vec<u32>,
    /// How the branch ends, for a leaf.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    end: Option<EndForm>,
}

/// The serialized form of a tableau: the sequent with every formula a
/// line names, and the nodes, each before its children.
#[cfg(feature = "interactive")]
#[derive(Serialize, Deserialize)]
struct TableauForm {
    /// The wire level, written only at the top of a document.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "wire::version"
    )]
    version: Option<u32>,
    /// The sequent, its form holding every formula a line names.
    sequent: SequentForm,
    /// The nodes.
    nodes: Vec<TableauNodeForm>,
}

#[cfg(feature = "interactive")]
impl From<&crate::ordinary::Tableau> for TableauForm {
    /// Writes the tableau's form, nested: without its level.
    fn from(tableau: &crate::ordinary::Tableau) -> Self {
        use crate::ordinary::{End, Sign};
        let (left, right) = tableau.sequent();
        Self {
            version: None,
            sequent: SequentForm::of(tableau.formulas(), left, right),
            nodes: tableau
                .nodes()
                .iter()
                .map(|node| TableauNodeForm {
                    lines: node
                        .lines()
                        .iter()
                        .map(|line| {
                            let sign = match line.sign {
                                Sign::True => SignForm::T,
                                Sign::False => SignForm::F,
                            };
                            (sign, line.formula.index() as u32)
                        })
                        .collect(),
                    expands: node.expands(),
                    children: node.children().to_vec(),
                    end: node.end().map(|end| match end {
                        End::Closed {
                            true_line,
                            false_line,
                        } => EndForm::Closed {
                            true_line,
                            false_line,
                        },
                        End::Falsity { line } => EndForm::Falsity { line },
                        End::Truth { line } => EndForm::Truth { line },
                        End::Open => EndForm::Open,
                        End::Unexpanded => EndForm::Unexpanded,
                    }),
                })
                .collect(),
        }
    }
}

#[cfg(feature = "interactive")]
impl TableauForm {
    /// Returns the tableau the form holds, its sequent within the limits.
    /// Refuses a form without the shape every tableau has: at least one
    /// node; every node but the first the child of exactly one node before
    /// it; a node with children expanding a line and without an end, a
    /// leaf with an end and expanding nothing; every line named in range.
    /// Whether its expansions follow the rules is not checked.
    fn within(self, limits: &Limits) -> Result<crate::ordinary::Tableau, Error> {
        use crate::ordinary::{End, Sign, Signed, Tableau, TableauNode};
        let refuse = |message: String| Error::Json {
            form: "tableau",
            message,
        };
        let (read, left, right) = self.sequent.within(limits)?;
        let total: u64 = self.nodes.iter().map(|n| n.lines.len() as u64).sum();
        let total =
            u32::try_from(total).map_err(|_| refuse("more lines than a u32 numbers".to_owned()))?;
        let line = |n: u32| {
            if n < total {
                Ok(n)
            } else {
                Err(refuse(format!(
                    "line {n} is past the tableau's {total} lines"
                )))
            }
        };
        let len = self.nodes.len();
        let mut parents = vec![0u8; len];
        let mut nodes = Vec::with_capacity(len);
        let mut first = 0u32;
        for (n, form) in self.nodes.into_iter().enumerate() {
            let lines = form
                .lines
                .iter()
                .map(|&(sign, k)| {
                    let sign = match sign {
                        SignForm::T => Sign::True,
                        SignForm::F => Sign::False,
                    };
                    Ok(Signed::new(sign, read.ids(&[k])?[0]))
                })
                .collect::<Result<Vec<_>, Error>>()?;
            for &child in &form.children {
                if (child as usize) <= n || child as usize >= len {
                    return Err(refuse(format!("node {n} names child {child}")));
                }
                parents[child as usize] = parents[child as usize].saturating_add(1);
            }
            let expands = form
                .expands
                .map(|(l, rule)| line(l).map(|l| (l, rule)))
                .transpose()?;
            let end = form
                .end
                .map(|end| {
                    Ok::<_, Error>(match end {
                        EndForm::Closed {
                            true_line,
                            false_line,
                        } => End::Closed {
                            true_line: line(true_line)?,
                            false_line: line(false_line)?,
                        },
                        EndForm::Falsity { line: l } => End::Falsity { line: line(l)? },
                        EndForm::Truth { line: l } => End::Truth { line: line(l)? },
                        EndForm::Open => End::Open,
                        EndForm::Unexpanded => End::Unexpanded,
                    })
                })
                .transpose()?;
            let leaf = form.children.is_empty();
            if leaf != end.is_some() || leaf == expands.is_some() {
                return Err(refuse(format!(
                    "node {n} must have children and expand a line, or end its branch"
                )));
            }
            let count = lines.len() as u32;
            nodes.push(TableauNode::from_parts(
                first,
                lines,
                (expands, form.children, end),
            ));
            first += count;
        }
        let shaped = parents
            .split_first()
            .is_some_and(|(&root, rest)| root == 0 && rest.iter().all(|&p| p == 1));
        if !shaped {
            return Err(refuse(
                "the nodes are no tree with its root first".to_owned(),
            ));
        }
        Ok(Tableau::from_parts(read.formulas, (left, right), nodes))
    }
}

#[cfg(feature = "interactive")]
impl Serialize for crate::ordinary::Tableau {
    /// Serializes the tableau as a document at level 14.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut form = TableauForm::from(self);
        form.version = Some(wire::TABLES);
        form.serialize(serializer)
    }
}

#[cfg(feature = "interactive")]
impl<'a> Deserialize<'a> for crate::ordinary::Tableau {
    /// Deserializes a tableau within the default limits, as
    /// [`wire::upgrade`] does.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Self::read(deserializer, &Limits::default())
    }
}

#[cfg(feature = "interactive")]
impl crate::sealed::Readable for crate::ordinary::Tableau {}

#[cfg(feature = "interactive")]
impl Readable for crate::ordinary::Tableau {
    const FORM: &'static str = "tableau";

    /// Reads a tableau: its shape and indices checked, not its
    /// expansions.
    fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
        TableauForm::deserialize(deserializer)?
            .within(limits)
            .map_err(wire::fail)
    }
}