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

use super::proofs::{Instances, Proof, Step};
use super::sequents::Sequent as SequentForm;
use crate::limits::{Limits, Space};
use crate::linear::fragment::{Fragment, Mode};
use crate::linear::occurrences::{Member, OccId, Sign};
use crate::linear::search::{
    Basis, Bias, Cadence, Classical, Disproof, Engine, Equation, Jobs, Marking, OneSided,
    OneSidedSymbol, Outcome as Out, Reason, Refutation, Saturated, Stable, StateEquation,
    Statistics, Unbalanced, UnbalancedSymbol, Verdict,
};
use crate::linear::sequents::{Atom, Symbol};
use crate::wire::{self, Readable};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

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

impl<'a> Deserialize<'a> for Fragment {
    /// Deserializes a fragment from its name. It returns the named
    /// fragment, which contains every fragment of that name.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        let name = String::deserialize(deserializer)?;
        name.parse().map_err(serde::de::Error::custom)
    }
}

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

impl<'a> Deserialize<'a> for Mode {
    /// Deserializes a mode from its name. An unknown name is refused with
    /// a list of the known ones.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        let name = <std::borrow::Cow<'a, str>>::deserialize(deserializer)?;
        name.parse().map_err(serde::de::Error::custom)
    }
}

/// The serialized form of a reason: its `kind`, with the bound that
/// stopped the search where there is one. A kind it does not know is
/// refused, never read as another.
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(super) enum Why {
    /// The stop condition fired.
    Stopped,
    /// The recursion limit was reached.
    RecursionLimit {
        /// The depth the limits allowed.
        depth: u32,
    },
    /// Every level up to the copy bound hit its bound on some branch.
    CopyBound {
        /// The bound.
        copies: u32,
    },
    /// The search would have held more than the memory bound.
    MemoryLimit {
        /// The bound.
        limit_bytes: u64,
    },
    /// A structure of the search outgrew its indices.
    IndexLimit,
    /// The work limit was reached, by the search or by the check of its
    /// proof.
    WorkLimit {
        /// The bound.
        limit: u64,
    },
    /// A proof was found whose check would hold more than the memory bound.
    Unchecked {
        /// The bound.
        limit_bytes: u64,
    },
    /// A binding would have passed the witness depth, and no proof was
    /// found.
    WitnessDepth {
        /// The bound.
        depth: u32,
    },
    /// An instance would have passed the bound on instances, and no proof
    /// was found.
    Instances {
        /// The bound.
        instances: u32,
    },
}

impl From<Reason> for Why {
    /// Converts a reason into its serialized form.
    fn from(r: Reason) -> Self {
        match r {
            Reason::Stopped => Why::Stopped,
            Reason::RecursionLimit { depth } => Why::RecursionLimit { depth },
            Reason::CopyBound { copies } => Why::CopyBound { copies },
            Reason::MemoryLimit { limit_bytes } => Why::MemoryLimit { limit_bytes },
            Reason::IndexLimit => Why::IndexLimit,
            Reason::WorkLimit { limit } => Why::WorkLimit { limit },
            Reason::Unchecked { limit_bytes } => Why::Unchecked { limit_bytes },
            Reason::WitnessDepth { depth } => Why::WitnessDepth { depth },
            Reason::Instances { instances } => Why::Instances { instances },
        }
    }
}

impl From<Why> for Reason {
    /// Converts a reason's serialized form back.
    fn from(w: Why) -> Self {
        match w {
            Why::Stopped => Reason::Stopped,
            Why::RecursionLimit { depth } => Reason::RecursionLimit { depth },
            Why::CopyBound { copies } => Reason::CopyBound { copies },
            Why::MemoryLimit { limit_bytes } => Reason::MemoryLimit { limit_bytes },
            Why::IndexLimit => Reason::IndexLimit,
            Why::WorkLimit { limit } => Reason::WorkLimit { limit },
            Why::Unchecked { limit_bytes } => Reason::Unchecked { limit_bytes },
            Why::WitnessDepth { depth } => Reason::WitnessDepth { depth },
            Why::Instances { instances } => Reason::Instances { instances },
        }
    }
}

impl Serialize for Reason {
    /// Serializes the reason tagged by its `kind`.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        Why::from(*self).serialize(serializer)
    }
}

impl<'a> Deserialize<'a> for Reason {
    /// Deserializes a reason from its `kind`, refusing one it does not
    /// know.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Why::deserialize(deserializer).map(Reason::from)
    }
}

/// A literal of an atom as a refutation names it: the atom, or its
/// negation.
#[derive(Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum Literal {
    /// The atom `a`.
    Atom,
    /// Its negation `~a`.
    Dual,
}

impl From<Sign> for Literal {
    /// Returns the literal of the sign.
    fn from(sign: Sign) -> Self {
        match sign {
            Sign::Atom => Literal::Atom,
            Sign::Dual => Literal::Dual,
        }
    }
}

impl From<Literal> for Sign {
    /// Returns the sign of the literal.
    fn from(literal: Literal) -> Self {
        match literal {
            Literal::Atom => Sign::Atom,
            Literal::Dual => Sign::Dual,
        }
    }
}

/// The serialized form of a refutation: its `kind`, with the counts,
/// weights, assignment or set that rule a proof out. A kind it does not
/// know is refused, never read as another.
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum WhyNot {
    /// The search was exhaustive.
    Exhausted,
    /// An atom's literals cannot pair up.
    Unbalanced {
        /// The atom's index into the sequent's atoms.
        atom: u32,
        /// The least excess of positive over negative literals.
        least: i32,
        /// The greatest excess.
        most: i32,
    },
    /// An atom's literals cannot pair up, though copies may add one sign.
    OneSided {
        /// The atom's index into the sequent's atoms.
        atom: u32,
        /// The least excess outside the exponentials.
        least: i32,
        /// The greatest excess.
        most: i32,
        /// The sign of every literal of the atom below an exponential.
        copied: Literal,
    },
    /// The count equation fails.
    Equation {
        /// How many formulas the sequent has.
        formulas: u64,
        /// How many formulas the equation asks for.
        needed: i64,
        /// How many `⊗` the sequent has.
        tensors: u64,
        /// How many `⅋` it has.
        pars: u64,
        /// How many `1` it has.
        ones: u64,
        /// How many `⊥` it has.
        bottoms: u64,
        /// Whether Mix was allowed.
        mix: bool,
    },
    /// The state equation of the Petri net that the Horn engine reads the
    /// sequent as has no solution.
    StateEquation {
        /// The atoms that weigh something, by index, with their weights.
        atoms: Vec<(u32, i64)>,
        /// The clauses used once that weigh something, by occurrence, with
        /// their weights.
        clauses: Vec<(u32, i64)>,
        /// The clauses that can never fire, by occurrence.
        dropped: Vec<u32>,
    },
    /// The classical reading is false under an assignment.
    Classical {
        /// The value of each atom, by index.
        assignment: Vec<bool>,
    },
    /// A forward search saturated: its set of stable sequents is closed
    /// under the rules and leaves the goal underived.
    Saturated {
        /// The positive literal of each atom, by index.
        positive: Vec<Literal>,
        /// The sequents of the set.
        sequents: Vec<StableForm>,
    },
    /// A predicate's literals cannot pair up, all its atoms counted.
    UnbalancedSymbol {
        /// The predicate's index into the sequent's symbols.
        symbol: u32,
        /// The least excess of positive over negative literals.
        least: i32,
        /// The greatest excess.
        most: i32,
    },
    /// A predicate's literals cannot pair up, though copies may add one
    /// sign.
    OneSidedSymbol {
        /// The predicate's index into the sequent's symbols.
        symbol: u32,
        /// The least excess outside the exponentials.
        least: i32,
        /// The greatest excess.
        most: i32,
        /// The sign of every literal of the predicate below an
        /// exponential.
        copied: Literal,
    },
    /// A backward search from a Horn program's target saturated, and no
    /// marking of the basis it kept is at most the initial one.
    Basis {
        /// The sign of the bodies' literals.
        body: Literal,
        /// The classes of clauses used once, by occurrence.
        classes: Vec<Vec<u32>>,
        /// The markings of the basis.
        markings: Vec<MarkingForm>,
    },
}

/// The serialized form of a marking of a basis: atoms and classes by
/// index, each with its count.
#[derive(Serialize, Deserialize)]
struct MarkingForm {
    /// The atoms with tokens.
    atoms: Vec<(u32, u32)>,
    /// The classes with tickets.
    tickets: Vec<(u32, u32)>,
}

/// The serialized form of a stable sequent of a saturated set: its zones
/// by occurrence, and whether it absorbs.
#[derive(Serialize, Deserialize)]
struct StableForm {
    /// The linear zone, sorted, with repeats.
    linear: Vec<u32>,
    /// The unrestricted zone, sorted, without repeats.
    unrestricted: Vec<u32>,
    /// Whether a `⊤` above absorbs any further linear member.
    absorbs: bool,
}

impl From<&Refutation> for WhyNot {
    /// Converts a refutation into its serialized form.
    fn from(r: &Refutation) -> Self {
        match r {
            &Refutation::Unbalanced(Unbalanced { atom, least, most }) => WhyNot::Unbalanced {
                atom: atom.get(),
                least,
                most,
            },
            &Refutation::OneSided(OneSided {
                atom,
                least,
                most,
                copied,
            }) => WhyNot::OneSided {
                atom: atom.get(),
                least,
                most,
                copied: copied.into(),
            },
            &Refutation::Equation(Equation {
                formulas,
                needed,
                tensors,
                pars,
                ones,
                bottoms,
                mix,
            }) => WhyNot::Equation {
                formulas,
                needed,
                tensors,
                pars,
                ones,
                bottoms,
                mix,
            },
            Refutation::StateEquation(StateEquation {
                atoms,
                clauses,
                dropped,
            }) => WhyNot::StateEquation {
                atoms: atoms.iter().map(|&(a, w)| (a.get(), w)).collect(),
                clauses: clauses.iter().map(|&(o, w)| (o.get(), w)).collect(),
                dropped: dropped.iter().map(|o| o.get()).collect(),
            },
            Refutation::Classical(Classical { assignment }) => WhyNot::Classical {
                assignment: assignment.clone(),
            },
            Refutation::Saturated(Saturated { positive, sequents }) => WhyNot::Saturated {
                positive: positive.iter().map(|&sign| sign.into()).collect(),
                sequents: sequents
                    .iter()
                    .map(|s| StableForm {
                        linear: s.linear.iter().map(|o| o.get()).collect(),
                        unrestricted: s.unrestricted.iter().map(|o| o.get()).collect(),
                        absorbs: s.absorbs,
                    })
                    .collect(),
            },
            Refutation::Basis(Basis {
                body,
                classes,
                markings,
            }) => WhyNot::Basis {
                body: (*body).into(),
                classes: classes
                    .iter()
                    .map(|class| class.iter().map(|o| o.get()).collect())
                    .collect(),
                markings: markings
                    .iter()
                    .map(|m| MarkingForm {
                        atoms: m.atoms.iter().map(|&(a, n)| (a.get(), n)).collect(),
                        tickets: m.tickets.clone(),
                    })
                    .collect(),
            },
            &Refutation::UnbalancedSymbol(UnbalancedSymbol {
                symbol,
                least,
                most,
            }) => WhyNot::UnbalancedSymbol {
                symbol: symbol.get(),
                least,
                most,
            },
            &Refutation::OneSidedSymbol(OneSidedSymbol {
                symbol,
                least,
                most,
                copied,
            }) => WhyNot::OneSidedSymbol {
                symbol: symbol.get(),
                least,
                most,
                copied: copied.into(),
            },
            Refutation::Exhausted => WhyNot::Exhausted,
        }
    }
}

impl From<WhyNot> for Refutation {
    /// Converts a refutation's serialized form back. The disproof's reader
    /// checks its indices against the sequent.
    fn from(w: WhyNot) -> Self {
        match w {
            WhyNot::Exhausted => Refutation::Exhausted,
            WhyNot::Unbalanced { atom, least, most } => Refutation::Unbalanced(Unbalanced {
                atom: Atom::new(atom),
                least,
                most,
            }),
            WhyNot::OneSided {
                atom,
                least,
                most,
                copied,
            } => Refutation::OneSided(OneSided {
                atom: Atom::new(atom),
                least,
                most,
                copied: copied.into(),
            }),
            WhyNot::Equation {
                formulas,
                needed,
                tensors,
                pars,
                ones,
                bottoms,
                mix,
            } => Refutation::Equation(Equation {
                formulas,
                needed,
                tensors,
                pars,
                ones,
                bottoms,
                mix,
            }),
            WhyNot::StateEquation {
                atoms,
                clauses,
                dropped,
            } => Refutation::StateEquation(StateEquation {
                atoms: atoms.into_iter().map(|(a, w)| (Atom::new(a), w)).collect(),
                clauses: clauses
                    .into_iter()
                    .map(|(o, w)| (OccId::new(o), w))
                    .collect(),
                dropped: dropped.into_iter().map(OccId::new).collect(),
            }),
            WhyNot::Classical { assignment } => Refutation::Classical(Classical { assignment }),
            WhyNot::UnbalancedSymbol {
                symbol,
                least,
                most,
            } => Refutation::UnbalancedSymbol(UnbalancedSymbol {
                symbol: Symbol::new(symbol),
                least,
                most,
            }),
            WhyNot::OneSidedSymbol {
                symbol,
                least,
                most,
                copied,
            } => Refutation::OneSidedSymbol(OneSidedSymbol {
                symbol: Symbol::new(symbol),
                least,
                most,
                copied: copied.into(),
            }),
            WhyNot::Basis {
                body,
                classes,
                markings,
            } => Refutation::Basis(Basis::new(
                body.into(),
                classes
                    .into_iter()
                    .map(|class| class.into_iter().map(OccId::new).collect())
                    .collect(),
                markings
                    .into_iter()
                    .map(|m| {
                        Marking::new(
                            m.atoms
                                .into_iter()
                                .map(|(a, n)| (Atom::new(a), n))
                                .collect(),
                            m.tickets,
                        )
                    })
                    .collect(),
            )),
            WhyNot::Saturated { positive, sequents } => Refutation::Saturated(Saturated::new(
                positive.into_iter().map(Sign::from).collect(),
                sequents
                    .into_iter()
                    .map(|s| {
                        Stable::new(
                            s.linear.into_iter().map(OccId::new).collect(),
                            s.unrestricted.into_iter().map(OccId::new).collect(),
                            s.absorbs,
                        )
                    })
                    .collect(),
            )),
        }
    }
}

impl Serialize for Refutation {
    /// Serializes the refutation tagged by its `kind`.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        WhyNot::from(self).serialize(serializer)
    }
}

impl<'a> Deserialize<'a> for Refutation {
    /// Deserializes a refutation from its `kind`, refusing one it does not
    /// know.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        WhyNot::deserialize(deserializer).map(Refutation::from)
    }
}

/// The serialized form of a disproof: its level at the top of a
/// document, the sequent, the mode, the refutation, and the goal where it
/// is not the roots. An unprovable outcome holds the same keys, so it
/// reads back as its disproof.
#[derive(Serialize, Deserialize)]
struct DisproofForm {
    /// 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 mode it is refuted in.
    mode: Mode,
    /// Why it is unprovable.
    refutation: WhyNot,
    /// The goal refuted, absent for the roots.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    goal: Option<Vec<u32>>,
}

impl DisproofForm {
    /// Returns the disproof the form holds, its sequent within `limits`.
    /// Every atom, symbol and occurrence it names is checked against the
    /// sequent. The refutation itself is not checked.
    fn within(self, limits: &Limits) -> Result<Disproof, crate::Error> {
        let sequent = self.sequent.within(limits)?;
        let atoms = sequent.atom_names().len();
        let occurrences = usize::try_from(sequent.occurrences()).unwrap_or(usize::MAX);
        let atom = |atom: Atom| match atom.index() {
            index if index < atoms => Ok(()),
            index => Err(crate::Error::IndexOutOfBounds {
                space: Space::Atom,
                index,
                len: atoms,
            }),
        };
        let symbols = sequent.symbols().len();
        let symbol = |symbol: Symbol| match symbol.index() {
            index if index < symbols => Ok(()),
            index => Err(crate::Error::IndexOutOfBounds {
                space: Space::Symbol,
                index,
                len: symbols,
            }),
        };
        let occurrence = |index: usize| match index {
            index if index < occurrences => Ok(()),
            index => Err(crate::Error::IndexOutOfBounds {
                space: Space::Occurrence,
                index,
                len: occurrences,
            }),
        };
        let refutation = Refutation::from(self.refutation);
        match &refutation {
            Refutation::Unbalanced(unbalanced) => atom(unbalanced.atom)?,
            Refutation::OneSided(one_sided) => atom(one_sided.atom)?,
            Refutation::UnbalancedSymbol(unbalanced) => symbol(unbalanced.symbol)?,
            Refutation::OneSidedSymbol(one_sided) => symbol(one_sided.symbol)?,
            Refutation::StateEquation(equation) => {
                for &(a, _) in &equation.atoms {
                    atom(a)?;
                }
                for &(o, _) in &equation.clauses {
                    occurrence(o.index())?;
                }
                for o in &equation.dropped {
                    occurrence(o.index())?;
                }
            }
            Refutation::Saturated(saturated) => {
                for s in &saturated.sequents {
                    for o in s.linear.iter().chain(&s.unrestricted) {
                        occurrence(o.index())?;
                    }
                }
            }
            Refutation::Basis(basis) => {
                for o in basis.classes.iter().flatten() {
                    occurrence(o.index())?;
                }
                for m in &basis.markings {
                    for &(a, _) in &m.atoms {
                        atom(a)?;
                    }
                }
            }
            Refutation::Exhausted | Refutation::Equation(_) | Refutation::Classical(_) => {}
        }
        let disproof = Disproof::new(sequent, self.mode, refutation);
        Ok(match self.goal {
            None => disproof,
            Some(goal) => {
                for &m in &goal {
                    occurrence(m as usize)?;
                }
                disproof.of_goal(goal.into_iter().map(Member::new).collect())
            }
        })
    }
}

impl Serialize for Disproof {
    /// Serializes the disproof as a document, at the larger of the level
    /// its refutation and mode need and its sequent's.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        DisproofForm {
            version: Some(
                wire::level_of(self.refutation(), self.mode())
                    .max(wire::level_of_sequent(self.sequent())),
            ),
            sequent: SequentForm::from(self.sequent()),
            mode: self.mode(),
            refutation: WhyNot::from(self.refutation()),
            goal: self
                .goal()
                .map(|goal| goal.iter().map(|m| m.get()).collect()),
        }
        .serialize(serializer)
    }
}

impl<'a> Deserialize<'a> for Disproof {
    /// Deserializes a disproof 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 Disproof {}

impl Readable for Disproof {
    const FORM: &'static str = "disproof";

    /// Reads a disproof. Builds its sequent within the limits and checks
    /// every index of its refutation and goal, not the refutation.
    fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
        DisproofForm::deserialize(deserializer)?
            .within(limits)
            .map_err(wire::fail)
    }
}

/// The keys an unprovable outcome adds for its disproof beside its
/// `mode` and `refutation`: the sequent, and the goal when it is not the
/// roots.
#[derive(Serialize)]
struct DisproofKeys<'a> {
    /// The sequent.
    sequent: SequentForm,
    /// The goal refuted, absent for the roots.
    #[serde(skip_serializing_if = "Option::is_none")]
    goal: Option<&'a [Member]>,
}

/// The serialized form of an outcome: the verdict as a word, the reason
/// for `unknown`, the refutation for `unprovable`, and how the search ran.
/// The proof's keys for `proved`, and the disproof's for `unprovable`, are
/// keys of the outcome itself. So the outcome reads as a proof file or a
/// disproof file too.
#[derive(Serialize)]
struct Outcome<'a> {
    /// The wire level, written only at the top of a document.
    #[serde(skip_serializing_if = "Option::is_none")]
    version: Option<u32>,
    /// The crate's version, which wrote the outcome, written only at the
    /// top of a document.
    #[serde(skip_serializing_if = "Option::is_none")]
    deduxit: Option<&'static str>,
    /// `proved`, `unprovable` or `unknown`.
    verdict: &'static str,
    /// Whether the proof passed the checker, for `proved`.
    #[serde(skip_serializing_if = "Option::is_none")]
    checked: Option<bool>,
    /// Why the search could not decide.
    #[serde(skip_serializing_if = "Option::is_none")]
    reason: Option<Why>,
    /// Why the sequent is unprovable.
    #[serde(skip_serializing_if = "Option::is_none")]
    refutation: Option<WhyNot>,
    /// The fragment searched in, by its name in the mode.
    fragment: &'static str,
    /// The mode searched in.
    mode: Mode,
    /// The engine that ran.
    engine: Engine,
    /// What the search cost.
    statistics: Statistics,
    /// The proof, for `proved`.
    #[serde(flatten)]
    proof: Option<Proof>,
    /// What the disproof adds, for `unprovable`.
    #[serde(flatten)]
    disproof: Option<DisproofKeys<'a>>,
}

impl Serialize for Out {
    /// Serializes the outcome as a document: its verdict with its reason,
    /// its proof or its disproof, and the fragment, mode, engine
    /// and statistics of the search.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        form(self, true).serialize(serializer)
    }
}

/// An outcome written inside another document, as the image's outcome in
/// an ordinary outcome: without its level and its writer's version.
pub(super) struct Nested<'a>(pub(super) &'a Out);

impl Serialize for Nested<'_> {
    /// Serializes the outcome's keys without `version` and `deduxit`.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        form(self.0, false).serialize(serializer)
    }
}

/// Returns the wire level of an outcome: the larger of its mode's and its
/// proof's or disproof's sequent's.
pub(super) fn level(outcome: &Out) -> u32 {
    match &outcome.verdict {
        Verdict::Unprovable(d) => {
            wire::level_of(d.refutation(), outcome.mode).max(wire::level_of_sequent(d.sequent()))
        }
        Verdict::Proved(p) => {
            wire::level_in(Some(outcome.mode)).max(wire::level_of_sequent(p.sequent()))
        }
        Verdict::Unknown(_) => wire::level_in(Some(outcome.mode)),
    }
}

/// Returns the form an outcome is written in, with its level and writer
/// at the top of a document.
fn form(outcome: &Out, top: bool) -> Outcome<'_> {
    let verdict = outcome.verdict.name();
    let (reason, refutation, proof, disproof) = match &outcome.verdict {
        Verdict::Proved(p) => (None, None, Some(Proof::keys(p)), None),
        Verdict::Unprovable(d) => {
            let keys = DisproofKeys {
                sequent: SequentForm::from(d.sequent()),
                goal: d.goal(),
            };
            let why = WhyNot::from(d.refutation());
            (None, Some(why), None, Some(keys))
        }
        Verdict::Unknown(r) => (Some(Why::from(*r)), None, None, None),
    };
    Outcome {
        version: top.then(|| level(outcome)),
        deduxit: top.then_some(env!("CARGO_PKG_VERSION")),
        verdict,
        checked: proof.as_ref().map(|_| outcome.checked),
        reason,
        refutation,
        fragment: outcome.fragment.name_in(outcome.mode),
        mode: outcome.mode,
        engine: outcome.engine,
        statistics: outcome.statistics,
        proof,
        disproof,
    }
}

/// The verdict of an outcome read, by its word.
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum VerdictWord {
    /// `proved`.
    Proved,
    /// `unprovable`.
    Unprovable,
    /// `unknown`.
    Unknown,
}

/// An engine's name in an outcome read: an engine of this build, or
/// [`Engine::Unknown`] for a name this build does not know, such as one
/// a later version wrote.
struct EngineRead(Engine);

impl<'a> Deserialize<'a> for EngineRead {
    /// Reads a name, never refusing one this build does not know.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        let name = <std::borrow::Cow<'a, str>>::deserialize(deserializer)?;
        Ok(Self(name.parse().unwrap_or(Engine::Unknown)))
    }
}

/// The keys an outcome is read from: those [`Outcome`] writes, the proof's
/// and the disproof's together, each present for its verdict. Other keys
/// are ignored, among them `deduxit`, the writer's version.
#[derive(Deserialize)]
pub(super) struct OutcomeForm {
    /// The wire level, read only to refuse one above this build's.
    #[serde(default, deserialize_with = "wire::version")]
    #[expect(dead_code, reason = "read for its check of the level alone")]
    version: Option<u32>,
    /// `proved`, `unprovable` or `unknown`.
    verdict: VerdictWord,
    /// Whether the proof passed the checker, for `proved`.
    #[serde(default)]
    checked: Option<bool>,
    /// Why the search could not decide, for `unknown`.
    #[serde(default)]
    reason: Option<Why>,
    /// Why the sequent is unprovable, for `unprovable`.
    #[serde(default)]
    refutation: Option<WhyNot>,
    /// The fragment searched in.
    fragment: Fragment,
    /// The mode searched in.
    mode: Mode,
    /// The engine that ran.
    engine: EngineRead,
    /// What the search cost.
    statistics: Statistics,
    /// The sequent of the proof or the disproof.
    #[serde(default)]
    sequent: Option<SequentForm>,
    /// The proof's nodes.
    #[serde(default)]
    nodes: Option<Vec<Step>>,
    /// The goal off the roots, of the proof or the disproof.
    #[serde(default)]
    goal: Option<Vec<u32>>,
    /// The proof's instance table.
    #[serde(default)]
    instances: Option<Instances>,
}

impl OutcomeForm {
    /// Returns the outcome the form holds. Its proof or disproof is read
    /// within `limits`, as [`Proof`]'s and [`Disproof`]'s readers read
    /// them. A key its verdict needs and the form lacks is an error.
    /// `checked` is false where the key is missing, and the outcome has no
    /// net.
    pub(super) fn within(self, limits: &Limits) -> Result<Out, crate::Error> {
        let missing = |key: &str| crate::Error::Json {
            form: "outcome",
            message: format!("missing field `{key}`"),
        };
        let verdict = match self.verdict {
            VerdictWord::Proved => {
                let sequent = self.sequent.ok_or_else(|| missing("sequent"))?;
                let nodes = self.nodes.ok_or_else(|| missing("nodes"))?;
                let proof = Proof::of_keys(sequent, nodes, self.mode, self.goal, self.instances);
                Verdict::Proved(Box::new(proof.within(limits)?))
            }
            VerdictWord::Unprovable => {
                let disproof = DisproofForm {
                    version: None,
                    sequent: self.sequent.ok_or_else(|| missing("sequent"))?,
                    mode: self.mode,
                    refutation: self.refutation.ok_or_else(|| missing("refutation"))?,
                    goal: self.goal,
                };
                Verdict::Unprovable(Box::new(disproof.within(limits)?))
            }
            VerdictWord::Unknown => {
                Verdict::Unknown(self.reason.ok_or_else(|| missing("reason"))?.into())
            }
        };
        let checked = matches!(verdict, Verdict::Proved(_)) && self.checked.unwrap_or(false);
        Ok(Out {
            verdict,
            fragment: self.fragment,
            mode: self.mode,
            engine: self.engine.0,
            statistics: self.statistics,
            net: None,
            checked,
        })
    }
}

impl<'a> Deserialize<'a> for Out {
    /// Deserializes an 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 Out {}

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

    /// Reads an outcome. Its proof or disproof is read as their own readers
    /// read them: every index is checked, but neither the proof nor the
    /// refutation.
    fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
        OutcomeForm::deserialize(deserializer)?
            .within(limits)
            .map_err(wire::fail)
    }
}

impl Serialize for Engine {
    /// Serializes the engine as its name, such as `"focus"`.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'a> Deserialize<'a> for Engine {
    /// Deserializes an engine from its name.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

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

impl<'a> Deserialize<'a> for Bias {
    /// Deserializes a bias rule from its name.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

/// A value written `"auto"` or as a number.
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum AutoOrNumber {
    /// A number.
    Number(u64),
    /// A word, of which `"auto"` is the one read.
    Word(String),
}

impl AutoOrNumber {
    /// Returns the number, or `None` for `"auto"`. Any other word is an
    /// error.
    fn number<E: serde::de::Error>(self) -> Result<Option<u64>, E> {
        match self {
            Self::Number(n) => Ok(Some(n)),
            Self::Word(word) if word == "auto" => Ok(None),
            Self::Word(word) => Err(E::custom(format!(
                "expected a number or \"auto\", found {word:?}"
            ))),
        }
    }
}

impl Serialize for Jobs {
    /// Serializes the threads as `"auto"` or their number.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Auto => serializer.serialize_str("auto"),
            Self::Count(n) => serializer.serialize_u64(u64::try_from(*n).unwrap_or(u64::MAX)),
        }
    }
}

impl<'a> Deserialize<'a> for Jobs {
    /// Deserializes the threads from `"auto"` or a number.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(match AutoOrNumber::deserialize(deserializer)?.number()? {
            None => Self::Auto,
            Some(n) => Self::Count(usize::try_from(n).unwrap_or(usize::MAX)),
        })
    }
}

impl Serialize for Cadence {
    /// Serializes the cadence as `"auto"` or the number of links.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Auto => serializer.serialize_str("auto"),
            Self::Every(n) => serializer.serialize_u32(*n),
        }
    }
}

impl<'a> Deserialize<'a> for Cadence {
    /// Deserializes the cadence from `"auto"` or a number of links.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(match AutoOrNumber::deserialize(deserializer)?.number()? {
            None => Self::Auto,
            Some(n) => Self::Every(u32::try_from(n).map_err(serde::de::Error::custom)?),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Every reason reads back as itself, and a kind no reason has is
    /// refused.
    #[test]
    fn reasons_read_back() {
        for reason in [
            Reason::Stopped,
            Reason::RecursionLimit { depth: 2048 },
            Reason::CopyBound { copies: 3 },
            Reason::MemoryLimit {
                limit_bytes: 1 << 30,
            },
            Reason::IndexLimit,
            Reason::WorkLimit { limit: 1 << 20 },
            Reason::Unchecked {
                limit_bytes: 1 << 30,
            },
            Reason::WitnessDepth { depth: 64 },
            Reason::Instances { instances: 1 << 16 },
        ] {
            let json = serde_json::to_string(&reason).unwrap();
            assert_eq!(
                serde_json::from_str::<Reason>(&json).unwrap(),
                reason,
                "{json}"
            );
        }
        assert_eq!(
            serde_json::to_string(&Reason::CopyBound { copies: 3 }).unwrap(),
            r#"{"kind":"copy_bound","copies":3}"#
        );
        let unknown = serde_json::from_str::<Reason>(r#"{"kind":"tired"}"#);
        assert!(
            unknown
                .unwrap_err()
                .to_string()
                .contains("unknown variant `tired`")
        );
    }

    /// Every refutation reads back as itself, and a kind no refutation
    /// has is refused, never read as `exhausted`.
    #[test]
    fn refutations_read_back() {
        let (a, o) = (Atom::new, OccId::new);
        for refutation in [
            Refutation::Exhausted,
            Refutation::Unbalanced(Unbalanced {
                atom: a(1),
                least: 1,
                most: 2,
            }),
            Refutation::OneSided(OneSided {
                atom: a(0),
                least: -2,
                most: -1,
                copied: Sign::Dual,
            }),
            Refutation::Equation(Equation {
                formulas: 2,
                needed: 3,
                tensors: 1,
                pars: 0,
                ones: 0,
                bottoms: 0,
                mix: false,
            }),
            Refutation::StateEquation(StateEquation {
                atoms: vec![(a(0), 2), (a(2), -1)],
                clauses: vec![(o(3), 1)],
                dropped: vec![o(5)],
            }),
            Refutation::Saturated(Saturated::new(
                vec![Sign::Atom, Sign::Dual],
                vec![
                    Stable::new(vec![o(1), o(1), o(4)], vec![o(2)], false),
                    Stable::new(Vec::new(), Vec::new(), true),
                ],
            )),
        ] {
            let json = serde_json::to_string(&refutation).unwrap();
            let back = serde_json::from_str::<Refutation>(&json).unwrap();
            assert_eq!(back, refutation, "{json}");
        }
        let unknown = serde_json::from_str::<Refutation>(r#"{"kind":"tableau"}"#);
        let message = unknown.unwrap_err().to_string();
        assert!(message.contains("unknown variant `tableau`"), "{message}");
    }
}