summaryrefslogtreecommitdiff
path: root/source/Checking/Declaration.hs
blob: f95286cfc3f8add98883f15a084db6025edcc9c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}

-- | Builder-confined authorization and atomic typed declaration append.
module Checking.Declaration
    ( ModuleDriver
    , DriverFailure(..)
    , DriverResult(..)
    , ImportedModuleEvidence
    , ImportedAliasOrigin(..)
    , freshImportedModuleEvidence
    , validateImportedModuleEvidence
    , importSealedModule
    , importSealedModuleDriver
    , nextDeclarationSlotDriver
    , currentTheoryDriver
    , currentFoundationAxiomDriver
    , resolveVisibleFactAliasDriver
    , resolveVisibleFactTargetsDriver
    , resolveVisibleGlobalDriver
    , resolveVisibleGlobalContentDriver
    , ResolvedStructure
    , resolvedStructureDescriptor
    , resolvedStructurePredicate
    , resolvedStructureOperation
    , resolvedStructureOperations
    , resolveVisibleStructureDriver
    , resolveVisibleStructureOperationObjectsDriver
    , objectAvailableDriver
    , objectTypeDriver
    , LoweringDriver
    , runProspectiveLoweringDriver
    , nextDeclarationSlotLowering
    , currentTheoryLowering
    , currentFoundationAxiomLowering
    , resolveVisibleFactAliasLowering
    , resolveVisibleFactTargetsLowering
    , resolveVisibleGlobalLowering
    , resolveVisibleGlobalContentLowering
    , resolveVisibleStructureLowering
    , resolveVisibleStructureOperationObjectsLowering
    , objectAvailableLowering
    , objectTypeLowering
    , runModuleDriver
    , ValidationLookup
    , validationLookup
    , ValidationRun(..)
    , failModuleDriver
    , failDeclarationDriver
    , VampireResolver
    , vampireBatchResolver
    , vampireBatchResolverWithPreparationObserver
    , vampireResolver
    , vampireSubmissionResolver
    , Declaration
    , failDeclaration
    , addDeclarationObject
    , addDeclarationProposition
    , resolveVisibleGlobal
    , stageSemanticGlobalBinding
    , stageSemanticStructureDescriptor
    , CandidateSpec
    , candidateSpec
    , CandidatePlanningSpec
    , CheckedCandidate
    , checkedCandidate
    , checkedDefinitionEquationPlanning
    , checkedSourceAxiomPlanning
    , checkedDatatypePlanning
    , checkedKernelPlanning
    , checkedSourceProofPlanning
    , checkedOmittedPlanning
    , CheckedPlannedVampireRequest
    , checkedPlannedVampireRequest
    , plannedEarlierCandidate
    , CheckedDeclaration
    , checkedProofDeclaration
    , checkedCompiledDeclaration
    , admitCheckedDeclaration
    , PlannedDeclaration
    , planCheckedDeclaration
    , admitPlannedCheckedDeclaration
    , plannedDeclarationPreviousPrefix
    , plannedDeclarationNextPrefix
    , plannedDeclarationDelta
    , PlanningIntegrityError(..)
    , prepareCandidateSpecDriver
    , prepareFrozenCandidateSpecDriver
    , prepareDefinitionEquationSpecDriver
    , preparePointwiseDefinitionEquationSpecDriver
    , prepareStagedCandidateVampireDriver
    , prepareCandidateSpecLowering
    , prepareFrozenCandidateSpecLowering
    , prepareDefinitionEquationSpecLowering
    , preparePointwiseDefinitionEquationSpecLowering
    , prepareStagedCandidateVampireLowering
    , ReservedCandidate
    , reserveCandidate
    , reserveCandidateBatch
    , reservePropositionCandidate
    , reserveFrozenPropositionCandidateBatch
    , reserveDefinitionEquationCandidate
    , reservePointwiseDefinitionEquationCandidate
    , reserveDefinitionEquationCandidateBatch
    , reservedCandidateSlot
    , reservedCandidateStage
    , CandidateProof
    , locateProofObligation
    , recordOmittedUse
    , VampirePremiseSelection(..)
    , VampireObligationPreparationError(..)
    , ScopedVampirePremise
    , scopedVampirePremise
    , PreparedVampireObligation
    , prepareScopedVampireObligationDriver
    , prepareScopedContradictionObligationDriver
    , prepareScopedVampireObligationLowering
    , prepareScopedContradictionObligationLowering
    , useAuthorizedFact
    , useStagedCandidate
    , LocalClaim
    , proveLocalKernelClaim
    , useLocalClaim
    , authorizeKernelProofCandidate
    , authorizeKernelConstructionCandidate
    , authorizeDefinitionEquationCandidate
    , acceptVampireObligation
    , acceptPreparedVampireObligation
    , acceptCurrentCandidateVampire
    , prepareCurrentCandidateVampire
    , authorizeVampireCandidate
    , authorizeVampireCandidateBatch
    , authorizeSourceAxiomCandidate
    , authorizeOmittedCandidate
    , authorizeDatatypeCompilationCandidates
    , authorizeCompiledDeclaration
    , commitProofDeclaration
    , commitCompiledDeclaration
    , CommittedDeclarationBatch
    , committedBatchOwner
    , committedBatchSlot
    , committedBatchPreviousPrefix
    , committedBatchNextPrefix
    , committedBatchDelta
    , committedBatchObjects
    , committedBatchPropositions
    , committedBatchProofValidations
    , committedBatchDeclarationValidation
    , PendingModulePrefix
    , emptyPendingModulePrefix
    , pendingModulePrefixBatches
    , pendingModulePrefixCurrent
    , ValidationIntegrityError(..)
    , renderValidationIntegrityError
    , DeclarationError(..)
    , declarationErrorLocation
    , renderDeclarationError
    , DriverOpenError(..)
    , renderDriverOpenError
    ) where

import Base
import Checking.Authority
import Checking.Backend.Problem qualified as Backend
import Checking.Backend.Tptp qualified as Tptp
import Checking.Core
import Checking.Foundation
import Checking.Identity
import Checking.Kernel.Derivation
import Checking.Semantic
import Checking.Materialization qualified as Materialization
import Felix.Cache.Codec (encodeCache)
import Felix.Module
import Provers qualified
import Report.Location
import Syntax.Abstract (StructSymbol)

import Control.Exception qualified as Exception
import Control.DeepSeq (deepseq)
import Control.Monad.Except (ExceptT)
import Control.Monad.Except qualified as Except
import Control.Monad (foldM, unless, when)
import Control.Monad.State.Strict (StateT)
import Control.Monad.State.Strict qualified as State
import Data.Bifunctor (first)
import Data.ByteString qualified as ByteString
import Data.List qualified as List
import Data.List.NonEmpty qualified as NonEmpty
import Data.Map.Strict qualified as Map
import Data.Maybe (catMaybes, mapMaybe)
import Data.Set qualified as Set
import Data.Text qualified as Text
import Data.Unique (Unique, newUnique)
import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)
import Data.Vector (Vector)
import Data.Vector qualified as Vector
import Numeric.Natural (Natural)


newtype BuilderIdentity = BuilderIdentity Unique
    deriving stock (Eq)

newtype DeclarationInvocation = DeclarationInvocation Natural
    deriving stock (Eq)

newtype CandidateStage = CandidateStage Natural
    deriving stock (Show, Eq, Ord)

data ValidationLookup = ValidationLookup
    !(ProofValidationKey -> IO (Maybe ProofValidationRecord))
    !(DeclarationValidationKey
        -> IO (Maybe DeclarationValidationRecord))

validationLookup
    :: (ProofValidationKey -> IO (Maybe ProofValidationRecord))
    -> (DeclarationValidationKey
        -> IO (Maybe DeclarationValidationRecord))
    -> ValidationLookup
validationLookup =
    ValidationLookup

data ValidationRun
    = FreshValidation
    | WarmValidation !ValidationLookup

data ValidationIntegrityError
    = CachedValidationIntegrityError
        !Materialization.MaterializationError
    deriving stock (Show, Eq)

instance Exception.Exception ValidationIntegrityError

renderValidationIntegrityError :: ValidationIntegrityError -> Text
renderValidationIntegrityError = \case
    CachedValidationIntegrityError failure ->
        "cached validation does not match its exact contextual input: "
            <> Text.pack (show failure)


data BuilderFactAuthorization = BuilderFactAuthorization
    !BuilderIdentity
    !FactSlot
    !FactAuthority

data PendingFactAuthorization = PendingFactAuthorization
    !BuilderIdentity
    !PrefixContextId
    !DeclarationInvocation
    !FactSlot
    !FactAuthority
    !CandidateStage

-- | Checked fact semantics paired with caller-selected evidence.  Semantic
-- lookup and request preparation deliberately ignore the evidence parameter;
-- only the admitted builder instantiation may consume capabilities.
data FactEntry evidence = FactEntry
    !CheckedPropositionContent
    !SemanticFactOccurrence
    !evidence

-- | The shared checked semantic state.  The evidence parameter makes the
-- distinction between admitted authority and future inert planning data
-- visible without duplicating lookup, collision, closure, or delta logic.
data BuilderState evidence = BuilderState
    { logicalBuilderIdentity :: !BuilderIdentity
    , logicalBuilderFoundation :: !CheckedFoundation
    , logicalBuilderTheory :: !TheoryId
    , logicalBuilderOwner :: !ModuleName
    , logicalBuilderDirectSemanticInputs :: ![SemanticInterfaceId]
    , logicalBuilderPrefix :: !PrefixContextId
    , logicalBuilderObjectClosure :: !CheckedObjectClosure
    , logicalBuilderFacts
        :: !(Map
            SemanticFactOccurrenceFingerprint
            (FactEntry evidence))
    , logicalBuilderAliases
        :: !(Map SemanticName ImportedAliasBinding)
    , logicalBuilderGlobals
        :: !(Map SemanticGlobalKey SemanticGlobalTarget)
    , logicalBuilderStructures
        :: !(Map SemanticStructurePhrase ResolvedStructure)
    , logicalBuilderImportedInterfaces :: !(Set SemanticInterfaceId)
    , logicalBuilderDeltas :: ![DeclarationInterfaceDelta]
    , logicalBuilderNextDeclaration :: !Natural
    , logicalBuilderNextFact :: !Natural
    , logicalBuilderNextInvocation :: !Natural
    }

-- | The only production builder in this milestone.  Capability-consuming
-- operations below accept this admitted instantiation, never a polymorphic
-- 'BuilderState'.
type LogicalBuilder = BuilderState BuilderFactAuthorization

-- | Public semantic contract and strict declaration-stage provenance for a
-- prospective fact.  It deliberately contains no builder identity, prefix,
-- declaration invocation, pending authorization, or minting capability.
data PlanningProvenance = PlanningProvenance
    !DeclarationSlot
    !CandidateStage
    !FactSlot
    deriving stock (Eq)

data PlanningEvidence = PlanningEvidence
    !FactAuthority
    !(Maybe PlanningProvenance)

data ResolvedStructureOperation = ResolvedStructureOperation
    !ObjectId
    !SemanticStructurePhrase
    deriving stock (Show, Eq)

data ResolvedStructure = ResolvedStructure
    !SemanticStructureDescriptor
    !(Set SemanticStructurePhrase)
    !(Map StructSymbol ResolvedStructureOperation)
    deriving stock (Show, Eq)

resolvedStructureDescriptor
    :: ResolvedStructure
    -> SemanticStructureDescriptor
resolvedStructureDescriptor (ResolvedStructure descriptor _ _) =
    descriptor

resolvedStructurePredicate :: ResolvedStructure -> Maybe ObjectId
resolvedStructurePredicate =
    semanticStructureDescriptorPredicate . resolvedStructureDescriptor

resolvedStructureOperation
    :: StructSymbol
    -> ResolvedStructure
    -> Maybe ObjectId
resolvedStructureOperation symbol (ResolvedStructure _ _ operations) =
    operationObject <$> Map.lookup symbol operations
  where
    operationObject (ResolvedStructureOperation object _origin) = object

resolvedStructureOperations
    :: ResolvedStructure
    -> Map StructSymbol ObjectId
resolvedStructureOperations (ResolvedStructure _ _ operations) =
    operationObject <$> operations
  where
    operationObject (ResolvedStructureOperation object _origin) = object

structureOperationBindings
    :: Map SemanticStructurePhrase ResolvedStructure
    -> Set (StructSymbol, ObjectId)
structureOperationBindings structures =
    Set.fromList
        [ (symbol, object)
        | structure <- Map.elems structures
        , (symbol, object) <-
            Map.toAscList (resolvedStructureOperations structure)
        ]


data CommittedDeclarationBatch = CommittedDeclarationBatch
    !ModuleName
    !DeclarationSlot
    !PrefixContextId
    !PrefixContextId
    !DeclarationInterfaceDelta
    ![AssertedObject]
    ![CheckedPropositionContent]
    ![ProofValidationRecord]
    !(Maybe DeclarationValidationRecord)

committedBatchOwner :: CommittedDeclarationBatch -> ModuleName
committedBatchOwner
        (CommittedDeclarationBatch owner _ _ _ _ _ _ _ _) =
    owner

committedBatchSlot
    :: CommittedDeclarationBatch
    -> DeclarationSlot
committedBatchSlot
        (CommittedDeclarationBatch _ slot _ _ _ _ _ _ _) =
    slot

committedBatchPreviousPrefix
    :: CommittedDeclarationBatch
    -> PrefixContextId
committedBatchPreviousPrefix
        (CommittedDeclarationBatch _ _ previous _ _ _ _ _ _) =
    previous

committedBatchNextPrefix
    :: CommittedDeclarationBatch
    -> PrefixContextId
committedBatchNextPrefix
        (CommittedDeclarationBatch _ _ _ next _ _ _ _ _) =
    next

committedBatchDelta
    :: CommittedDeclarationBatch
    -> DeclarationInterfaceDelta
committedBatchDelta
        (CommittedDeclarationBatch _ _ _ _ delta _ _ _ _) =
    delta

committedBatchObjects
    :: CommittedDeclarationBatch
    -> [AssertedObject]
committedBatchObjects
        (CommittedDeclarationBatch _ _ _ _ _ objects _ _ _) =
    objects

committedBatchPropositions
    :: CommittedDeclarationBatch
    -> [CheckedPropositionContent]
committedBatchPropositions
        (CommittedDeclarationBatch _ _ _ _ _ _ propositions _ _) =
    propositions

committedBatchProofValidations
    :: CommittedDeclarationBatch
    -> [ProofValidationRecord]
committedBatchProofValidations
        (CommittedDeclarationBatch _ _ _ _ _ _ _ validations _) =
    validations

committedBatchDeclarationValidation
    :: CommittedDeclarationBatch
    -> Maybe DeclarationValidationRecord
committedBatchDeclarationValidation
        (CommittedDeclarationBatch _ _ _ _ _ _ _ _ validation) =
    validation


data PendingModulePrefix = PendingModulePrefix
    !PrefixContextId
    ![CommittedDeclarationBatch]

emptyPendingModulePrefix
    :: PrefixContextId
    -> PendingModulePrefix
emptyPendingModulePrefix prefix =
    PendingModulePrefix prefix []

instance Show PendingModulePrefix where
    show prefix =
        "PendingModulePrefix {pendingModulePrefixCurrent = "
            <> show (pendingModulePrefixCurrent prefix)
            <> ", pendingModulePrefixBatchCount = "
            <> show (length (pendingModulePrefixBatches prefix))
            <> "}"

pendingModulePrefixBatches
    :: PendingModulePrefix
    -> [CommittedDeclarationBatch]
pendingModulePrefixBatches
        (PendingModulePrefix _ batchesReversed) =
    reverse batchesReversed

pendingModulePrefixCurrent
    :: PendingModulePrefix
    -> PrefixContextId
pendingModulePrefixCurrent
        (PendingModulePrefix prefix _batches) =
    prefix

appendPendingBatch
    :: CommittedDeclarationBatch
    -> PendingModulePrefix
    -> PendingModulePrefix
appendPendingBatch batch (PendingModulePrefix _ batches) =
    forceCommittedBatch batch `seq`
        PendingModulePrefix
            (committedBatchNextPrefix batch)
            (batch : batches)

forceCommittedBatch :: CommittedDeclarationBatch -> ()
forceCommittedBatch
        (CommittedDeclarationBatch
            owner slot previous next delta objects propositions
            proofValidations declarationValidation) =
    owner `seq`
    slot `seq`
    previous `seq`
    next `seq`
    ByteString.length
        (encodeCache (putDeclarationInterfaceDeltaCache delta)) `seq`
    objects `deepseq`
    propositions `deepseq`
    forceProofValidations proofValidations `seq`
    forceDeclarationValidation declarationValidation
  where
    forceProofValidations =
        foldl'
            (\() record ->
                proofValidationRecordKey record `seq`
                ByteString.length
                    (encodeCache
                        (putValidationCertificateCache
                            (proofValidationRecordCertificate
                                record))) `seq` ())
            ()

    forceDeclarationValidation = \case
        Nothing -> ()
        Just record ->
            declarationValidationRecordKey record `seq`
            foldl'
                (\() certificate ->
                    ByteString.length
                        (encodeCache
                            (putValidationCertificateCache
                                certificate)) `seq` ())
                ()
                (declarationValidationRecordCertificates record)


data VampireResolverMode
    = SynchronousVampireResolution
        (forall local origin.
            NonEmpty
                (Provers.PreparedTypedProverTask
                    SemanticFactOccurrenceFingerprint
                    local
                    origin
                    ObjectId)
            -> IO
                (NonEmpty
                    (Either
                        Provers.ProverProcessError
                        Provers.ProverAnswer)))
    | AsynchronousVampireSubmission
        (NonEmpty Provers.PreparedVerificationRequest
            -> IO (NonEmpty Provers.VampireHandle))

data VampireResolver = VampireResolver
    !VampireResolverMode
    !(Word64 -> IO ())

vampireBatchResolver
    :: (forall local origin.
        NonEmpty
            (Provers.PreparedTypedProverTask
                SemanticFactOccurrenceFingerprint
                local
                origin
                ObjectId)
        -> IO
            (NonEmpty
                (Either
                    Provers.ProverProcessError
                    Provers.ProverAnswer)))
    -> VampireResolver
vampireBatchResolver resolve =
    vampireBatchResolverWithPreparationObserver resolve (const (pure ()))

vampireBatchResolverWithPreparationObserver
    :: (forall local origin.
        NonEmpty
            (Provers.PreparedTypedProverTask
                SemanticFactOccurrenceFingerprint
                local
                origin
                ObjectId)
        -> IO
            (NonEmpty
                (Either
                    Provers.ProverProcessError
                    Provers.ProverAnswer)))
    -> (Word64 -> IO ())
    -> VampireResolver
vampireBatchResolverWithPreparationObserver resolve observe =
    VampireResolver (SynchronousVampireResolution resolve) observe

-- | Production submission-only resolver.  Retained-plan admission consumes
-- the submitted handles through its private synchronous replay resolver.
vampireSubmissionResolver
    :: (NonEmpty Provers.PreparedVerificationRequest
        -> IO (NonEmpty Provers.VampireHandle))
    -> (Word64 -> IO ())
    -> VampireResolver
vampireSubmissionResolver submit observe =
    VampireResolver (AsynchronousVampireSubmission submit) observe

vampireResolver
    :: (forall local origin.
        Provers.PreparedTypedProverTask
            SemanticFactOccurrenceFingerprint
            local
            origin
            ObjectId
        -> IO
            (Either
                Provers.ProverProcessError
                Provers.ProverAnswer))
    -> VampireResolver
vampireResolver resolve =
    vampireBatchResolver (traverse resolve)

resolveOneVampire
    :: VampireResolver
    -> Provers.PreparedTypedProverTask
        SemanticFactOccurrenceFingerprint
        local
        origin
        ObjectId
    -> ExceptT DeclarationError IO
        (Either
            Provers.ProverProcessError
            Provers.ProverAnswer)
resolveOneVampire resolver prepared = do
    results@(result :| _) <-
        liftIO (resolveSynchronousVampireBatch resolver (prepared :| []))
    void
        (Except.liftEither
            (validateVampireResolverResultCount 1 results))
    pure result

resolveSynchronousVampireBatch
    :: VampireResolver
    -> NonEmpty
        (Provers.PreparedTypedProverTask
            SemanticFactOccurrenceFingerprint
            local
            origin
            ObjectId)
    -> IO
        (NonEmpty
            (Either
                Provers.ProverProcessError
                Provers.ProverAnswer))
resolveSynchronousVampireBatch
        (VampireResolver mode _observe) tasks =
    case mode of
        SynchronousVampireResolution resolve -> resolve tasks
        AsynchronousVampireSubmission{} ->
            throwIO
                (PlanningIntegrityError
                    "asynchronous Vampire resolver reached synchronous admission")

observeVampirePreparation
    :: VampireResolver
    -> Word64
    -> IO ()
observeVampirePreparation (VampireResolver _mode observe) = observe

validateVampireResolverResultCount
    :: Int
    -> NonEmpty value
    -> Either DeclarationError [value]
validateVampireResolverResultCount expected results
    | expected == actual =
        Right (NonEmpty.toList results)
    | otherwise =
        Left (VampireResolverBatchSizeMismatch expected actual)
  where
    actual = NonEmpty.length results

data DriverState = DriverState
    !VampireResolver
    !LogicalBuilder
    !PendingModulePrefix
    !ValidationRun

-- | Authority-free semantic state used while lowering checked declarations.
-- Existing admitted facts are projected to their public contracts; no
-- builder-local authorization capability crosses this boundary.
newtype ProspectiveBuilder = ProspectiveBuilder
    (BuilderState PlanningEvidence)

data LoweringState = LoweringState
    !VampireResolver
    !ProspectiveBuilder
    !ValidationRun

newtype LoweringDriver value = LoweringDriver
    { runLoweringStep :: StateT LoweringState IO value
    }
    deriving newtype (Functor, Applicative, Monad)

newtype ModuleDriver failure value = ModuleDriver
    { runDriverStep
        :: ExceptT
            (DriverFailure failure)
            (StateT DriverState IO)
            value
    }
    deriving newtype (Functor, Applicative, Monad)

-- | Run one complete authority-free planning action from the current admitted
-- input projection.  The prospective state advances throughout the action but
-- never mutates the authoritative module builder.
runProspectiveLoweringDriver
    :: LoweringDriver value
    -> ModuleDriver failure value
runProspectiveLoweringDriver action = ModuleDriver do
    DriverState resolver builder _prefix validation <- State.get
    State.lift
        (liftIO
            (State.evalStateT
                (runLoweringStep action)
                (LoweringState resolver
                    (projectLogicalBuilder builder)
                    validation)))

projectLogicalBuilder :: LogicalBuilder -> ProspectiveBuilder
projectLogicalBuilder builder =
    ProspectiveBuilder
        builder
            { logicalBuilderFacts =
                fmap projectFact (logicalBuilderFacts builder)
            }
  where
    projectFact (FactEntry proposition occurrence _authorization) =
        FactEntry proposition occurrence
            (PlanningEvidence
                (semanticFactAuthority occurrence)
                Nothing)

data DriverFailure failure
    = DriverDeclarationFailed !DeclarationError
    | DriverActionFailed !failure
    deriving stock (Show, Eq)

data DriverResult failure value
    = DriverSucceeded
        !value
        !SemanticInterface
        !PendingModulePrefix
        !CheckedObjectClosure
    | DriverFailed
        !(DriverFailure failure)
        !PendingModulePrefix
    | DriverSealFailed
        !SemanticInterfaceError
        !PendingModulePrefix

data ImportedAliasOrigin = ImportedAliasOrigin
    !DeclarationSlot
    !SemanticFactOccurrenceFingerprint
    deriving stock (Show, Eq)

data ImportedAliasBinding = ImportedAliasBinding
    !SemanticFactOccurrenceFingerprint
    !ImportedAliasOrigin

-- | Opaque evidence produced from a successfully sealed producer.  Direct
-- parents retain the semantic DAG; importing folds it deterministically and
-- mints fresh authority for the consuming builder.
data ImportedModuleEvidence = ImportedModuleEvidence
    !SemanticInterface
    ![ImportedModuleEvidence]
    !(Map
        SemanticFactOccurrenceFingerprint
        (SemanticFactOccurrence, CheckedPropositionContent))
    ![AssertedObject]

freshImportedModuleEvidence
    :: [ImportedModuleEvidence]
    -> SemanticInterface
    -> PendingModulePrefix
    -> ImportedModuleEvidence
freshImportedModuleEvidence parents interface prefix =
    ImportedModuleEvidence
        interface
        parents
        (Map.fromList
            [ ( semanticFactFingerprint occurrence
              , (occurrence, requireProposition occurrence)
              )
            | occurrence <- occurrences
            ])
        objects
  where
    batches = pendingModulePrefixBatches prefix
    objects = concatMap committedBatchObjects batches
    propositions = concatMap committedBatchPropositions batches
    propositionMap =
        Map.fromList
            [ (checkedPropositionId proposition, proposition)
            | proposition <- propositions
            ]
    occurrences =
        concatMap
            declarationDeltaFacts
            (semanticInterfaceDeclarations interface)

    requireProposition occurrence =
        case Map.lookup
                (semanticFactProposition occurrence)
                propositionMap of
            Just proposition ->
                proposition
            Nothing ->
                impossible
                    ("sealed fact occurrence references absent proposition "
                        <> show (semanticFactProposition occurrence))

-- | Construct import evidence after a trusted producer or validated store
-- installation has supplied the complete canonical proposition payloads.
validateImportedModuleEvidence
    :: TheoryId
    -> [ImportedModuleEvidence]
    -> SemanticInterface
    -> [AssertedObject]
    -> [CheckedPropositionContent]
    -> Either DeclarationError ImportedModuleEvidence
validateImportedModuleEvidence
        theory parents interface objects propositions = do
    _ <- first ImportedEvidenceInterfaceFailed
        (validateSemanticInterface
            (semanticInterfaceOwner interface)
            (semanticInterfaceDirectInputs interface)
            (semanticInterfaceDeclarations interface)
            (semanticInterfaceAssertedId interface))
    unless
        (semanticInterfaceDirectInputs interface == parentIds)
        (Left
            (ImportedEvidenceDirectMismatch
                (semanticInterfaceDirectInputs interface)
                parentIds))
    let propositionMap =
            Map.fromList
                [ (checkedPropositionId proposition, proposition)
                | proposition <- propositions
                ]
        objectMap =
            Map.fromList
                [ (assertedObjectId object, object)
                | object <- objects
                ]
        localObjectIds =
            concatMap
                declarationDeltaObjects
                (semanticInterfaceDeclarations interface)
        parentObjectMap =
            foldl'
                (Map.unionWith const)
                Map.empty
                (evidenceObjectMap <$> parents)
    localObjects <- traverse
        (\identity ->
            maybe
                (Left (ImportedEvidenceObjectMissing identity))
                Right
                (Map.lookup identity objectMap))
        localObjectIds
    closure <- first DeclarationObjectValidationFailed
        (validateObjectClosure
            theory
            (Map.elems parentObjectMap <> localObjects))
    let occurrences =
            concatMap
                declarationDeltaFacts
                (semanticInterfaceDeclarations interface)
    pairs <- traverse
        (\occurrence -> do
            proposition <- maybe
                (Left
                    (ImportedEvidencePropositionMissing
                        (semanticFactProposition occurrence)))
                Right
                (Map.lookup
                    (semanticFactProposition occurrence)
                    propositionMap)
            _ <- first DeclarationPropositionValidationFailed
                (validateAssertedPropositionContent
                    closure
                    (checkedPropositionId proposition)
                    (frozenCoreTerm
                        (checkedPropositionTerm proposition)))
            _ <- first ImportedFactMaterializationFailed
                (Materialization.checkImportedOccurrence
                    theory
                    (semanticFactFingerprint occurrence)
                    occurrence
                    proposition
                    (semanticFactAuthority occurrence))
            pure
                ( semanticFactFingerprint occurrence
                , (occurrence, proposition)
                ))
        occurrences
    let evidence =
            ImportedModuleEvidence
                interface
                parents
                (Map.fromList pairs)
                localObjects
    _ <- validateEvidenceInventory theory closure evidence
    pure evidence
  where
    parentIds =
        semanticInterfaceAssertedId . evidenceInterface <$> parents

validateEvidenceInventory
    :: TheoryId
    -> CheckedObjectClosure
    -> ImportedModuleEvidence
    -> Either DeclarationError ()
validateEvidenceInventory theory closure evidence =
    do
        void (foldEvidence Set.empty Map.empty Map.empty evidence)
        (_seen, structures) <-
            foldStructures Set.empty Map.empty evidence
        void (foldGlobals structures Set.empty Map.empty evidence)
  where
    foldEvidence seen facts aliases current
        | identity `Set.member` seen =
            Right (seen, facts, aliases)
        | otherwise = do
            unless
                (semanticInterfaceDirectInputs interface == parentIds)
                (Left
                    (ImportedEvidenceDirectMismatch
                        (semanticInterfaceDirectInputs interface)
                        parentIds))
            (parentsSeen, parentFacts, parentAliases) <-
                foldM
                    (\(seen', facts', aliases') parent ->
                        foldEvidence seen' facts' aliases' parent)
                    (seen, facts, aliases)
                    parents
            localFacts <- foldM insertFact parentFacts (Map.elems entries)
            localAliases <- foldM
                (insertAlias localFacts)
                parentAliases
                [ ( alias
                  , ImportedAliasOrigin
                        (declarationDeltaSlot delta)
                        (semanticAliasTarget alias)
                  )
                | delta <- semanticInterfaceDeclarations interface
                , alias <- declarationDeltaAliases delta
                ]
            pure
                ( Set.insert identity parentsSeen
                , localFacts
                , localAliases
                )
      where
        ImportedModuleEvidence interface parents entries _objects = current
        identity = semanticInterfaceAssertedId interface
        parentIds =
            semanticInterfaceAssertedId . evidenceInterface <$> parents

    insertFact facts pair@(occurrence, proposition) = do
        let fingerprint = semanticFactFingerprint occurrence
        _ <- first ImportedFactMaterializationFailed
            (Materialization.checkImportedOccurrence
                theory
                fingerprint
                occurrence
                proposition
                (semanticFactAuthority occurrence))
        case Map.lookup fingerprint facts of
            Nothing ->
                Right (Map.insert fingerprint pair facts)
            Just (existingOccurrence, existingProposition)
                | existingOccurrence == occurrence
                  && checkedPropositionId existingProposition
                    == checkedPropositionId proposition ->
                    Right facts
                | otherwise ->
                    Left (ImportedFactCollision fingerprint)

    insertAlias facts aliases (alias, origin) = do
        let name = semanticAliasName alias
            target = semanticAliasTarget alias
        unless
            (Map.member target facts)
            (Left (ImportedAliasTargetMissing target))
        case Map.lookup name aliases of
            Nothing ->
                Right
                    (Map.insert
                        name
                        (ImportedAliasBinding target origin)
                        aliases)
            Just (ImportedAliasBinding existingTarget existingOrigin)
                | existingTarget == target ->
                    Right aliases
                | otherwise ->
                    Left
                        (ImportedAliasCollision
                            name existingOrigin origin)

    foldGlobals structures seen globals current
        | identity `Set.member` seen =
            Right (seen, globals)
        | otherwise = do
            (parentsSeen, parentGlobals) <-
                foldM
                    (\(seen', globals') parent ->
                        foldGlobals structures seen' globals' parent)
                    (seen, globals)
                    parents
            globals' <-
                foldM
                    (insertGlobal
                        (structureOperationBindings structures))
                    parentGlobals
                    [ binding
                    | delta <- semanticInterfaceDeclarations interface
                    , binding <- semanticEnvironmentBindings
                        (declarationDeltaEnvironment delta)
                    ]
            pure (Set.insert identity parentsSeen, globals')
      where
        ImportedModuleEvidence interface parents _entries _objects = current
        identity = semanticInterfaceAssertedId interface

    insertGlobal operationBindings globals binding = do
        let key = semanticGlobalBindingKey binding
            target = semanticGlobalBindingTarget binding
        _ <-
            first
                (ImportedGlobalTargetInvalid key target)
                (validateSemanticGlobalBindingTarget
                    operationBindings
                    closure binding)
        case Map.lookup key globals of
            Nothing -> Right (Map.insert key target globals)
            Just existing
                | existing == target -> Right globals
                | otherwise ->
                    Left (ImportedGlobalCollision key existing target)

    foldStructures seen structures current
        | identity `Set.member` seen =
            Right (seen, structures)
        | otherwise = do
            (parentsSeen, parentStructures) <-
                foldM
                    (\(seen', structures') parent ->
                        foldStructures seen' structures' parent)
                    (seen, structures)
                    parents
            structures' <-
                foldM
                    (insertSemanticStructure closure)
                    parentStructures
                    [ descriptor
                    | delta <- semanticInterfaceDeclarations interface
                    , descriptor <- semanticEnvironmentStructures
                        (declarationDeltaEnvironment delta)
                    ]
            pure (Set.insert identity parentsSeen, structures')
      where
        ImportedModuleEvidence interface parents _entries _objects = current
        identity = semanticInterfaceAssertedId interface

evidenceInterface :: ImportedModuleEvidence -> SemanticInterface
evidenceInterface
        (ImportedModuleEvidence interface _parents _entries _objects) =
    interface

evidenceObjectMap
    :: ImportedModuleEvidence
    -> Map ObjectId AssertedObject
evidenceObjectMap
        (ImportedModuleEvidence _interface parents _entries objects) =
    foldl'
        (Map.unionWith const)
        (Map.fromList
            [ (assertedObjectId object, object)
            | object <- objects
            ])
        (evidenceObjectMap <$> parents)

data DriverOpenError
    = DriverInitialPrefixError !PrefixContextError
    | DriverInitialObjectError !ObjectValidationError
    deriving stock (Show, Eq)

renderDriverOpenError :: DriverOpenError -> Text
renderDriverOpenError = \case
    DriverInitialPrefixError{} ->
        "the initial semantic prefix is inconsistent"
    DriverInitialObjectError{} ->
        "the initial object closure is inconsistent"

runModuleDriver
    :: CheckedFoundation
    -> ModuleName
    -> [SemanticInterfaceId]
    -> VampireResolver
    -> ValidationRun
    -> ModuleDriver failure value
    -> IO
        (Either
            DriverOpenError
            (DriverResult failure value))
runModuleDriver
        foundation owner direct resolver validationRun action = do
    unique <- BuilderIdentity <$> newUnique
    let theory = theoryId foundation
    case (,) <$>
            first DriverInitialPrefixError
                (initialPrefixContextId theory owner direct)
            <*>
            first DriverInitialObjectError
                (validateObjectClosure theory []) of
        Left err ->
            pure (Left err)
        Right (prefix, closure) -> do
            let builder =
                    BuilderState
                        { logicalBuilderIdentity = unique
                        , logicalBuilderFoundation = foundation
                        , logicalBuilderTheory = theory
                        , logicalBuilderOwner = owner
                        , logicalBuilderDirectSemanticInputs = direct
                        , logicalBuilderPrefix = prefix
                        , logicalBuilderObjectClosure = closure
                        , logicalBuilderFacts = Map.empty
                        , logicalBuilderAliases = Map.empty
                        , logicalBuilderGlobals = Map.empty
                        , logicalBuilderStructures = Map.empty
                        , logicalBuilderImportedInterfaces = Set.empty
                        , logicalBuilderDeltas = []
                        , logicalBuilderNextDeclaration = 0
                        , logicalBuilderNextFact = 0
                        , logicalBuilderNextInvocation = 0
                        }
                initialState =
                    DriverState
                        resolver
                        builder
                        (PendingModulePrefix prefix [])
                        validationRun
            (result, DriverState _ finalBuilder finalPrefix _) <-
                State.runStateT
                    (Except.runExceptT
                        (runDriverStep action))
                    initialState
            case result of
                Left err ->
                    pure (Right (DriverFailed err finalPrefix))
                Right value -> do
                    case semanticInterface
                            owner
                            direct
                            (reverse
                                (logicalBuilderDeltas
                                    finalBuilder)) of
                        Left err ->
                            pure
                                (Right
                                    (DriverSealFailed
                                        err
                                        finalPrefix))
                        Right interface ->
                            pure
                                (Right
                                    (DriverSucceeded
                                        value
                                        interface
                                        finalPrefix
                                        (logicalBuilderObjectClosure
                                            finalBuilder)))

failModuleDriver :: failure -> ModuleDriver failure value
failModuleDriver err =
    ModuleDriver
        (Except.throwError
            (DriverActionFailed err))

failDeclarationDriver :: DeclarationError -> ModuleDriver failure value
failDeclarationDriver err =
    ModuleDriver (Except.throwError (DriverDeclarationFailed err))

nextDeclarationSlotDriver
    :: ModuleDriver failure DeclarationSlot
nextDeclarationSlotDriver = ModuleDriver do
    DriverState _resolver builder _prefix _validation <- State.get
    pure
        (declarationSlot
            (logicalBuilderOwner builder)
            (localDeclarationOrdinal
                (logicalBuilderNextDeclaration builder)))

currentTheoryDriver :: ModuleDriver failure TheoryId
currentTheoryDriver =
    ModuleDriver
        (State.gets
            (\(DriverState _resolver builder _prefix _validation) ->
                logicalBuilderTheory builder))

currentFoundationAxiomDriver
    :: FoundationAxiomTag
    -> ModuleDriver failure (FrozenCheckedCore Void)
currentFoundationAxiomDriver tag =
    ModuleDriver
        (State.gets
            (\(DriverState _resolver builder _prefix _validation) ->
                foundationAxiomFrozen
                    (logicalBuilderFoundation builder)
                    tag))

resolveVisibleFactAliasDriver
    :: SemanticName
    -> ModuleDriver failure
        (Maybe SemanticFactOccurrenceFingerprint)
resolveVisibleFactAliasDriver alias = ModuleDriver do
    DriverState _resolver builder _prefix _validation <- State.get
    pure do
        ImportedAliasBinding fingerprint _origin <-
            Map.lookup alias (logicalBuilderAliases builder)
        pure fingerprint

resolveVisibleFactTargetsDriver
    :: FrozenCheckedCore ObjectId
    -> ModuleDriver failure
        [SemanticFactOccurrenceFingerprint]
resolveVisibleFactTargetsDriver target = ModuleDriver do
    DriverState _resolver builder _prefix _validation <- State.get
    pure
        [ fingerprint
        | (fingerprint, FactEntry proposition _occurrence _authorization) <-
            Map.toAscList (logicalBuilderFacts builder)
        , checkedPropositionTerm proposition == target
        ]

resolveVisibleGlobalDriver
    :: SemanticGlobalKey
    -> ModuleDriver failure (Maybe (SemanticGlobalTarget, CoreType))
resolveVisibleGlobalDriver key = ModuleDriver do
    DriverState _resolver builder _prefix _validation <- State.get
    pure
        ( (\(target, _content, _dependencies) ->
                ( target
                , fromMaybe
                    (impossible "visible semantic key has no source type")
                    (semanticGlobalKeyType key)
                ))
            <$> resolveVisibleGlobalContent builder key
        )

resolveVisibleGlobalContentDriver
    :: SemanticGlobalKey
    -> ModuleDriver failure
        (Maybe
            ( SemanticGlobalTarget
            , ObjectContent
            , Map ObjectId CoreType
            ))
resolveVisibleGlobalContentDriver key = ModuleDriver do
    DriverState _resolver builder _prefix _validation <- State.get
    pure (resolveVisibleGlobalContent builder key)

resolveVisibleStructureDriver
    :: SemanticStructurePhrase
    -> ModuleDriver failure (Maybe ResolvedStructure)
resolveVisibleStructureDriver structurePhrase = ModuleDriver do
    DriverState _resolver builder _prefix _validation <- State.get
    pure (Map.lookup structurePhrase (logicalBuilderStructures builder))

resolveVisibleStructureOperationObjectsDriver
    :: StructSymbol
    -> ModuleDriver failure [ObjectId]
resolveVisibleStructureOperationObjectsDriver symbol = ModuleDriver do
    DriverState _resolver builder _prefix _validation <- State.get
    pure
        ( Set.toAscList
            (Set.fromList
                (mapMaybe
                    (resolvedStructureOperation symbol)
                    (Map.elems (logicalBuilderStructures builder))))
        )

resolveVisibleGlobalContent
    :: BuilderState evidence
    -> SemanticGlobalKey
    -> Maybe
        ( SemanticGlobalTarget
        , ObjectContent
        , Map ObjectId CoreType
        )
resolveVisibleGlobalContent builder key = do
    target <- Map.lookup key (logicalBuilderGlobals builder)
    content <-
        lookupCheckedObjectContent
            (semanticGlobalTargetObject target)
            closure
    let dependencies =
            Map.fromList
                [ (identity, requireDependency identity)
                | identity <- case content of
                    TransparentObjectContent _theory _coreType body ->
                        Set.toAscList (canonicalTermGlobals body)
                    _ -> []
                ]
    pure
        ( target
        , content
        , dependencies
        )
  where
    closure = logicalBuilderObjectClosure builder

    requireDependency identity =
        case lookupCheckedObjectType identity closure of
            Just coreType -> coreType
            Nothing ->
                impossible "checked object dependency is absent"

objectAvailableDriver
    :: ObjectId
    -> ModuleDriver failure Bool
objectAvailableDriver identity =
    ModuleDriver
        (State.gets
            (\(DriverState _resolver builder _prefix _validation) ->
                isJust
                    (lookupCheckedObjectType
                        identity
                        (logicalBuilderObjectClosure builder))))

objectTypeDriver
    :: ObjectId
    -> ModuleDriver failure (Maybe CoreType)
objectTypeDriver identity =
    ModuleDriver
        (State.gets
            (\(DriverState _resolver builder _prefix _validation) ->
                lookupCheckedObjectType
                    identity
                    (logicalBuilderObjectClosure builder)))

nextDeclarationSlotLowering :: LoweringDriver DeclarationSlot
nextDeclarationSlotLowering =
    withLoweringBuilder \builder ->
        declarationSlot
            (logicalBuilderOwner builder)
            (localDeclarationOrdinal
                (logicalBuilderNextDeclaration builder))

currentTheoryLowering :: LoweringDriver TheoryId
currentTheoryLowering =
    withLoweringBuilder logicalBuilderTheory

currentFoundationAxiomLowering
    :: FoundationAxiomTag
    -> LoweringDriver (FrozenCheckedCore Void)
currentFoundationAxiomLowering tag =
    withLoweringBuilder
        (\builder ->
            foundationAxiomFrozen
                (logicalBuilderFoundation builder)
                tag)

resolveVisibleFactAliasLowering
    :: SemanticName
    -> LoweringDriver (Maybe SemanticFactOccurrenceFingerprint)
resolveVisibleFactAliasLowering alias =
    withLoweringBuilder \builder -> do
        ImportedAliasBinding fingerprint _origin <-
            Map.lookup alias (logicalBuilderAliases builder)
        pure fingerprint

resolveVisibleFactTargetsLowering
    :: FrozenCheckedCore ObjectId
    -> LoweringDriver [SemanticFactOccurrenceFingerprint]
resolveVisibleFactTargetsLowering target =
    withLoweringBuilder \builder ->
        [ fingerprint
        | (fingerprint, FactEntry proposition _occurrence _evidence) <-
            Map.toAscList (logicalBuilderFacts builder)
        , checkedPropositionTerm proposition == target
        ]

resolveVisibleGlobalLowering
    :: SemanticGlobalKey
    -> LoweringDriver (Maybe (SemanticGlobalTarget, CoreType))
resolveVisibleGlobalLowering key =
    withLoweringBuilder \builder ->
        ( (\(target, _content, _dependencies) ->
                ( target
                , fromMaybe
                    (impossible "visible semantic key has no source type")
                    (semanticGlobalKeyType key)
                ))
            <$> resolveVisibleGlobalContent builder key
        )

resolveVisibleGlobalContentLowering
    :: SemanticGlobalKey
    -> LoweringDriver
        (Maybe
            ( SemanticGlobalTarget
            , ObjectContent
            , Map ObjectId CoreType
            ))
resolveVisibleGlobalContentLowering key =
    withLoweringBuilder (\builder -> resolveVisibleGlobalContent builder key)

resolveVisibleStructureLowering
    :: SemanticStructurePhrase
    -> LoweringDriver (Maybe ResolvedStructure)
resolveVisibleStructureLowering phrase =
    withLoweringBuilder (Map.lookup phrase . logicalBuilderStructures)

resolveVisibleStructureOperationObjectsLowering
    :: StructSymbol
    -> LoweringDriver [ObjectId]
resolveVisibleStructureOperationObjectsLowering symbol =
    withLoweringBuilder \builder ->
        Set.toAscList
            (Set.fromList
                (mapMaybe
                    (resolvedStructureOperation symbol)
                    (Map.elems (logicalBuilderStructures builder))))

objectAvailableLowering :: ObjectId -> LoweringDriver Bool
objectAvailableLowering identity =
    withLoweringBuilder
        (isJust
            . lookupCheckedObjectType identity
            . logicalBuilderObjectClosure)

objectTypeLowering :: ObjectId -> LoweringDriver (Maybe CoreType)
objectTypeLowering identity =
    withLoweringBuilder
        (lookupCheckedObjectType identity
            . logicalBuilderObjectClosure)

withLoweringBuilder
    :: (BuilderState PlanningEvidence -> value)
    -> LoweringDriver value
withLoweringBuilder action = LoweringDriver do
    LoweringState _resolver (ProspectiveBuilder builder) _validation <- State.get
    pure (action builder)


data CandidateSpec = CandidateSpec
    !CheckedPropositionContent
    !FactSearchEligibility
    ![SemanticName]

candidateSpec
    :: CheckedPropositionContent
    -> FactSearchEligibility
    -> [SemanticName]
    -> CandidateSpec
candidateSpec =
    CandidateSpec

-- | One strictly earlier candidate in the same checked declaration.  The
-- position is structural and becomes a concrete fact slot only while the
-- declaration is planned.
data PlannedCandidatePosition = PlannedCandidatePosition
    !Natural
    !Natural
    deriving stock (Show, Eq, Ord)

data CandidatePlanningDirect
    = PlanningDefinitionEquation !ObjectId
    | PlanningSourceAxiom
    | PlanningTrustedDatatype !DatatypeCompilationDescriptor
    | PlanningKernelConstruction !KernelConstructionDescriptor
    | PlanningCheckedSourceProof
    | PlanningOmitted
    deriving stock (Show, Eq)

-- | Erased exact request data needed by scheduling and public-contract
-- planning.  The family body retains the typed obligation used by admission;
-- this projection carries only its one canonical request and exact global
-- premise fingerprints.
data CheckedPlannedVampireRequest = CheckedPlannedVampireRequest
    !Location
    !Provers.PreparedVerificationRequest
    ![SemanticFactOccurrenceFingerprint]

data CandidatePlanningSpec = CandidatePlanningSpec
    !CandidatePlanningDirect
    ![SemanticFactOccurrenceFingerprint]
    ![PlannedCandidatePosition]
    ![CheckedPlannedVampireRequest]

-- | One authority-free checked candidate and its exact planning contract.
-- The two parts are constructed together by the declaration-family lowerer
-- and retain no builder capability or publication path.
data CheckedCandidate = CheckedCandidate
    !CandidateSpec
    !CandidatePlanningSpec

checkedCandidate
    :: CandidateSpec
    -> CandidatePlanningSpec
    -> CheckedCandidate
checkedCandidate = CheckedCandidate

checkedDefinitionEquationPlanning :: ObjectId -> CandidatePlanningSpec
checkedDefinitionEquationPlanning identity =
    CandidatePlanningSpec
        (PlanningDefinitionEquation identity) [] [] []

checkedSourceAxiomPlanning :: CandidatePlanningSpec
checkedSourceAxiomPlanning =
    CandidatePlanningSpec PlanningSourceAxiom [] [] []

checkedDatatypePlanning
    :: DatatypeCompilationDescriptor
    -> CandidatePlanningSpec
checkedDatatypePlanning descriptor =
    CandidatePlanningSpec (PlanningTrustedDatatype descriptor) [] [] []

checkedKernelPlanning
    :: KernelConstructionDescriptor
    -> [SemanticFactOccurrenceFingerprint]
    -> CandidatePlanningSpec
checkedKernelPlanning descriptor facts =
    CandidatePlanningSpec
        (PlanningKernelConstruction descriptor)
        facts
        []
        []

checkedSourceProofPlanning
    :: [CheckedPlannedVampireRequest]
    -> [PlannedCandidatePosition]
    -> CandidatePlanningSpec
checkedSourceProofPlanning requests staged =
    CandidatePlanningSpec
        PlanningCheckedSourceProof [] staged requests

checkedOmittedPlanning
    :: [CheckedPlannedVampireRequest]
    -> [PlannedCandidatePosition]
    -> CandidatePlanningSpec
checkedOmittedPlanning requests staged =
    CandidatePlanningSpec PlanningOmitted [] staged requests

checkedPlannedVampireRequest
    :: Location
    -> PreparedVampireObligation local origin
    -> CheckedPlannedVampireRequest
checkedPlannedVampireRequest location
        (PreparedVampireObligation expected task) =
    CheckedPlannedVampireRequest
        location
        (Provers.preparedTypedProverRequest task)
        ( Backend.typedBackendFactReference
            <$> Vector.toList
                (Backend.typedProblemGlobalPremises expected)
        )

plannedEarlierCandidate
    :: Natural
    -> Natural
    -> PlannedCandidatePosition
plannedEarlierCandidate =
    PlannedCandidatePosition

data CheckedDeclarationMode
    = CheckedProofMode !ProofSyntaxId
    | CheckedCompiledMode !DeclarationSyntaxId

-- | One completely lowered, authority-free declaration transaction.  The
-- family body is a closed checked authorization recipe owned by its exact
-- lowerer; structural effects and stable source-ordered candidate stages are
-- common.  This value is invocation-local and never serialized.
data CheckedDeclaration body = CheckedDeclaration
    !CheckedDeclarationMode
    ![AssertedObject]
    ![CheckedPropositionContent]
    ![SemanticGlobalBinding]
    ![SemanticStructureDescriptor]
    ![NonEmpty CheckedCandidate]
    !body

checkedProofDeclaration
    :: ProofSyntaxId
    -> [AssertedObject]
    -> [CheckedPropositionContent]
    -> [SemanticGlobalBinding]
    -> [SemanticStructureDescriptor]
    -> [NonEmpty CheckedCandidate]
    -> body
    -> CheckedDeclaration body
checkedProofDeclaration
        syntax objects propositions globals structures stages =
    CheckedDeclaration
        (CheckedProofMode syntax) objects propositions globals structures
        stages

checkedCompiledDeclaration
    :: DeclarationSyntaxId
    -> [AssertedObject]
    -> [CheckedPropositionContent]
    -> [SemanticGlobalBinding]
    -> [SemanticStructureDescriptor]
    -> [NonEmpty CheckedCandidate]
    -> body
    -> CheckedDeclaration body
checkedCompiledDeclaration
        syntax objects propositions globals structures stages =
    CheckedDeclaration
        (CheckedCompiledMode syntax) objects propositions globals structures
        stages

prepareCandidateSpecDriver
    :: [AssertedObject]
    -> ScopedCheckedCore ObjectId
    -> FactSearchEligibility
    -> [SemanticName]
    -> ModuleDriver failure (Either DeclarationError CandidateSpec)
prepareCandidateSpecDriver objects scoped eligibility aliases =
    prepareCandidateSpecWithDriverClosure objects
        (\closure ->
            prepareScopedCandidateSpec
                closure scoped eligibility aliases)

prepareFrozenCandidateSpecDriver
    :: [AssertedObject]
    -> FrozenCheckedCore ObjectId
    -> FactSearchEligibility
    -> [SemanticName]
    -> ModuleDriver failure (Either DeclarationError CandidateSpec)
prepareFrozenCandidateSpecDriver objects frozen eligibility aliases =
    prepareCandidateSpecWithDriverClosure objects
        (\closure ->
            prepareFrozenCandidateSpec
                closure frozen eligibility aliases)

prepareDefinitionEquationSpecDriver
    :: [AssertedObject]
    -> ObjectId
    -> SemanticName
    -> ModuleDriver failure (Either DeclarationError CandidateSpec)
prepareDefinitionEquationSpecDriver objects identity alias =
    prepareCandidateSpecWithDriverClosure objects
        (\closure ->
            prepareDefinitionEquationSpec closure identity alias)

preparePointwiseDefinitionEquationSpecDriver
    :: [AssertedObject]
    -> ObjectId
    -> SemanticName
    -> ModuleDriver failure (Either DeclarationError CandidateSpec)
preparePointwiseDefinitionEquationSpecDriver objects identity alias =
    prepareCandidateSpecWithDriverClosure objects
        (\closure ->
            preparePointwiseDefinitionEquationSpec closure identity alias)

prepareCandidateSpecLowering
    :: [AssertedObject]
    -> ScopedCheckedCore ObjectId
    -> FactSearchEligibility
    -> [SemanticName]
    -> LoweringDriver (Either DeclarationError CandidateSpec)
prepareCandidateSpecLowering objects scoped eligibility aliases =
    prepareCandidateSpecWithLoweringClosure objects
        (\closure ->
            prepareScopedCandidateSpec
                closure scoped eligibility aliases)

prepareFrozenCandidateSpecLowering
    :: [AssertedObject]
    -> FrozenCheckedCore ObjectId
    -> FactSearchEligibility
    -> [SemanticName]
    -> LoweringDriver (Either DeclarationError CandidateSpec)
prepareFrozenCandidateSpecLowering objects frozen eligibility aliases =
    prepareCandidateSpecWithLoweringClosure objects
        (\closure ->
            prepareFrozenCandidateSpec
                closure frozen eligibility aliases)

prepareDefinitionEquationSpecLowering
    :: [AssertedObject]
    -> ObjectId
    -> SemanticName
    -> LoweringDriver (Either DeclarationError CandidateSpec)
prepareDefinitionEquationSpecLowering objects identity alias =
    prepareCandidateSpecWithLoweringClosure objects
        (\closure ->
            prepareDefinitionEquationSpec closure identity alias)

preparePointwiseDefinitionEquationSpecLowering
    :: [AssertedObject]
    -> ObjectId
    -> SemanticName
    -> LoweringDriver (Either DeclarationError CandidateSpec)
preparePointwiseDefinitionEquationSpecLowering objects identity alias =
    prepareCandidateSpecWithLoweringClosure objects
        (\closure ->
            preparePointwiseDefinitionEquationSpec closure identity alias)

-- | Prepare one closed Vampire obligation whose only premise is a
-- conditionally available fact from a strictly earlier candidate stage of
-- the same declaration.  The temporary checked stage contains public fact
-- semantics and structural provenance only; admission must still consume the
-- corresponding real reserved candidate before accepting this request.
prepareStagedCandidateVampireDriver
    :: Location
    -> [AssertedObject]
    -> CandidateSpec
    -> CandidateSpec
    -> ModuleDriver failure
        (Either
            DeclarationError
            (PreparedVampireObligation Void ()))
prepareStagedCandidateVampireDriver
        location objects premiseSpec targetSpec =
    ModuleDriver do
        DriverState resolver builder _prefix _validation <- State.get
        State.lift
            (liftIO
                (prepareStagedCandidateVampireWith
                    resolver builder location objects premiseSpec targetSpec))

prepareStagedCandidateVampireLowering
    :: Location
    -> [AssertedObject]
    -> CandidateSpec
    -> CandidateSpec
    -> LoweringDriver
        (Either
            DeclarationError
            (PreparedVampireObligation Void ()))
prepareStagedCandidateVampireLowering
        location objects premiseSpec targetSpec =
    LoweringDriver do
        LoweringState resolver (ProspectiveBuilder builder) _validation <-
            State.get
        liftIO
            (prepareStagedCandidateVampireWith
                resolver builder location objects premiseSpec targetSpec)

prepareStagedCandidateVampireWith
    :: VampireResolver
    -> BuilderState evidence
    -> Location
    -> [AssertedObject]
    -> CandidateSpec
    -> CandidateSpec
    -> IO
        (Either
            DeclarationError
            (PreparedVampireObligation Void ()))
prepareStagedCandidateVampireWith
        resolver builder location objects premiseSpec targetSpec = do
    let staged = do
            closure <-
                first DeclarationObjectValidationFailed
                    (extendObjectClosure
                        (logicalBuilderObjectClosure builder)
                        objects)
            premise <-
                prospectiveStagePremise
                    builder closure premiseSpec targetSpec
            pure (closure, premise)
    case staged of
        Left failure -> pure (Left failure)
        Right (closure, premise) -> do
            prepared <-
                measureVampirePreparation resolver
                    (prepareClosedCandidateVampire
                        builder closure
                        (candidateSpecProposition targetSpec)
                        [premise])
            pure
                (first
                    (ProofObligationFailedAt location
                        . CurrentCandidateVampirePreparationFailed)
                    prepared)

candidateSpecProposition :: CandidateSpec -> CheckedPropositionContent
candidateSpecProposition (CandidateSpec proposition _eligibility _aliases) =
    proposition

prospectiveStagePremise
    :: BuilderState evidence
    -> CheckedObjectClosure
    -> CandidateSpec
    -> CandidateSpec
    -> Either DeclarationError CheckedPropositionContent
prospectiveStagePremise builder closure premiseSpec targetSpec = do
    let owner = logicalBuilderOwner builder
        declaration =
            declarationSlot owner
                (localDeclarationOrdinal
                    (logicalBuilderNextDeclaration builder))
        premiseSlot =
            factSlot owner
                (localFactOrdinal (logicalBuilderNextFact builder))
        targetSlot =
            factSlot owner
                (localFactOrdinal (logicalBuilderNextFact builder + 1))
        premiseStage = CandidateStage 0
        targetStage = CandidateStage 1
        proposition = candidateSpecProposition premiseSpec
        authority =
            factAuthority
                (theoremRef
                    (logicalBuilderTheory builder)
                    (checkedPropositionId proposition))
                cleanAuthoritySafety
        CandidateSpec _ eligibility _aliases = premiseSpec
        occurrence =
            semanticFactOccurrence premiseSlot authority eligibility
        stage =
            CheckedDeclarationStage declaration closure
                (Map.singleton premiseSlot
                        (FactEntry proposition occurrence
                            (PlanningEvidence
                                authority
                                (Just
                                    (PlanningProvenance
                                        declaration premiseStage premiseSlot)))))
    unless
        (propositionMatchesClosure closure
            (candidateSpecProposition targetSpec))
        (Left (PlanningFactContractMismatch targetSlot))
    useProspectiveStageFact
        stage targetStage targetSlot premiseStage premiseSlot

useProspectiveStageFact
    :: CheckedDeclarationStage
    -> CandidateStage
    -> FactSlot
    -> CandidateStage
    -> FactSlot
    -> Either DeclarationError CheckedPropositionContent
useProspectiveStageFact
        (CheckedDeclarationStage ownSlot closure entries)
        currentStage currentSlot expectedStage premiseSlot = do
    FactEntry proposition occurrence
        (PlanningEvidence authority provenance) <-
            maybe
                (Left (PlanningFactContractMismatch premiseSlot))
                Right
                (Map.lookup premiseSlot entries)
    unless
        ( provenance
            == Just
                (PlanningProvenance
                    ownSlot expectedStage premiseSlot)
          && expectedStage < currentStage
          && semanticFactSlot occurrence == premiseSlot
          && semanticFactAuthority occurrence == authority
          && propositionMatchesClosure closure proposition
        )
        (Left (PlanningFactContractMismatch currentSlot))
    pure proposition

prepareCandidateSpecWithDriverClosure
    :: [AssertedObject]
    -> (CheckedObjectClosure -> Either DeclarationError CandidateSpec)
    -> ModuleDriver failure (Either DeclarationError CandidateSpec)
prepareCandidateSpecWithDriverClosure objects prepare = ModuleDriver do
    DriverState _resolver builder _prefix _validation <- State.get
    pure do
        closure <-
            first DeclarationObjectValidationFailed
                (extendObjectClosure
                    (logicalBuilderObjectClosure builder)
                    objects)
        prepare closure

prepareCandidateSpecWithLoweringClosure
    :: [AssertedObject]
    -> (CheckedObjectClosure -> Either DeclarationError CandidateSpec)
    -> LoweringDriver (Either DeclarationError CandidateSpec)
prepareCandidateSpecWithLoweringClosure objects prepare =
    withLoweringBuilder \builder -> do
        closure <-
            first DeclarationObjectValidationFailed
                (extendObjectClosure
                    (logicalBuilderObjectClosure builder)
                    objects)
        prepare closure

data ReservedCandidate = ReservedCandidate
    !BuilderIdentity
    !PrefixContextId
    !DeclarationInvocation
    !CandidateStage
    !FactSlot
    !CandidateSpec

reservedCandidateSlot :: ReservedCandidate -> FactSlot
reservedCandidateSlot
        (ReservedCandidate _ _ _ _ slot _) =
    slot

reservedCandidateStage :: ReservedCandidate -> Natural
reservedCandidateStage
        (ReservedCandidate _ _ _ (CandidateStage stage) _ _) =
    stage

candidateCheckedProposition
    :: ReservedCandidate
    -> CheckedPropositionContent
candidateCheckedProposition
        (ReservedCandidate _ _ _ _ _ (CandidateSpec proposition _ _)) =
    proposition

candidateTheoremReference
    :: BuilderState evidence
    -> ReservedCandidate
    -> TheoremRef
candidateTheoremReference builder candidate =
    theoremRef
        (logicalBuilderTheory builder)
        (checkedPropositionId
            (candidateCheckedProposition candidate))


data PendingCandidate = PendingCandidate
    !ReservedCandidate
    !ValidationCertificate
    !PendingFactAuthorization

data DeclarationValidationSelection
    = DeclarationValidationUnselected
    | FreshDeclarationValidation
    | CachedDeclarationValidation
        !DeclarationSyntaxId
        ![ObjectId]
        ![TheoremId]
        !DeclarationValidationRecord
        !(Map FactSlot Natural)

data DeclarationState = DeclarationState
    { declarationVampireResolver :: !VampireResolver
    , declarationValidationRun :: !ValidationRun
    , declarationValidationMode :: !ValidationMode
    , declarationValidationSelection
        :: !DeclarationValidationSelection
    , declarationBuilder :: !LogicalBuilder
    , declarationOwnSlot :: !DeclarationSlot
    , declarationInvocation :: !DeclarationInvocation
    , declarationObjectsReversed :: ![AssertedObject]
    , declarationObjectClosure :: !(Maybe CheckedObjectClosure)
    , declarationPropositionsReversed
        :: ![CheckedPropositionContent]
    , declarationGlobalBindingsReversed
        :: ![SemanticGlobalBinding]
    , declarationStructureDescriptorsReversed
        :: ![SemanticStructureDescriptor]
    , declarationReservations
        :: !(Map FactSlot ReservedCandidate)
    , declarationPending :: !(Map FactSlot PendingCandidate)
    , declarationNextFact :: !Natural
    , declarationNextStage :: !Natural
    , declarationAuthorizationFrontier :: !Natural
    }

-- | Authority-free view of checked declaration-local semantics.  This is the
-- narrow staging substrate for later lowerers: it carries the exact object
-- closure and conditional public fact contracts, but no builder identity,
-- prefix, invocation, pending authorization, admitted alias, or published
-- occurrence.
data CheckedDeclarationStage = CheckedDeclarationStage
    !DeclarationSlot
    !CheckedObjectClosure
    !(Map FactSlot (FactEntry PlanningEvidence))

newtype Declaration value = Declaration
    { runDeclaration
        :: StateT
            DeclarationState
            (ExceptT DeclarationError IO)
            value
    }
    deriving newtype (Functor, Applicative, Monad)

failDeclaration :: DeclarationError -> Declaration value
failDeclaration =
    Declaration . State.lift . Except.throwError

addDeclarationObject :: AssertedObject -> Declaration ()
addDeclarationObject asserted = Declaration do
    state <- State.get
    case declarationValidationSelection state of
        DeclarationValidationUnselected -> pure ()
        _ ->
            State.lift
                (Except.throwError
                    DeclarationShapeChangedAfterValidationLookup)
    when
        (isJust (declarationObjectClosure state))
        (State.lift
            (Except.throwError
                DeclarationObjectAddedAfterAuthorization))
    State.put
        state
            { declarationObjectsReversed =
                asserted : declarationObjectsReversed state
            }

addDeclarationProposition
    :: CheckedPropositionContent
    -> Declaration ()
addDeclarationProposition proposition =
    Declaration
        (State.modify' \state ->
            state
                { declarationPropositionsReversed =
                    proposition
                        : declarationPropositionsReversed state
                })

resolveVisibleGlobal
    :: SemanticGlobalKey
    -> Declaration (Maybe (SemanticGlobalTarget, CoreType))
resolveVisibleGlobal key = Declaration do
    state <- State.get
    let builder = declarationBuilder state
    pure do
        target <- Map.lookup key (logicalBuilderGlobals builder)
        coreType <- semanticGlobalKeyType key
        pure (target, coreType)

stageSemanticGlobalBinding
    :: SemanticGlobalKey
    -> SemanticGlobalTarget
    -> Declaration ()
stageSemanticGlobalBinding key target = Declaration do
    state <- State.get
    case declarationValidationSelection state of
        DeclarationValidationUnselected -> pure ()
        _ ->
            State.lift
                (Except.throwError
                    DeclarationShapeChangedAfterValidationLookup)
    when
        (any
            ((== key) . semanticGlobalBindingKey)
            (declarationGlobalBindingsReversed state))
        (State.lift
            (Except.throwError
                (DeclarationGlobalAlreadyStaged key)))
    State.put
        state
            { declarationGlobalBindingsReversed =
                semanticGlobalBinding key target
                    : declarationGlobalBindingsReversed state
            }

stageSemanticStructureDescriptor
    :: SemanticStructureDescriptor
    -> Declaration ()
stageSemanticStructureDescriptor descriptor = Declaration do
    state <- State.get
    case declarationValidationSelection state of
        DeclarationValidationUnselected -> pure ()
        _ ->
            State.lift
                (Except.throwError
                    DeclarationShapeChangedAfterValidationLookup)
    let structurePhrase = semanticStructureDescriptorPhrase descriptor
    when
        (any
            ((== structurePhrase) . semanticStructureDescriptorPhrase)
            (declarationStructureDescriptorsReversed state))
        (State.lift
            (Except.throwError
                (DeclarationStructureAlreadyStaged structurePhrase)))
    State.put
        state
            { declarationStructureDescriptorsReversed =
                descriptor
                    : declarationStructureDescriptorsReversed state
            }

prepareScopedCandidateSpec
    :: CheckedObjectClosure
    -> ScopedCheckedCore ObjectId
    -> FactSearchEligibility
    -> [SemanticName]
    -> Either DeclarationError CandidateSpec
prepareScopedCandidateSpec closure scoped eligibility aliases = do
    frozen <-
        maybe (Left CandidatePropositionNotClosed) Right
            (closeScopedCore scoped)
    prepareFrozenCandidateSpec closure frozen eligibility aliases

prepareFrozenCandidateSpec
    :: CheckedObjectClosure
    -> FrozenCheckedCore ObjectId
    -> FactSearchEligibility
    -> [SemanticName]
    -> Either DeclarationError CandidateSpec
prepareFrozenCandidateSpec closure frozen eligibility aliases = do
    unless
        (frozenCoreType frozen == TyProp)
        (Left
            (CandidatePropositionNotProposition
                (frozenCoreType frozen)))
    proposition <-
        first DeclarationPropositionValidationFailed
            (validatePropositionContent closure (frozenCoreTerm frozen))
    pure (candidateSpec proposition eligibility aliases)

prepareDefinitionEquationSpec
    :: CheckedObjectClosure
    -> ObjectId
    -> SemanticName
    -> Either DeclarationError CandidateSpec
prepareDefinitionEquationSpec closure identity alias = do
    content <-
        maybe
            (Left (DefinitionEquationObjectMissing identity))
            Right
            (lookupCheckedObjectContent identity closure)
    (coreType, body) <-
        case content of
            TransparentObjectContent _theory objectType objectBody ->
                Right (objectType, objectBody)
            _ ->
                Left (DefinitionEquationObjectNotTransparent identity)
    proposition <-
        first DeclarationPropositionValidationFailed
            (validatePropositionContent
                closure
                (CEq coreType (CGlobal identity) body))
    pure (candidateSpec proposition SearchEligible [alias])

preparePointwiseDefinitionEquationSpec
    :: CheckedObjectClosure
    -> ObjectId
    -> SemanticName
    -> Either DeclarationError CandidateSpec
preparePointwiseDefinitionEquationSpec closure identity alias = do
    content <-
        maybe
            (Left (DefinitionEquationObjectMissing identity))
            Right
            (lookupCheckedObjectContent identity closure)
    body <-
        case content of
            TransparentObjectContent _theory
                    (TyArrow TySet TyProp) (CLam TySet predicate) ->
                Right predicate
            _ ->
                Left
                    (DefinitionEquationObjectNotPointwisePredicate identity)
    proposition <-
        first DeclarationPropositionValidationFailed
            (validatePropositionContent
                closure
                (CForall TySet
                    (CEq TyProp
                        (CApp (CGlobal identity) (CBound 0))
                        body)))
    pure (candidateSpec proposition SearchEligible [alias])

reserveCandidate
    :: CandidateSpec
    -> Declaration ReservedCandidate
reserveCandidate spec =
    NonEmpty.head <$> reserveCandidateBatch (spec :| [])

-- | Validate and reserve one closed checked proposition in the current
-- declaration closure.
reservePropositionCandidate
    :: ScopedCheckedCore ObjectId
    -> FactSearchEligibility
    -> [SemanticName]
    -> Declaration ReservedCandidate
reservePropositionCandidate scoped eligibility aliases = Declaration do
    unprepared <- State.get
    prepared <-
        State.lift
            (Except.liftEither
                (prepareDeclarationClosure unprepared))
    spec <-
        State.lift
            (Except.liftEither
                (prepareScopedCandidateSpec
                    (fromMaybe
                        (impossible
                            "prepared proposition closure is absent")
                        (declarationObjectClosure prepared))
                    scoped eligibility aliases))
    State.put prepared
    runDeclaration (reserveCandidate spec)

-- | Validate and reserve one stage of already closed checked propositions in
-- the current declaration closure.
reserveFrozenPropositionCandidateBatch
    :: NonEmpty
        ( FrozenCheckedCore ObjectId
        , FactSearchEligibility
        , [SemanticName]
        )
    -> Declaration (NonEmpty ReservedCandidate)
reserveFrozenPropositionCandidateBatch inputs = Declaration do
    unprepared <- State.get
    prepared <-
        State.lift
            (Except.liftEither
                (prepareDeclarationClosure unprepared))
    let closure =
            maybe
                (impossible "prepared proposition closure is absent")
                id
                (declarationObjectClosure prepared)
    specs <- traverse (prepareInput closure) inputs
    State.put prepared
    runDeclaration (reserveCandidateBatch specs)
  where
    prepareInput closure (frozen, eligibility, aliases) =
        State.lift
            (Except.liftEither
                (prepareFrozenCandidateSpec
                    closure frozen eligibility aliases))

reserveCandidateBatch
    :: NonEmpty CandidateSpec
    -> Declaration (NonEmpty ReservedCandidate)
reserveCandidateBatch specs = Declaration do
    state <- State.get
    case declarationValidationSelection state of
        DeclarationValidationUnselected -> pure ()
        _ ->
            State.lift
                (Except.throwError
                    DeclarationShapeChangedAfterValidationLookup)
    let builder = declarationBuilder state
        stage = CandidateStage (declarationNextStage state)
        firstFact = declarationNextFact state
        candidates =
            NonEmpty.zipWith
                (makeReserved builder state stage)
                (0 :| [1 ..])
                specs
        reservations' =
            foldl'
                (\reservations candidate ->
                    Map.insert
                        (reservedCandidateSlot candidate)
                        candidate
                        reservations)
                (declarationReservations state)
                candidates
        candidateCount = fromIntegral (NonEmpty.length specs)
    State.put
        state
            { declarationReservations = reservations'
            , declarationNextFact = firstFact + candidateCount
            , declarationNextStage =
                declarationNextStage state + 1
            }
    pure candidates
  where
    makeReserved builder state stage offset spec =
        ReservedCandidate
            (logicalBuilderIdentity builder)
            (logicalBuilderPrefix builder)
            (declarationInvocation state)
            stage
            (factSlot
                (logicalBuilderOwner builder)
                (localFactOrdinal
                    (declarationNextFact state + offset)))
            spec

-- | Construct the one defining equation owned by a checked transparent
-- object. The equation is derived from authoritative object content, not from
-- a caller-supplied proposition.
reserveDefinitionEquationCandidate
    :: ObjectId
    -> SemanticName
    -> Declaration ReservedCandidate
reserveDefinitionEquationCandidate identity alias = Declaration do
    unprepared <- State.get
    prepared <-
        State.lift
            (Except.liftEither
                (prepareDeclarationClosure unprepared))
    spec <-
        State.lift
            (Except.liftEither
                (prepareDefinitionEquationSpec
                    (fromMaybe
                        (impossible
                            "prepared definition closure is absent")
                        (declarationObjectClosure prepared))
                    identity alias))
    State.put prepared
    runDeclaration (reserveCandidate spec)

-- | Construct the pointwise presentation of one unary transparent predicate
-- definition. The candidate remains tied to the object's checked content.
reservePointwiseDefinitionEquationCandidate
    :: ObjectId
    -> SemanticName
    -> Declaration ReservedCandidate
reservePointwiseDefinitionEquationCandidate identity alias = Declaration do
    unprepared <- State.get
    prepared <-
        State.lift
            (Except.liftEither
                (prepareDeclarationClosure unprepared))
    spec <-
        State.lift
            (Except.liftEither
                (preparePointwiseDefinitionEquationSpec
                    (fromMaybe
                        (impossible "prepared predicate closure is absent")
                        (declarationObjectClosure prepared))
                    identity alias))
    State.put prepared
    runDeclaration (reserveCandidate spec)

-- | Reserve one defining equation and a nonempty generated-fact batch at the
-- same declaration stage. No candidate in the batch can cite a sibling.
reserveDefinitionEquationCandidateBatch
    :: ObjectId
    -> SemanticName
    -> NonEmpty
        ( ScopedCheckedCore ObjectId
        , FactSearchEligibility
        , [SemanticName]
        )
    -> Declaration
        ( ReservedCandidate
        , NonEmpty ReservedCandidate
        )
reserveDefinitionEquationCandidateBatch identity alias generated =
    Declaration do
        unprepared <- State.get
        prepared <-
            State.lift
                (Except.liftEither
                    (prepareDeclarationClosure unprepared))
        let closure =
                maybe
                    (impossible
                        "prepared declaration closure is absent")
                    id
                    (declarationObjectClosure prepared)
        definition <-
            State.lift
                (Except.liftEither
                    (prepareDefinitionEquationSpec closure identity alias))
        generatedSpecs <-
            traverse
                (prepareGeneratedSpec closure)
                generated
        State.put prepared
        candidates <-
            runDeclaration
                (reserveCandidateBatch
                    (definition :| toList generatedSpecs))
        case candidates of
            definitionCandidate :| firstGenerated : remainingGenerated ->
                pure
                    ( definitionCandidate
                    , firstGenerated :| remainingGenerated
                    )
            _ ->
                impossible
                    "a nonempty generated batch produced no candidate"
  where
    prepareGeneratedSpec closure (scoped, eligibility, aliases) =
        State.lift
            (Except.liftEither
                (prepareScopedCandidateSpec
                    closure scoped eligibility aliases))

-- | Resolve one complete compiled declaration against its exact validation
-- key, then run the source-level authorization action under that selection.
-- Objects and candidates must already be prepared so the lookup key cannot
-- change after a hit or miss is chosen.
authorizeCompiledDeclaration
    :: Declaration value
    -> Declaration value
authorizeCompiledDeclaration action = Declaration do
    unprepared <- State.get
    (syntax, objects, theorems, ordinals, prepared) <-
        State.lift
            (Except.liftEither
                (prepareCompiledValidation unprepared))
    let key =
            declarationValidationKey
                syntax
                (logicalBuilderPrefix
                    (declarationBuilder prepared))
                objects
                theorems
    cached <-
        case declarationValidationRun prepared of
            FreshValidation ->
                pure Nothing
            WarmValidation
                    (ValidationLookup _lookupProof lookupDeclaration) ->
                liftIO (lookupDeclaration key)
    traverse_
        (\record ->
            case Materialization.checkDeclarationValidationRecord
                    (logicalBuilderPrefix
                        (declarationBuilder prepared))
                    syntax
                    objects
                    theorems
                    record of
                Left failure ->
                    liftIO
                        (throwIO
                            (CachedValidationIntegrityError failure))
                Right () ->
                    pure ())
        cached
    let selection =
            case cached of
                Nothing ->
                    FreshDeclarationValidation
                Just record ->
                    CachedDeclarationValidation
                        syntax objects theorems record ordinals
    State.put
        prepared
            { declarationValidationSelection = selection
            }
    runDeclaration action

prepareCompiledValidation
    :: DeclarationState
    -> Either
        DeclarationError
        ( DeclarationSyntaxId
        , [ObjectId]
        , [TheoremId]
        , Map FactSlot Natural
        , DeclarationState
        )
prepareCompiledValidation declaration = do
    syntax <-
        case declarationValidationMode declaration of
            DeclarationValidationMode value ->
                Right value
            _ ->
                Left DeclarationValidationOutsideCompiledDeclaration
    case declarationValidationSelection declaration of
        DeclarationValidationUnselected -> pure ()
        _ -> Left DeclarationValidationAlreadySelected
    closure <- declarationClosure declaration
    let builder = declarationBuilder declaration
        candidates = Map.elems (declarationReservations declaration)
        objects =
            assertedObjectId
                <$> reverse
                    (declarationObjectsReversed declaration)
        theorems =
            theoremId . candidateTheoremReference builder
                <$> candidates
        ordinals =
            Map.fromList
                (zip
                    (reservedCandidateSlot <$> candidates)
                    [0 ..])
    pure
        ( syntax
        , objects
        , theorems
        , ordinals
        , declaration
            { declarationObjectClosure = Just closure
            }
        )

lookupProofValidation
    :: ReservedCandidate
    -> Declaration (ProofSyntaxId, Maybe ProofValidationRecord)
lookupProofValidation candidate = Declaration do
    state <- State.get
    syntax <-
        case declarationValidationMode state of
            EnvironmentImportMode ->
                State.lift
                    (Except.throwError
                        ProofValidationOutsideProofDeclaration)
            ProofValidationMode proofSyntax ->
                pure proofSyntax
            DeclarationValidationMode{} ->
                State.lift
                    (Except.throwError
                        ProofValidationOutsideProofDeclaration)
    let builder = declarationBuilder state
        reference = candidateTheoremReference builder candidate
        key =
            proofValidationKey
                (theoremId
                    (factAuthorityTheorem
                        (factAuthority
                            reference
                            cleanAuthoritySafety)))
                syntax
                (logicalBuilderPrefix builder)
    record <-
        case declarationValidationRun state of
            FreshValidation ->
                pure Nothing
            WarmValidation (ValidationLookup lookupProof _lookupDeclaration) ->
                State.lift
                    (liftIO
                        (lookupProof key))
    pure (syntax, record)
data CandidatePremise = CandidatePremise
    !CheckedPropositionContent

data CandidateProofState = CandidateProofState
    { candidateProofDeclaration :: !DeclarationState
    , candidateProofObjectClosure :: !CheckedObjectClosure
    , candidateProofCandidate :: !ReservedCandidate
    , candidateProofCachedValidation
        :: !(Maybe Materialization.CandidateValidation)
    , candidateProofPremisesReversed :: ![CandidatePremise]
    , candidateProofPremiseCount :: !Natural
    , candidateProofSafety :: !CandidateSafety
    , candidateProofAcceptedRequestsReversed
        :: ![PreparedRequestId]
    }

candidateProofBuilder :: CandidateProofState -> LogicalBuilder
candidateProofBuilder =
    declarationBuilder . candidateProofDeclaration

newtype CandidateProof value = CandidateProof
    { runCandidateProof
        :: StateT
            CandidateProofState
            (ExceptT DeclarationError IO)
            value
    }
    deriving newtype (Functor, Applicative, Monad)

-- | Attach source trivia to a proof-obligation failure.  The location does
-- not participate in validation or request identity.
locateProofObligation
    :: Location
    -> CandidateProof value
    -> CandidateProof value
locateProofObligation location (CandidateProof action) =
    CandidateProof
        (State.mapStateT
            (Except.withExceptT
                (ProofObligationFailedAt location))
            action)

-- | Record that the current exact proof discharged one goal with @Omitted@.
recordOmittedUse :: CandidateProof ()
recordOmittedUse = CandidateProof do
    state <- State.get
    State.put
        state
            { candidateProofSafety =
                addCandidateEscape
                    Omitted
                    (candidateProofSafety state)
            }

data VampirePremiseSelection
    = VampireImplicitPremises
    | VampireExplicitPremises
        !(NonEmpty SemanticFactOccurrenceFingerprint)
    | VampireLocalPremises
    deriving stock (Show, Eq)

data VampireObligationPreparationError local
    = VampireObligationIndirectTargetNotFalsum
    | VampireObligationClaimProjectionFailed
        !(Backend.SupportedPropositionProjectionError local)
    | VampireObligationLocalProjectionFailed
        !Backend.LocalPremiseOrdinal
        !(Backend.SupportedPropositionProjectionError local)
    | VampireObligationLocalClassificationFailed
        !Backend.LocalPremiseOrdinal
        !(Backend.BackendClassificationError ObjectId)
    | VampireObligationFactNotVisible
        !SemanticFactOccurrenceFingerprint
    | VampireObligationFactInvalid
        !SemanticFactOccurrenceFingerprint
    | VampireObligationPlanningFailed
        !(Backend.TypedProblemError local ObjectId)
    | VampireObligationEncodingFailed
        !(Tptp.TypedTptpPreparationError local ObjectId)
    deriving stock (Show, Eq)

data ScopedVampirePremise local origin = ScopedVampirePremise
    !Backend.LocalPremiseOrdinal
    !origin
    !(Vector (local, CoreType))
    !(ScopedCheckedCore ObjectId)

scopedVampirePremise
    :: Backend.LocalPremiseOrdinal
    -> origin
    -> Vector (local, CoreType)
    -> ScopedCheckedCore ObjectId
    -> ScopedVampirePremise local origin
scopedVampirePremise =
    ScopedVampirePremise

data PreparedVampireObligation local origin =
    PreparedVampireObligation
        !(Backend.TypedProblem
            SemanticFactOccurrenceFingerprint
            local
            origin
            ObjectId)
        !(Provers.PreparedTypedProverTask
            SemanticFactOccurrenceFingerprint
            local
            origin
            ObjectId)

-- | Prepare a scoped task for a trusted structural proof checker.  This
-- validates the typed problem but does not establish how its local judgments
-- derive from the enclosing theorem.  'Checking.Exact.Proof' owns that
-- composition on the production path.
prepareScopedVampireObligationDriver
    :: Ord local
    => Vector (local, CoreType)
    -> ScopedCheckedCore ObjectId
    -> [ScopedVampirePremise local origin]
    -> [FoundationAxiomTag]
    -> VampirePremiseSelection
    -> ModuleDriver failure
        (Either
            (VampireObligationPreparationError local)
            (PreparedVampireObligation local origin))
prepareScopedVampireObligationDriver
        claimSupport claim scopedLocals auxiliaryTags selection =
    prepareScopedVampireObligationForMode
        Provers.DirectTask
        claimSupport
        claim
        scopedLocals
        auxiliaryTags
        selection

-- | Prepare the one indirect task admitted by the exact proof compiler.
-- The target check keeps contradictory input from authorizing another goal.
prepareScopedContradictionObligationDriver
    :: Ord local
    => Vector (local, CoreType)
    -> ScopedCheckedCore ObjectId
    -> [ScopedVampirePremise local origin]
    -> [FoundationAxiomTag]
    -> VampirePremiseSelection
    -> ModuleDriver failure
        (Either
            (VampireObligationPreparationError local)
            (PreparedVampireObligation local origin))
prepareScopedContradictionObligationDriver
        claimSupport claim scopedLocals auxiliaryTags selection
    | scopedCoreType claim /= TyProp || scopedCoreTerm claim /= CFalsum =
        pure (Left VampireObligationIndirectTargetNotFalsum)
    | otherwise =
        prepareScopedVampireObligationForMode
            Provers.IndirectTask
            claimSupport
            claim
            scopedLocals
            auxiliaryTags
            selection

prepareScopedVampireObligationLowering
    :: Ord local
    => Vector (local, CoreType)
    -> ScopedCheckedCore ObjectId
    -> [ScopedVampirePremise local origin]
    -> [FoundationAxiomTag]
    -> VampirePremiseSelection
    -> LoweringDriver
        (Either
            (VampireObligationPreparationError local)
            (PreparedVampireObligation local origin))
prepareScopedVampireObligationLowering
        claimSupport claim scopedLocals auxiliaryTags selection =
    prepareScopedVampireObligationForModeLowering
        Provers.DirectTask
        claimSupport claim scopedLocals auxiliaryTags selection

prepareScopedContradictionObligationLowering
    :: Ord local
    => Vector (local, CoreType)
    -> ScopedCheckedCore ObjectId
    -> [ScopedVampirePremise local origin]
    -> [FoundationAxiomTag]
    -> VampirePremiseSelection
    -> LoweringDriver
        (Either
            (VampireObligationPreparationError local)
            (PreparedVampireObligation local origin))
prepareScopedContradictionObligationLowering
        claimSupport claim scopedLocals auxiliaryTags selection
    | scopedCoreType claim /= TyProp || scopedCoreTerm claim /= CFalsum =
        pure (Left VampireObligationIndirectTargetNotFalsum)
    | otherwise =
        prepareScopedVampireObligationForModeLowering
            Provers.IndirectTask
            claimSupport claim scopedLocals auxiliaryTags selection

prepareScopedVampireObligationForModeLowering
    :: Ord local
    => Provers.VampireTaskMode
    -> Vector (local, CoreType)
    -> ScopedCheckedCore ObjectId
    -> [ScopedVampirePremise local origin]
    -> [FoundationAxiomTag]
    -> VampirePremiseSelection
    -> LoweringDriver
        (Either
            (VampireObligationPreparationError local)
            (PreparedVampireObligation local origin))
prepareScopedVampireObligationForModeLowering
        taskMode claimSupport claim scopedLocals auxiliaryTags selection =
    LoweringDriver do
        LoweringState resolver (ProspectiveBuilder builder) _validation <-
            State.get
        liftIO
            (prepareScopedVampireObligationWith
                resolver builder taskMode claimSupport claim scopedLocals
                auxiliaryTags selection)

prepareScopedVampireObligationForMode
    :: Ord local
    => Provers.VampireTaskMode
    -> Vector (local, CoreType)
    -> ScopedCheckedCore ObjectId
    -> [ScopedVampirePremise local origin]
    -> [FoundationAxiomTag]
    -> VampirePremiseSelection
    -> ModuleDriver failure
        (Either
            (VampireObligationPreparationError local)
            (PreparedVampireObligation local origin))
prepareScopedVampireObligationForMode
        taskMode claimSupport claim scopedLocals auxiliaryTags selection =
    ModuleDriver do
        DriverState resolver builder _prefix _validation <- State.get
        State.lift
            (Except.liftIO
                (prepareScopedVampireObligationWith
                    resolver builder taskMode claimSupport claim scopedLocals
                    auxiliaryTags selection))

prepareScopedVampireObligationWith
    :: (Ord local)
    => VampireResolver
    -> BuilderState evidence
    -> Provers.VampireTaskMode
    -> Vector (local, CoreType)
    -> ScopedCheckedCore ObjectId
    -> [ScopedVampirePremise local origin]
    -> [FoundationAxiomTag]
    -> VampirePremiseSelection
    -> IO
        (Either
            (VampireObligationPreparationError local)
            (PreparedVampireObligation local origin))
prepareScopedVampireObligationWith
        resolver builder taskMode claimSupport claim scopedLocals
        auxiliaryTags selection =
    measureVampirePreparation resolver preparation
  where
    closure = logicalBuilderObjectClosure builder
    globalType = (`lookupCheckedObjectType` closure)
    preparation = do
        supportedClaim <-
            first VampireObligationClaimProjectionFailed
                (Backend.projectSupportedProposition
                    globalType
                    claimSupport
                    claim)
        locals <- traverse prepareLocal scopedLocals
        prepareVampireObligationWith
            taskMode
            builder
            closure
            supportedClaim
            locals
            auxiliaryTags
            selection

    prepareLocal
            (ScopedVampirePremise
                ordinal origin support proposition) = do
        supported <-
            first
                (VampireObligationLocalProjectionFailed ordinal)
                (Backend.projectSupportedProposition
                    globalType
                    support
                    proposition)
        first
            (VampireObligationLocalClassificationFailed ordinal)
            (Backend.typedLocalPremise
                globalType
                ordinal
                origin
                supported)

prepareVampireObligationWith
    :: Ord local
    => Provers.VampireTaskMode
    -> BuilderState evidence
    -> CheckedObjectClosure
    -> Backend.SupportedProposition local ObjectId
    -> [Backend.TypedLocalPremise local origin ObjectId]
    -> [FoundationAxiomTag]
    -> VampirePremiseSelection
    -> Either
        (VampireObligationPreparationError local)
        (PreparedVampireObligation local origin)
prepareVampireObligationWith
        taskMode builder closure claim locals auxiliaryTags selection = do
    let globalType = (`lookupCheckedObjectType` closure)
    selected <-
        selectVampireFacts
            globalType
            builder
            selection
    let premiseSelection =
            case selection of
                VampireImplicitPremises ->
                    Backend.ImplicitPremiseSelection
                VampireExplicitPremises{} ->
                    Backend.ExplicitGlobalPremiseSelection
                VampireLocalPremises ->
                    Backend.LocalOnlyPremiseSelection
        propositionDependencies =
            foundationAxiomDependencies
                . Backend.supportedPropositionTerm
        requiredAuxiliaryTags =
            Set.toAscList
                ( Set.fromList auxiliaryTags
                    <> propositionDependencies claim
                    <> foldMap
                        (propositionDependencies
                            . Backend.typedBackendFactProposition)
                        selected
                    <> foldMap
                        (propositionDependencies
                            . Backend.typedLocalPremiseProposition)
                        (Backend.selectTypedLocalPremises
                            premiseSelection
                            locals)
                )
        auxiliaries =
            Backend.typedFoundationAuxiliaryInput
                (logicalBuilderFoundation builder)
                <$> requiredAuxiliaryTags
    problem <-
        first VampireObligationPlanningFailed
            (Backend.planTypedProblem
                globalType
                selected
                claim
                locals
                auxiliaries
                premiseSelection)
    task <-
        first VampireObligationEncodingFailed
            (Provers.prepareTypedProverTask
                taskMode
                problem)
    pure (PreparedVampireObligation problem task)

measureVampirePreparation
    :: VampireResolver
    -> Either
        (VampireObligationPreparationError local)
        (PreparedVampireObligation local origin)
    -> IO
        (Either
            (VampireObligationPreparationError local)
            (PreparedVampireObligation local origin))
measureVampirePreparation resolver preparation = do
    started <- getMonotonicTimeNSec
    prepared <- Exception.evaluate (forcePrepared preparation)
    finished <- getMonotonicTimeNSec
    observeVampirePreparation resolver (finished - started)
    pure prepared
  where
    forcePrepared result =
        case result of
            Left err -> err `seq` result
            Right prepared@(PreparedVampireObligation _ task) ->
                let request = Provers.preparedTypedProverRequest task
                in Provers.preparedVerificationByteCount request `seq`
                    Provers.preparedVerificationRequestId request `seq`
                    prepared `seq`
                    result

selectVampireFacts
    :: (ObjectId -> Maybe CoreType)
    -> BuilderState evidence
    -> VampirePremiseSelection
    -> Either
        (VampireObligationPreparationError local)
        (Vector
            (Backend.TypedBackendFact
                SemanticFactOccurrenceFingerprint
                ObjectId))
selectVampireFacts globalType builder selection =
    Vector.fromList <$> case selection of
        VampireImplicitPremises ->
            mapMaybeM prepareImplicit
                (Map.toAscList (logicalBuilderFacts builder))
        VampireExplicitPremises fingerprints ->
            traverse prepareExplicit
                (stableUniqueBy id (toList fingerprints))
        VampireLocalPremises ->
            Right []
  where
    prepareImplicit (fingerprint, authorized@(FactEntry
            _proposition occurrence _authorization))
        | semanticFactSearchEligibility occurrence
            /= SearchEligible =
                Right Nothing
        | otherwise = do
            fact <- prepareFact fingerprint authorized
            pure case Backend.typedBackendFactCapability fact of
                Backend.FofProjectable{} -> Just fact
                Backend.RequiresTh0{} -> Nothing

    prepareExplicit fingerprint =
        case Map.lookup fingerprint (logicalBuilderFacts builder) of
            Nothing ->
                Left (VampireObligationFactNotVisible fingerprint)
            Just authorized ->
                prepareFact fingerprint authorized

    prepareFact fingerprint
            (FactEntry proposition occurrence _authorization)
        | semanticFactFingerprint occurrence /= fingerprint =
            Left (VampireObligationFactInvalid fingerprint)
        | otherwise = do
            supported <-
                first
                    (const
                        (VampireObligationFactInvalid fingerprint))
                    (Backend.supportedProposition
                        Vector.empty
                        (embedClosedCore
                            []
                            (checkedPropositionTerm proposition)))
            capability <-
                first
                    (const
                        (VampireObligationFactInvalid fingerprint))
                    (Backend.classifySupportedProposition
                        globalType
                        supported)
            pure
                (Backend.typedBackendFact
                    fingerprint
                    supported
                    capability)

    mapMaybeM action =
        fmap catMaybes . traverse action

data LocalClaim = LocalClaim
    !BuilderIdentity
    !DeclarationInvocation
    !FactSlot
    !CheckedPropositionContent

useAuthorizedFact
    :: SemanticFactOccurrenceFingerprint
    -> CandidateProof ImportIx
useAuthorizedFact fingerprint = do
    proposition <- consumeAuthorizedFact fingerprint
    registerKernelImport proposition

-- | Validate one fact capability and accumulate only its safety effect.
-- Backend use does not register a kernel import.
consumeAuthorizedFact
    :: SemanticFactOccurrenceFingerprint
    -> CandidateProof CheckedPropositionContent
consumeAuthorizedFact fingerprint = CandidateProof do
    state <- State.get
    let builder = candidateProofBuilder state
        declaration = candidateProofDeclaration state
        staged =
            findPendingByFingerprint
                fingerprint
                (declarationPending declaration)
    case staged of
        Just pending ->
            consumePendingFact pending state
        Nothing ->
            case Map.lookup
                    fingerprint
                    (logicalBuilderFacts builder) of
                Nothing ->
                    State.lift
                        (Except.throwError
                            (AuthorizedFactNotVisible fingerprint))
                Just authorized ->
                    consumeBuilderAuthorizedFact authorized state

-- | Materialize one sealed direct import and its transitive parents.  The
-- interface DAG is folded imported-before-importer and each producer
-- occurrence receives a fresh capability for this consuming builder.
importSealedModule
    :: ImportedModuleEvidence
    -> Declaration ()
importSealedModule evidence = Declaration do
    state <- State.get
    when
        (isJust (declarationObjectClosure state))
        (State.lift
            (Except.throwError ImportedModuleAfterAuthorization))
    let builder = declarationBuilder state
        interfaceId =
            semanticInterfaceAssertedId
                (evidenceInterface evidence)
    unless
        (interfaceId `elem`
            logicalBuilderDirectSemanticInputs builder)
        (State.lift
            (Except.throwError
                (ImportedModuleNotDirect interfaceId)))
    imported <-
        State.lift
            (Except.liftEither
                (foldImportedEvidence evidence builder))
    State.put
        state
            { declarationBuilder = imported
            , declarationObjectClosure = Nothing
            }

-- The walking path keeps complete aggregate maps. Measure long chains before
-- replacing this representation.
foldImportedEvidence
    :: ImportedModuleEvidence
    -> LogicalBuilder
    -> Either DeclarationError LogicalBuilder
foldImportedEvidence evidence builder
    | interfaceId
        `Set.member` logicalBuilderImportedInterfaces builder =
            Right builder
    | otherwise = do
        unless
            (semanticInterfaceDirectInputs interface
                == (semanticInterfaceAssertedId . evidenceInterface
                        <$> parents))
            (Left
                (ImportedEvidenceDirectMismatch
                    (semanticInterfaceDirectInputs interface)
                    (semanticInterfaceAssertedId . evidenceInterface
                        <$> parents)))
        withParents <- foldM
            (flip foldImportedEvidence)
            builder
            parents
        objectClosure <-
            first
                DeclarationObjectValidationFailed
                (extendImportedObjectClosure
                    (logicalBuilderObjectClosure withParents)
                    objects)
        importedFacts <- foldM
            (insertImportedFact withParents)
            (logicalBuilderFacts withParents)
            (Map.elems entries)
        importedAliases <- foldM
            (insertImportedAlias importedFacts)
            (logicalBuilderAliases withParents)
            [ ( alias
              , ImportedAliasOrigin
                    (declarationDeltaSlot delta)
                    (semanticAliasTarget alias)
              )
            | delta <- semanticInterfaceDeclarations interface
            , alias <- declarationDeltaAliases delta
            ]
        importedStructures <- foldM
            (insertSemanticStructure objectClosure)
            (logicalBuilderStructures withParents)
            [ descriptor
            | delta <- semanticInterfaceDeclarations interface
            , descriptor <- semanticEnvironmentStructures
                (declarationDeltaEnvironment delta)
            ]
        importedGlobals <- foldM
            (insertImportedGlobal objectClosure importedStructures)
            (logicalBuilderGlobals withParents)
            [ binding
            | delta <- semanticInterfaceDeclarations interface
            , binding <- semanticEnvironmentBindings
                (declarationDeltaEnvironment delta)
            ]
        pure
            withParents
                { logicalBuilderFacts = importedFacts
                , logicalBuilderAliases = importedAliases
                , logicalBuilderGlobals = importedGlobals
                , logicalBuilderStructures = importedStructures
                , logicalBuilderObjectClosure = objectClosure
                , logicalBuilderImportedInterfaces =
                    Set.insert
                        interfaceId
                        (logicalBuilderImportedInterfaces withParents)
                }
  where
    ImportedModuleEvidence interface parents entries objects = evidence
    interfaceId = semanticInterfaceAssertedId interface

    extendImportedObjectClosure closure asserted =
        extendObjectClosure
            closure
            [ object
            | object <- asserted
            , assertedObjectId object
                `Set.notMember` checkedObjectIds closure
            ]

    insertImportedFact
        current facts pair = do
            let (occurrence, proposition) = pair
                fingerprint = semanticFactFingerprint occurrence
                authority = semanticFactAuthority occurrence
            _ <-
                first ImportedFactMaterializationFailed
                    (Materialization.checkImportedOccurrence
                        (logicalBuilderTheory current)
                        fingerprint
                        occurrence
                        proposition
                        authority)
            let authorization =
                    BuilderFactAuthorization
                        (logicalBuilderIdentity current)
                        (semanticFactSlot occurrence)
                        authority
                authorized =
                    FactEntry proposition occurrence authorization
            case Map.lookup fingerprint facts of
                Nothing ->
                    pure (Map.insert fingerprint authorized facts)
                Just existing
                    | equivalentAuthorizedFact existing authorized ->
                        pure facts
                    | otherwise ->
                        Left (ImportedFactCollision fingerprint)

    insertImportedAlias facts aliases (alias, origin) = do
        let name = semanticAliasName alias
            target = semanticAliasTarget alias
        unless
            (Map.member target facts)
            (Left (ImportedAliasTargetMissing target))
        case Map.lookup name aliases of
            Nothing ->
                pure
                    (Map.insert
                        name
                        (ImportedAliasBinding target origin)
                        aliases)
            Just (ImportedAliasBinding existingTarget existingOrigin)
                | existingTarget == target ->
                    pure aliases
                | otherwise ->
                    Left
                        (ImportedAliasCollision
                            name existingOrigin origin)

    insertImportedGlobal closure structures globals binding = do
        let key = semanticGlobalBindingKey binding
            target = semanticGlobalBindingTarget binding
        _ <-
            first
                (ImportedGlobalTargetInvalid key target)
                (validateSemanticGlobalBindingTarget
                    (structureOperationBindings structures)
                    closure binding)
        case Map.lookup key globals of
            Nothing -> pure (Map.insert key target globals)
            Just existing
                | existing == target -> pure globals
                | otherwise ->
                    Left (ImportedGlobalCollision key existing target)

insertSemanticStructure
    :: CheckedObjectClosure
    -> Map SemanticStructurePhrase ResolvedStructure
    -> SemanticStructureDescriptor
    -> Either
        DeclarationError
        (Map SemanticStructurePhrase ResolvedStructure)
insertSemanticStructure closure structures descriptor = do
    validateSemanticStructureTargets closure descriptor
    let structurePhrase = semanticStructureDescriptorPhrase descriptor
    case Map.lookup structurePhrase structures of
        Just (ResolvedStructure existing _ _)
            | existing == descriptor -> Right structures
            | otherwise ->
                Left
                    (ImportedStructureCollision
                        structurePhrase existing descriptor)
        Nothing -> do
            parents <- traverse resolveParent
                (semanticStructureDescriptorParents descriptor)
            inherited <- foldM mergeParentOperations Map.empty parents
            complete <- foldM insertOwnOperation inherited
                (semanticStructureDescriptorOperations descriptor)
            let ancestors =
                    Set.unions
                        [ Set.insert
                            (semanticStructureDescriptorPhrase
                                (resolvedStructureDescriptor parent))
                            parentAncestors
                        | parent@(ResolvedStructure _ parentAncestors _) <- parents
                        ]
                resolved = ResolvedStructure descriptor ancestors complete
            Right (Map.insert structurePhrase resolved structures)
  where
    resolveParent parentPhrase =
        maybe
            (Left
                (SemanticStructureParentMissing
                    (semanticStructureDescriptorPhrase descriptor)
                    parentPhrase))
            Right
            (Map.lookup parentPhrase structures)

    mergeParentOperations operations
            (ResolvedStructure _descriptor _ancestors parentOperations) =
        foldM insertInheritedOperation operations
            (Map.toAscList parentOperations)

    insertInheritedOperation operations (symbol, operation) =
        insertResolvedOperation symbol operation operations

    insertOwnOperation operations operation =
        insertResolvedOperation
            (semanticStructureOperationSymbol operation)
            (ResolvedStructureOperation
                (semanticStructureOperationObject operation)
                (semanticStructureDescriptorPhrase descriptor))
            operations

    insertResolvedOperation symbol incoming operations =
        case Map.lookup symbol operations of
            Nothing -> Right (Map.insert symbol incoming operations)
            Just (ResolvedStructureOperation existingObject existingOrigin) ->
                case incoming of
                    ResolvedStructureOperation incomingObject incomingOrigin
                        | existingObject == incomingObject -> Right operations
                        | otherwise ->
                            Left
                                (SemanticStructureOperationConflict
                                    symbol existingOrigin incomingOrigin)

validateSemanticStructureTargets
    :: CheckedObjectClosure
    -> SemanticStructureDescriptor
    -> Either DeclarationError ()
validateSemanticStructureTargets closure descriptor = do
    traverse_ validatePredicate
        (semanticStructureDescriptorPredicate descriptor)
    traverse_ validateOperation
        (semanticStructureDescriptorOperations descriptor)
  where
    validatePredicate object =
        validateObjectType
            (SemanticStructurePredicateTargetInvalid
                (semanticStructureDescriptorPhrase descriptor))
            object
            (TyArrow TySet TyProp)

    validateOperation operation =
        validateObjectType
            (SemanticStructureOperationTargetInvalid
                (semanticStructureDescriptorPhrase descriptor)
                (semanticStructureOperationSymbol operation))
            (semanticStructureOperationObject operation)
            (TyArrow TySet TySet)

    validateObjectType failure object expected =
        case lookupCheckedObjectType object closure of
            Nothing -> Left (failure object Nothing expected)
            Just actual
                | actual == expected -> Right ()
                | otherwise -> Left (failure object (Just actual) expected)

equivalentAuthorizedFact
    :: FactEntry BuilderFactAuthorization
    -> FactEntry BuilderFactAuthorization
    -> Bool
equivalentAuthorizedFact
        (FactEntry leftProposition leftOccurrence
            (BuilderFactAuthorization leftIdentity leftSlot leftAuthority))
        (FactEntry rightProposition rightOccurrence
            (BuilderFactAuthorization rightIdentity rightSlot rightAuthority)) =
    checkedPropositionId leftProposition
        == checkedPropositionId rightProposition
        && leftOccurrence == rightOccurrence
        && leftIdentity == rightIdentity
        && leftSlot == rightSlot
        && leftAuthority == rightAuthority

-- | Driver-level form used before the first declaration of a consuming
-- module.  It changes only the private builder's imported fact environment;
-- no declaration prefix or durable envelope is emitted.
importSealedModuleDriver
    :: ImportedModuleEvidence
    -> ModuleDriver failure ()
importSealedModuleDriver evidence = ModuleDriver do
    DriverState resolver builder prefix validationRun <-
        State.get
    let declaration =
            initialDeclarationState
                resolver
                validationRun
                EnvironmentImportMode
                builder
    result <-
        liftIO
            (Except.runExceptT
                (State.runStateT
                    (runDeclaration
                        (importSealedModule evidence))
                    declaration))
    case result of
        Left failure ->
            Except.throwError (DriverDeclarationFailed failure)
        Right (_value, importedState) ->
            State.put
                (DriverState
                    resolver
                    (declarationBuilder importedState)
                    prefix
                    validationRun)

useStagedCandidate
    :: ReservedCandidate
    -> CandidateProof ImportIx
useStagedCandidate premise = CandidateProof do
    state <- State.get
    let current = candidateProofCandidate state
        declaration = candidateProofDeclaration state
    State.lift
        (Except.liftEither
            (validateReservedCandidate
                declaration
                premise))
    State.lift
        (Except.liftEither
            (validateStrictCandidateStage premise current))
    pending <-
        maybe
            (State.lift
                (Except.throwError
                    (StagedPremiseNotAuthorized
                        (reservedCandidateSlot premise))))
            pure
            (Map.lookup
                (reservedCandidateSlot premise)
                (declarationPending declaration))
    let proposedAuthority =
            validationTarget (pendingCandidateCertificate pending)
    checkedStage <-
        State.lift
            (Except.liftEither
                (prepareCheckedDeclarationStage
                    declaration
                    (candidateProofObjectClosure state)
                    [(premise, proposedAuthority)]))
    stagedProposition <-
        State.lift
            (Except.liftEither
                (useCheckedStageFact checkedStage current premise))
    proposition <- consumePendingFact pending state
    unless
        (checkedPropositionId stagedProposition
            == checkedPropositionId proposition)
        (State.lift
            (Except.throwError
                (PlanningFactContractMismatch
                    (reservedCandidateSlot premise))))
    updated <- State.get
    appendCandidatePremise proposition updated

validateStrictCandidateStage
    :: ReservedCandidate
    -> ReservedCandidate
    -> Either DeclarationError ()
validateStrictCandidateStage premise current =
    unless
        (reservedStage premise < reservedStage current)
        (Left
            (StagedPremiseNotEarlier
                (reservedCandidateSlot premise)
                (reservedCandidateStage premise)
                (reservedCandidateSlot current)
                (reservedCandidateStage current)))

prepareCheckedDeclarationStage
    :: DeclarationState
    -> CheckedObjectClosure
    -> [(ReservedCandidate, FactAuthority)]
    -> Either DeclarationError CheckedDeclarationStage
prepareCheckedDeclarationStage declaration closure candidates = do
    entries <- foldM insertCandidate Map.empty candidates
    pure (CheckedDeclarationStage ownSlot closure entries)
  where
    builder = declarationBuilder declaration
    ownSlot = declarationOwnSlot declaration

    insertCandidate entries (candidate, authority) = do
        validateReservedCandidate declaration candidate
        let slot = reservedCandidateSlot candidate
        unless
            (factAuthorityTheorem authority
                == candidateTheoremReference builder candidate)
            (Left (PlanningFactContractMismatch slot))
        when
            (Map.member slot entries)
            (Left (PlanningFactContractMismatch slot))
        let occurrence = candidateOccurrence candidate authority
            evidence = PlanningEvidence
                authority
                (Just
                    (PlanningProvenance
                        ownSlot
                        (reservedStage candidate)
                        slot))
        pure
            (Map.insert
                slot
                (FactEntry
                    (candidateCheckedProposition candidate)
                    occurrence
                    evidence)
                entries)

useCheckedStageFact
    :: CheckedDeclarationStage
    -> ReservedCandidate
    -> ReservedCandidate
    -> Either DeclarationError CheckedPropositionContent
useCheckedStageFact
        (CheckedDeclarationStage ownSlot closure entries)
        current
        premise = do
    validateStrictCandidateStage premise current
    let slot = reservedCandidateSlot premise
    FactEntry proposition occurrence
        (PlanningEvidence authority provenance) <-
            maybe
                (Left (PlanningFactContractMismatch slot))
                Right
                (Map.lookup slot entries)
    unless
        ( provenance
            == Just
                (PlanningProvenance
                    ownSlot
                    (reservedStage premise)
                    slot)
          && semanticFactSlot occurrence == slot
          && semanticFactAuthority occurrence == authority
          && checkedPropositionId proposition
                == checkedPropositionId
                    (candidateCheckedProposition premise)
          && propositionMatchesClosure closure proposition
        )
        (Left (PlanningFactContractMismatch slot))
    pure proposition

propositionMatchesClosure
    :: CheckedObjectClosure
    -> CheckedPropositionContent
    -> Bool
propositionMatchesClosure closure proposition =
    case validateAssertedPropositionContent
            closure
            (checkedPropositionId proposition)
            (frozenCoreTerm (checkedPropositionTerm proposition)) of
        Right _ -> True
        Left _ -> False

candidateOccurrence
    :: ReservedCandidate
    -> FactAuthority
    -> SemanticFactOccurrence
candidateOccurrence
        (ReservedCandidate _ _ _ _ slot
            (CandidateSpec _ eligibility _aliases))
        authority =
    semanticFactOccurrence slot authority eligibility

candidateAliases :: ReservedCandidate -> [SemanticName]
candidateAliases
        (ReservedCandidate _ _ _ _ _
            (CandidateSpec _ _ aliases)) =
    aliases

proveLocalKernelClaim
    :: CheckedPropositionContent
    -> KernelDerivation ObjectId
    -> CandidateProof LocalClaim
proveLocalKernelClaim proposition derivation = CandidateProof do
    state <- State.get
    void
        (State.lift
            (Except.liftEither
                (replayCandidateKernel proposition derivation state)))
    let candidate = candidateProofCandidate state
        declaration = candidateProofDeclaration state
    pure
        (LocalClaim
            (logicalBuilderIdentity
                (candidateProofBuilder state))
            (declarationInvocation declaration)
            (reservedCandidateSlot candidate)
            proposition)

useLocalClaim :: LocalClaim -> CandidateProof ImportIx
useLocalClaim
        (LocalClaim identity invocation slot proposition) =
    CandidateProof do
        state <- State.get
        let builder = candidateProofBuilder state
            declaration = candidateProofDeclaration state
            candidate = candidateProofCandidate state
        unless
            ( identity == logicalBuilderIdentity builder
              && invocation == declarationInvocation declaration
              && slot == reservedCandidateSlot candidate
            )
            (State.lift
                (Except.throwError LocalClaimOutsideCandidate))
        appendCandidatePremise proposition state


authorizeKernelProofCandidate
    :: ReservedCandidate
    -> CandidateProof (KernelDerivation ObjectId)
    -> Declaration ()
authorizeKernelProofCandidate candidate proof =
    authorizeOneCandidate candidate \initial -> do
        (derivation, final) <-
            State.runStateT (runCandidateProof proof) initial
        when
            (isNothing (candidateProofCachedValidation final))
            (void
                (Except.liftEither
                    (replayCandidateKernel
                        (candidateCheckedProposition candidate)
                        derivation
                        final)))
        completeCandidateWithValidation
                candidate
                (CheckedSourceProof
                    (acceptedRequestIds final))
                (candidateProofSafety final)
                final

authorizeKernelConstructionCandidate
    :: KernelConstructionDescriptor
    -> ReservedCandidate
    -> CandidateProof (KernelDerivation ObjectId)
    -> Declaration ()
authorizeKernelConstructionCandidate descriptor candidate proof =
    authorizeOneCandidate candidate \initial -> do
        (derivation, final) <-
            State.runStateT (runCandidateProof proof) initial
        when
            (isNothing (candidateProofCachedValidation final)) do
                replayed <-
                    Except.liftEither
                        (replayCandidateKernel
                            (candidateCheckedProposition candidate)
                            derivation
                            final)
                Except.liftEither
                    (validateKernelConstruction
                        descriptor
                        (candidateCheckedProposition candidate)
                        replayed
                        final)
        completeCandidateWithValidation
                candidate
                (CheckedKernelConstruction descriptor)
                (candidateProofSafety final)
                final

authorizeDefinitionEquationCandidate
    :: ObjectId
    -> ReservedCandidate
    -> Declaration ()
authorizeDefinitionEquationCandidate identity candidate =
    authorizeOneCandidate candidate \initial -> do
        when
            (isNothing (candidateProofCachedValidation initial))
            (unless
                (matchesDefinitionEquation
                    identity
                    (candidateCheckedProposition candidate)
                    initial)
                (Except.throwError
                    DefinitionEquationCandidateMismatch))
        completeCandidateWithValidation
            candidate
            (CheckedKernelConstruction
                (CheckedDefinitionEquation identity))
            (candidateProofSafety initial)
            initial

authorizeSourceAxiomCandidate
    :: ReservedCandidate
    -> Declaration ()
authorizeSourceAxiomCandidate candidate =
    authorizeOneCandidate candidate \initial ->
        let safety =
                addCandidateEscape
                    SourceAxiom
                    initialCandidateSafety
        in completeCandidateWithValidation
                candidate
                SourceAxiomAuthorization
                safety
                initial

-- | Complete one exact deterministic datatype as a single trusted family.
-- The descriptor, objects, and complete candidate batch must agree exactly.
-- Law semantics are trusted to the sole production compiler in
-- "Checking.Exact.Datatype"; this boundary validates its complete inventory,
-- not the meaning of each generated proposition.
authorizeDatatypeCompilationCandidates
    :: DatatypeCompilationDescriptor
    -> ObjectId
    -> NonEmpty ObjectId
    -> NonEmpty ReservedCandidate
    -> Declaration ()
authorizeDatatypeCompilationCandidates
        suppliedDescriptor carrier constructors candidates =
    Declaration do
        state <- State.get
        let builder = declarationBuilder state
            objectInventory = carrier : NonEmpty.toList constructors
            declaredObjects =
                assertedObjectId
                    <$> reverse (declarationObjectsReversed state)
            reservedCandidates =
                Map.elems (declarationReservations state)
            theoremInventory =
                candidateTheoremReference builder
                    <$> NonEmpty.toList candidates
            expectedDescriptor =
                datatypeCompilationDescriptor
                    carrier
                    constructors
                    theoremInventory
            stages =
                nubOrd
                    (reservedCandidateStage
                        <$> NonEmpty.toList candidates)
        unless
            ( suppliedDescriptor == expectedDescriptor
              && declaredObjects == objectInventory
              && reservedCandidates == NonEmpty.toList candidates
              && length stages == 1
            )
            (State.lift
                (Except.throwError
                    DatatypeCompilationDescriptorMismatch))
        runDeclaration
            (traverse_
                (authorizeDatatypeCandidate suppliedDescriptor)
                candidates)

authorizeDatatypeCandidate
    :: DatatypeCompilationDescriptor
    -> ReservedCandidate
    -> Declaration ()
authorizeDatatypeCandidate descriptor candidate =
    authorizeOneCandidate candidate \initial ->
        completeCandidateWithValidation
            candidate
            (TrustedCompilation
                (DatatypeCompilation descriptor))
            initialCandidateSafety
            initial

authorizeOmittedCandidate
    :: ReservedCandidate
    -> CandidateProof ()
    -> Declaration ()
authorizeOmittedCandidate candidate proof =
    authorizeOneCandidate candidate \initial -> do
        cached <-
            selectProofCandidateValidation candidate initial
        let preparedInitial =
                initial
                    { candidateProofCachedValidation = cached
                    }
        ((), final) <-
            State.runStateT (runCandidateProof proof) preparedInitial
        let safety = candidateProofSafety final
        unless
            (Omitted
                `elem` escapeKindsToList
                    (authoritySafetyEscapeKinds
                        (candidateSafetyAuthority safety)))
            (Except.throwError OmittedProofDidNotRecordUse)
        completeCandidateWithValidation
                candidate
                OmittedAuthorization
                safety
                final

-- | Retain the closed candidate-target path while scoped proof composition is
-- introduced. It uses the same environment validation as local obligations.
acceptVampireObligation
    :: Provers.PreparedTypedProverTask
        SemanticFactOccurrenceFingerprint
        Void
        origin
        ObjectId
    -> CandidateProof ()
acceptVampireObligation prepared =
    acceptValidatedVampireTask
        (validateCandidateVampireProblem prepared)
        prepared

-- | Validate one internally prepared scoped obligation, then retain its exact
-- accepted request.  The trusted caller remains responsible for structural
-- local-proof composition.
acceptPreparedVampireObligation
    :: (Eq local, Eq origin)
    => PreparedVampireObligation local origin
    -> CandidateProof ()
acceptPreparedVampireObligation
        (PreparedVampireObligation expected prepared) =
    acceptValidatedVampireTask
        (validatePreparedVampireProblem expected prepared)
        prepared

-- | Prepare and execute the current closed candidate using exactly the
-- staged premises already consumed by its trusted declaration compiler.
acceptCurrentCandidateVampire :: CandidateProof ()
acceptCurrentCandidateVampire =
    prepareCurrentCandidateVampire
        >>= acceptPreparedVampireObligation

-- | Prepare the current closed candidate without executing its request.  The
-- declaration-owned batch authorizer uses this seam only after all strictly
-- earlier staged premises have been consumed.
prepareCurrentCandidateVampire
    :: CandidateProof (PreparedVampireObligation Void ())
prepareCurrentCandidateVampire = CandidateProof do
    initial <- State.get
    let builder = candidateProofBuilder initial
        closure = candidateProofObjectClosure initial
        target = candidateCheckedProposition
            (candidateProofCandidate initial)
        premises =
            [ proposition
            | CandidatePremise proposition <-
                reverse (candidateProofPremisesReversed initial)
            ]
        resolver =
            declarationVampireResolver
                (candidateProofDeclaration initial)
        preparation =
            prepareClosedCandidateVampire
                builder closure target premises
    preparedResult <-
        State.lift
            (liftIO
                (measureVampirePreparation resolver preparation))
    prepared <-
        State.lift
            (Except.liftEither
                (first
                    CurrentCandidateVampirePreparationFailed
                    preparedResult))
    pure prepared

prepareClosedCandidateVampire
    :: BuilderState evidence
    -> CheckedObjectClosure
    -> CheckedPropositionContent
    -> [CheckedPropositionContent]
    -> Either
        (VampireObligationPreparationError Void)
        (PreparedVampireObligation Void ())
prepareClosedCandidateVampire builder closure target premises = do
    supportedTarget <-
        first
            VampireObligationClaimProjectionFailed
            (Backend.projectSupportedProposition
                globalType
                (Vector.empty :: Vector (Void, CoreType))
                (closed target))
    locals <-
        traverse
            prepareLocal
            (zip [0 :: Natural ..] premises)
    prepareVampireObligationWith
        Provers.DirectTask
        builder
        closure
        supportedTarget
        locals
        []
        VampireLocalPremises
  where
    globalType = (`lookupCheckedObjectType` closure)
    closed proposition =
        embedClosedCore []
            (checkedPropositionTerm proposition)

    prepareLocal (index, proposition) = do
        let ordinal = Backend.localPremiseOrdinal index
        supported <-
            first
                (VampireObligationLocalProjectionFailed ordinal)
                (Backend.projectSupportedProposition
                    globalType
                    (Vector.empty :: Vector (Void, CoreType))
                    (closed proposition))
        first
            (VampireObligationLocalClassificationFailed ordinal)
            (Backend.typedLocalPremise
                globalType ordinal () supported)

acceptValidatedVampireTask
    :: (CandidateProofState
        -> ExceptT DeclarationError IO CandidateProofState)
    -> Provers.PreparedTypedProverTask
        SemanticFactOccurrenceFingerprint
        local
        origin
        ObjectId
    -> CandidateProof ()
acceptValidatedVampireTask validate prepared = CandidateProof do
    initial <- State.get
    validated <- State.lift (validate initial)
    result <-
        case candidateProofCachedValidation initial of
            Nothing -> do
                let resolver =
                        declarationVampireResolver
                            (candidateProofDeclaration initial)
                Just <$> State.lift (resolveOneVampire resolver prepared)
            Just _validation ->
                pure Nothing
    final <-
        State.lift
            (acceptVampireBatchMemberResult
                prepared result validated)
    State.put final

-- | Complete one checked source candidate after all of its obligations have
-- been accepted in source order.  The enclosing proof declaration owns the
-- exact syntax key and selects live or cached execution before this action.
authorizeVampireCandidate
    :: ReservedCandidate
    -> CandidateProof ()
    -> Declaration ()
authorizeVampireCandidate candidate proof =
    authorizeOneCandidate candidate \initial -> do
        cached <-
            selectProofCandidateValidation candidate initial
        let preparedInitial =
                initial
                    { candidateProofCachedValidation = cached
                    }
        ((), final) <-
            State.runStateT (runCandidateProof proof) preparedInitial
        case acceptedRequestIds final of
            [] ->
                Except.throwError
                    VampireProofHasNoAcceptedObligations
            requests ->
                completeCandidateWithValidation
                    candidate
                    (CheckedSourceProof requests)
                    (candidateProofSafety final)
                    final

data PreparedVampireCandidateBatchMember =
    PreparedVampireCandidateBatchMember
        !Location
        !ReservedCandidate
        !(Provers.PreparedTypedProverTask
            SemanticFactOccurrenceFingerprint
            Void
            ()
            ObjectId)
        !CandidateProofState

data ResolvedVampireCandidateBatchMember =
    ResolvedVampireCandidateBatchMember
        !PreparedVampireCandidateBatchMember
        !(Maybe
            (Either
                Provers.ProverProcessError
                Provers.ProverAnswer))

-- | Authorize one complete, source-ordered candidate stage whose members are
-- mutually independent and each require exactly one closed Vampire request.
-- Every member is prepared and validated against the same declaration
-- baseline.  Results are applied only after the complete live batch returns,
-- so no same-stage sibling can become authority for another member.
authorizeVampireCandidateBatch
    :: NonEmpty
        ( Location
        , ReservedCandidate
        , CandidateProof (PreparedVampireObligation Void ())
        )
    -> Declaration ()
authorizeVampireCandidateBatch inputs = Declaration do
    unprepared <- State.get
    baseline <-
        State.lift
            (Except.liftEither
                (prepareDeclarationClosure unprepared))
    let supplied =
            [ candidate
            | (_location, candidate, _prepare) <- NonEmpty.toList inputs
            ]
        frontier = declarationAuthorizationFrontier baseline
        expected =
            List.filter
                ((== CandidateStage frontier) . reservedStage)
                (Map.elems (declarationReservations baseline))
    traverse_
        (State.lift
            . Except.liftEither
            . validateReservedCandidate baseline)
        supplied
    traverse_
        (\candidate ->
            when
                (Map.member
                    (reservedCandidateSlot candidate)
                    (declarationPending baseline))
                (State.lift
                    (Except.throwError
                        (CandidateAlreadyAuthorized
                            (reservedCandidateSlot candidate)))))
        supplied
    unless (supplied == expected)
        (State.lift
            (Except.throwError
                (VampireCandidateBatchMismatch
                    (reservedCandidateSlot <$> expected)
                    (reservedCandidateSlot <$> supplied))))
    prepared <-
        State.lift
            (traverse
                (prepareVampireCandidateBatchMember baseline)
                inputs)
    State.lift
        (validateCachedVampireCandidateBatch
            (NonEmpty.toList prepared))
    let live =
            [ task
            | PreparedVampireCandidateBatchMember
                    _location _candidate task final <-
                        NonEmpty.toList prepared
            , isNothing (candidateProofCachedValidation final)
            ]
    liveResults <-
        case NonEmpty.nonEmpty live of
            Nothing -> pure []
            Just nonempty -> do
                let resolver =
                        declarationVampireResolver baseline
                results <-
                    liftIO
                        (resolveSynchronousVampireBatch resolver nonempty)
                State.lift
                    (Except.liftEither
                        (validateVampireResolverResultCount
                            (length live)
                            results))
    pending <-
        State.lift
            (completeVampireCandidateBatch
                (NonEmpty.toList prepared)
                liveResults)
    let withPending =
            baseline
                { declarationPending =
                    foldl'
                        (\entries item@(PendingCandidate candidate _ _) ->
                            Map.insert
                                (reservedCandidateSlot
                                    candidate)
                                item
                                entries)
                        (declarationPending baseline)
                        pending
                }
    State.put (advanceAuthorizationFrontier withPending)

prepareVampireCandidateBatchMember
    :: DeclarationState
    -> ( Location
       , ReservedCandidate
       , CandidateProof (PreparedVampireObligation Void ())
       )
    -> ExceptT DeclarationError IO PreparedVampireCandidateBatchMember
prepareVampireCandidateBatchMember
        baseline (location, candidate, prepare) = do
    initial <-
        Except.liftEither
            (initialCandidateProofState baseline candidate)
    cached <- selectProofCandidateValidation candidate initial
    let selected =
            initial{candidateProofCachedValidation = cached}
    (obligation, preparedState) <-
        State.runStateT
            (runCandidateProof
                (locateProofObligation location prepare))
            selected
    unless (null (acceptedRequestIds preparedState))
        (Except.throwError
            (VampireCandidateBatchProofShapeMismatch
                (reservedCandidateSlot candidate)))
    let PreparedVampireObligation expected task = obligation
    validated <-
        Except.withExceptT
            (ProofObligationFailedAt location)
            (validatePreparedVampireProblem
                expected task preparedState)
    pure
        (PreparedVampireCandidateBatchMember
            location candidate task validated)

completeVampireCandidateBatch
    :: [PreparedVampireCandidateBatchMember]
    -> [Either Provers.ProverProcessError Provers.ProverAnswer]
    -> ExceptT DeclarationError IO [PendingCandidate]
completeVampireCandidateBatch members liveResults = do
    resolved <-
        Except.liftEither
            (associateVampireCandidateBatchResults
                members liveResults)
    -- Integrity dominates ranked proof failure: validate every accepted run
    -- before inspecting any ordinary process or prover rejection.
    traverse_ validateAcceptedVampireBatchMember resolved
    traverse_ rejectOrdinaryVampireBatchMember resolved
    traverse completeVampireCandidateBatchMember resolved

validateCachedVampireCandidateBatch
    :: [PreparedVampireCandidateBatchMember]
    -> ExceptT DeclarationError IO ()
validateCachedVampireCandidateBatch =
    traverse_ \member ->
        when
            (preparedVampireCandidateBatchMemberIsCached member)
            (void
                (completeVampireCandidateBatchMember
                    (ResolvedVampireCandidateBatchMember member Nothing)))

associateVampireCandidateBatchResults
    :: [PreparedVampireCandidateBatchMember]
    -> [Either Provers.ProverProcessError Provers.ProverAnswer]
    -> Either
        DeclarationError
        [ResolvedVampireCandidateBatchMember]
associateVampireCandidateBatchResults members =
    go members
  where
    go [] [] = Right []
    go [] results =
        Left
            (VampireResolverBatchSizeMismatch
                0
                (length results))
    go (member : remaining) results
        | preparedVampireCandidateBatchMemberIsCached member =
                (ResolvedVampireCandidateBatchMember member Nothing :)
                    <$> go remaining results
        | otherwise =
            case results of
                [] ->
                    Left (VampireResolverBatchSizeMismatch 1 0)
                current : later ->
                    (ResolvedVampireCandidateBatchMember
                        member (Just current) :)
                        <$> go remaining later

preparedVampireCandidateBatchMemberIsCached
    :: PreparedVampireCandidateBatchMember
    -> Bool
preparedVampireCandidateBatchMemberIsCached
        (PreparedVampireCandidateBatchMember
            _location _candidate _task state) =
    isJust (candidateProofCachedValidation state)

validateAcceptedVampireBatchMember
    :: ResolvedVampireCandidateBatchMember
    -> ExceptT DeclarationError IO ()
validateAcceptedVampireBatchMember
        (ResolvedVampireCandidateBatchMember
            (PreparedVampireCandidateBatchMember
                location _candidate task _validated)
            result) =
    Except.withExceptT
        (ProofObligationFailedAt location)
        (validateAcceptedVampireResult task result)

rejectOrdinaryVampireBatchMember
    :: ResolvedVampireCandidateBatchMember
    -> ExceptT DeclarationError IO ()
rejectOrdinaryVampireBatchMember
        (ResolvedVampireCandidateBatchMember
            (PreparedVampireCandidateBatchMember
                location _candidate _task _validated)
            result) =
    traverse_
        (Except.throwError . ProofObligationFailedAt location)
        (result >>= vampireResultFailure)

completeVampireCandidateBatchMember
    :: ResolvedVampireCandidateBatchMember
    -> ExceptT DeclarationError IO PendingCandidate
completeVampireCandidateBatchMember
        (ResolvedVampireCandidateBatchMember
            (PreparedVampireCandidateBatchMember
                location candidate task validated)
            result) = do
    final <-
        Except.withExceptT
            (ProofObligationFailedAt location)
            (applyAcceptedVampireResult task result validated)
    completeCandidateWithValidation
        candidate
        (CheckedSourceProof (acceptedRequestIds final))
        (candidateProofSafety final)
        final

acceptVampireBatchMemberResult
    :: Provers.PreparedTypedProverTask
        SemanticFactOccurrenceFingerprint
        local
        origin
        ObjectId
    -> Maybe (Either Provers.ProverProcessError Provers.ProverAnswer)
    -> CandidateProofState
    -> ExceptT DeclarationError IO CandidateProofState
acceptVampireBatchMemberResult prepared result validated = do
    validateAcceptedVampireResult prepared result
    traverse_ Except.throwError (result >>= vampireResultFailure)
    applyAcceptedVampireResult prepared result validated

validateAcceptedVampireResult
    :: Provers.PreparedTypedProverTask
        SemanticFactOccurrenceFingerprint
        local
        origin
        ObjectId
    -> Maybe (Either Provers.ProverProcessError Provers.ProverAnswer)
    -> ExceptT DeclarationError IO ()
validateAcceptedVampireResult prepared result = do
    let request = Provers.preparedTypedProverRequest prepared
    traverse_
        (\resolved ->
            traverse_
                (\accepted ->
                    unless
                        (Provers.acceptedVampireRequestId accepted
                            == Provers.preparedVerificationRequestId request)
                        (Except.throwError VampireRequestMismatch))
                (either (const Nothing) Provers.provedVampireRun resolved))
        result

vampireResultFailure
    :: Either Provers.ProverProcessError Provers.ProverAnswer
    -> Maybe DeclarationError
vampireResultFailure = \case
    Left failure ->
        Just (VampireProcessFailed failure)
    Right answer ->
        case Provers.provedVampireRun answer of
            Nothing ->
                Just (VampireObligationRejected answer)
            Just _accepted ->
                Nothing

applyAcceptedVampireResult
    :: Provers.PreparedTypedProverTask
        SemanticFactOccurrenceFingerprint
        local
        origin
        ObjectId
    -> Maybe (Either Provers.ProverProcessError Provers.ProverAnswer)
    -> CandidateProofState
    -> ExceptT DeclarationError IO CandidateProofState
applyAcceptedVampireResult prepared result validated = do
    traverse_
        (\resolved ->
            case vampireResultFailure resolved of
                Just failure ->
                    Except.throwError failure
                Nothing ->
                    pure ())
        result
    let request = Provers.preparedTypedProverRequest prepared
        requestId = Provers.preparedVerificationRequestId request
    pure
        validated
            { candidateProofAcceptedRequestsReversed =
                requestId
                    : candidateProofAcceptedRequestsReversed validated
            }

selectProofCandidateValidation
    :: ReservedCandidate
    -> CandidateProofState
    -> ExceptT
        DeclarationError
        IO
        (Maybe Materialization.CandidateValidation)
selectProofCandidateValidation candidate initial =
    case declarationValidationMode
            (candidateProofDeclaration initial) of
        EnvironmentImportMode ->
            Except.throwError
                ProofValidationOutsideProofDeclaration
        ProofValidationMode{} -> do
            (syntax, cached) <-
                runDeclarationLookup
                    (lookupProofValidation candidate)
                    initial
            pure
                ((\record ->
                    Materialization.candidateProofValidation
                        record syntax)
                    <$> cached)
        DeclarationValidationMode{} ->
            pure (candidateProofCachedValidation initial)

completeCandidateWithValidation
    :: ReservedCandidate
    -> DirectAuthorization
    -> CandidateSafety
    -> CandidateProofState
    -> ExceptT DeclarationError IO PendingCandidate
completeCandidateWithValidation candidate direct safety final = do
    pending <-
        Except.liftEither
            (freshCompletion
                candidate
                direct
                safety
                final)
    traverse_
        (\validation ->
            case Materialization.checkCandidateValidation
                    (logicalBuilderTheory
                        (candidateProofBuilder final))
                    (logicalBuilderPrefix
                        (candidateProofBuilder final))
                    (candidateCheckedProposition candidate)
                    (validationTarget
                        (pendingCandidateCertificate pending))
                    direct
                    validation of
                Left failure ->
                    liftIO
                        (throwIO
                            (CachedValidationIntegrityError failure))
                Right () ->
                    pure ())
        (candidateProofCachedValidation final)
    pure pending

runDeclarationLookup
    :: Declaration value
    -> CandidateProofState
    -> ExceptT DeclarationError IO value
runDeclarationLookup action initial =
    fst
        <$> State.runStateT
            (runDeclaration action)
            (candidateProofDeclaration initial)

pendingCandidateCertificate :: PendingCandidate -> ValidationCertificate
pendingCandidateCertificate
        (PendingCandidate _ certificate _) =
    certificate

acceptedRequestIds :: CandidateProofState -> [PreparedRequestId]
acceptedRequestIds =
    reverse . candidateProofAcceptedRequestsReversed

freshCompletion
    :: ReservedCandidate
    -> DirectAuthorization
    -> CandidateSafety
    -> CandidateProofState
    -> Either DeclarationError PendingCandidate
freshCompletion candidate direct safety proofState = do
    let builder = candidateProofBuilder proofState
        declaration = candidateProofDeclaration proofState
        reference = candidateTheoremReference builder candidate
        authority = candidateFactAuthority reference safety
    void
        (first DeclarationPropositionValidationFailed
            (validateAssertedPropositionContent
                (candidateProofObjectClosure proofState)
                (checkedPropositionId
                    (candidateCheckedProposition candidate))
                (frozenCoreTerm
                    (checkedPropositionTerm
                        (candidateCheckedProposition candidate)))))
    certificate <-
        first ValidationCertificateFailed
            (validationCertificate authority direct)
    let authorization =
            PendingFactAuthorization
                (logicalBuilderIdentity builder)
                (logicalBuilderPrefix builder)
                (declarationInvocation declaration)
                (reservedCandidateSlot candidate)
                authority
                (reservedStage candidate)
    pure
        (PendingCandidate
            candidate
            certificate
            authorization)

authorizeOneCandidate
    :: ReservedCandidate
    -> (CandidateProofState
        -> ExceptT DeclarationError IO PendingCandidate)
    -> Declaration ()
authorizeOneCandidate candidate complete = Declaration do
    unprepared <- State.get
    state <-
        State.lift
            (Except.liftEither
                (prepareDeclarationClosure unprepared))
    State.lift
        (Except.liftEither
            (validateReservedCandidate state candidate))
    when
        (Map.member
            (reservedCandidateSlot candidate)
            (declarationPending state))
        (State.lift
            (Except.throwError
                (CandidateAlreadyAuthorized
                    (reservedCandidateSlot candidate))))
    unless
        (reservedStage candidate
            == CandidateStage
                (declarationAuthorizationFrontier state))
        (State.lift
            (Except.throwError
                (CandidateOutsideAuthorizationFrontier
                    (reservedCandidateSlot candidate)
                    (reservedCandidateStage candidate)
                    (declarationAuthorizationFrontier state))))
    initial <- State.lift
        (Except.liftEither
            (initialCandidateProofState state candidate))
    pending <- State.lift (complete initial)
    let state' =
            state
                { declarationPending =
                    Map.insert
                        (reservedCandidateSlot candidate)
                        pending
                        (declarationPending state)
                }
    State.put (advanceAuthorizationFrontier state')

advanceAuthorizationFrontier
    :: DeclarationState
    -> DeclarationState
advanceAuthorizationFrontier state
    | all stageCompleted currentCandidates =
        state
            { declarationAuthorizationFrontier =
                frontier + 1
            }
    | otherwise =
        state
  where
    frontier = declarationAuthorizationFrontier state
    currentCandidates =
        List.filter
            ((== CandidateStage frontier) . reservedStage)
            (Map.elems (declarationReservations state))
    stageCompleted candidate =
        Map.member
            (reservedCandidateSlot candidate)
            (declarationPending state)

initialCandidateProofState
    :: DeclarationState
    -> ReservedCandidate
    -> Either DeclarationError CandidateProofState
initialCandidateProofState declaration candidate = do
    closure <- declarationClosure declaration
    cached <-
        cachedDeclarationCandidateValidation declaration candidate
    pure CandidateProofState
        { candidateProofDeclaration = declaration
        , candidateProofObjectClosure = closure
        , candidateProofCandidate = candidate
        , candidateProofCachedValidation = cached
        , candidateProofPremisesReversed = []
        , candidateProofPremiseCount = 0
        , candidateProofSafety = initialCandidateSafety
        , candidateProofAcceptedRequestsReversed = []
        }

cachedDeclarationCandidateValidation
    :: DeclarationState
    -> ReservedCandidate
    -> Either
        DeclarationError
        (Maybe Materialization.CandidateValidation)
cachedDeclarationCandidateValidation declaration candidate =
    case declarationValidationSelection declaration of
        DeclarationValidationUnselected ->
            Right Nothing
        FreshDeclarationValidation ->
            Right Nothing
        CachedDeclarationValidation
                syntax objects theorems record ordinals ->
            maybe
                (Left
                    (CachedDeclarationCandidateMissing
                        (reservedCandidateSlot candidate)))
                (Right
                    . Just
                    . Materialization.candidateDeclarationValidation
                        record syntax objects theorems)
                (Map.lookup
                    (reservedCandidateSlot candidate)
                    ordinals)

reservedStage :: ReservedCandidate -> CandidateStage
reservedStage
        (ReservedCandidate _ _ _ stage _ _) =
    stage

validateReservedCandidate
    :: DeclarationState
    -> ReservedCandidate
    -> Either DeclarationError ()
validateReservedCandidate declaration candidate = do
    let builder = declarationBuilder declaration
        ReservedCandidate
            identity prefix invocation _stage slot _spec = candidate
    unless
        ( identity == logicalBuilderIdentity builder
          && prefix == logicalBuilderPrefix builder
          && invocation == declarationInvocation declaration
          && Map.lookup slot
                (declarationReservations declaration)
                == Just candidate
        )
        (Left (CandidateOutsideDeclaration slot))

instance Eq ReservedCandidate where
    left == right =
        reservedCandidateKey left == reservedCandidateKey right

reservedCandidateKey
    :: ReservedCandidate
    -> (BuilderIdentity, PrefixContextId, DeclarationInvocation, CandidateStage, FactSlot)
reservedCandidateKey
        (ReservedCandidate identity prefix invocation stage slot _spec) =
    (identity, prefix, invocation, stage, slot)


consumeBuilderAuthorizedFact
    :: FactEntry BuilderFactAuthorization
    -> CandidateProofState
    -> StateT
        CandidateProofState
        (ExceptT DeclarationError IO)
        CheckedPropositionContent
consumeBuilderAuthorizedFact
        (FactEntry proposition occurrence authorization)
        state = do
    let builder = candidateProofBuilder state
        BuilderFactAuthorization
            identity slot authority = authorization
    unless
        ( identity == logicalBuilderIdentity builder
          && slot == semanticFactSlot occurrence
          && authority == semanticFactAuthority occurrence
        )
        (State.lift
            (Except.throwError BuilderFactAuthorizationMismatch))
    accumulateAuthorizedSafety
        proposition
        authority
        state
    pure proposition

consumePendingFact
    :: PendingCandidate
    -> CandidateProofState
    -> StateT
        CandidateProofState
        (ExceptT DeclarationError IO)
        CheckedPropositionContent
consumePendingFact
        (PendingCandidate premise certificate authorization)
        state = do
    let builder = candidateProofBuilder state
        declaration = candidateProofDeclaration state
        PendingFactAuthorization
            identity prefix invocation slot authority
            premiseStageValue = authorization
        current = candidateProofCandidate state
    unless
        ( identity == logicalBuilderIdentity builder
          && prefix == logicalBuilderPrefix builder
          && invocation == declarationInvocation declaration
          && slot == reservedCandidateSlot premise
          && authority == validationTarget certificate
          && premiseStageValue == reservedStage premise
        )
        (State.lift
            (Except.throwError PendingFactAuthorizationMismatch))
    unless
        (reservedStage premise < reservedStage current)
        (State.lift
            (Except.throwError
                (StagedPremiseNotEarlier
                    (reservedCandidateSlot premise)
                    (reservedCandidateStage premise)
                    (reservedCandidateSlot current)
                    (reservedCandidateStage current))))
    let proposition = candidateCheckedProposition premise
    accumulateAuthorizedSafety
        proposition
        authority
        state
    pure proposition

accumulateAuthorizedSafety
    :: CheckedPropositionContent
    -> FactAuthority
    -> CandidateProofState
    -> StateT
        CandidateProofState
        (ExceptT DeclarationError IO)
        ()
accumulateAuthorizedSafety proposition authority state = do
    let expected =
            theoremRef
                (logicalBuilderTheory
                    (candidateProofBuilder state))
                (checkedPropositionId proposition)
    safety <-
        State.lift
            (Except.liftEither
                (first FactSafetyFailed
                    (accumulateFactSafety
                        expected
                        authority
                        (candidateProofSafety state))))
    State.put state{candidateProofSafety = safety}

registerKernelImport
    :: CheckedPropositionContent
    -> CandidateProof ImportIx
registerKernelImport proposition = CandidateProof do
    state <- State.get
    appendCandidatePremise proposition state

appendCandidatePremise
    :: CheckedPropositionContent
    -> CandidateProofState
    -> StateT
        CandidateProofState
        (ExceptT DeclarationError IO)
        ImportIx
appendCandidatePremise proposition state = do
    let index = candidateProofPremiseCount state
    State.put
        state
            { candidateProofPremisesReversed =
                CandidatePremise proposition
                    : candidateProofPremisesReversed state
            , candidateProofPremiseCount = index + 1
            }
    pure (importIx index)

findPendingByFingerprint
    :: SemanticFactOccurrenceFingerprint
    -> Map FactSlot PendingCandidate
    -> Maybe PendingCandidate
findPendingByFingerprint fingerprint =
    find
        (\(PendingCandidate candidate certificate _authorization) ->
            semanticFactOccurrenceFingerprint
                (reservedCandidateSlot candidate)
                (validationTarget certificate)
                == fingerprint)
        . Map.elems

candidateImportJudgments
    :: CandidateProofState
    -> Either DeclarationError (Vector (DerivationImportJudgment ObjectId))
candidateImportJudgments state =
    Vector.fromList
        <$> traverse
            (\(CandidatePremise proposition) ->
                first DerivationImportFailed
                    (derivationImportJudgment
                        (checkedPropositionTerm proposition)))
            (reverse
                (candidateProofPremisesReversed state))

replayCandidateKernel
    :: CheckedPropositionContent
    -> KernelDerivation ObjectId
    -> CandidateProofState
    -> Either
        DeclarationError
        (ReplayedKernelDerivation ObjectId)
replayCandidateKernel proposition derivation state = do
    imports <- candidateImportJudgments state
    let builder = candidateProofBuilder state
        closure = candidateProofObjectClosure state
    first KernelCompletionFailed
        (replayKernelDerivation
            (logicalBuilderFoundation builder)
            defaultKernelReplayLimits
            (`lookupCheckedObjectType` closure)
            imports
            (checkedPropositionTerm proposition)
            derivation)

validateKernelConstruction
    :: KernelConstructionDescriptor
    -> CheckedPropositionContent
    -> ReplayedKernelDerivation ObjectId
    -> CandidateProofState
    -> Either DeclarationError ()
validateKernelConstruction descriptor proposition replayed proofState =
    unless matches
        (Left KernelConstructionDescriptorMismatch)
  where
    builder = candidateProofBuilder proofState
    noImports = Set.null (replayedKernelImportUses replayed)
    noFoundation = Set.null (replayedKernelFoundationUses replayed)
    noRules = Set.null (replayedKernelRuleUses replayed)

    matches =
        case descriptor of
            FoundationLeaf tag ->
                noImports
                    && replayedKernelFoundationUses replayed
                        == Set.singleton tag
                    && noRules
                    && checkedPropositionTerm proposition
                        == mapFrozenGlobals
                            absurd
                            (foundationAxiomFrozen
                                (logicalBuilderFoundation builder)
                                tag)
            GuardedFoundationRules rules ->
                replayedKernelRuleUses replayed
                    == guardedRuleTags rules
            CheckedDefinitionEquation identity ->
                noImports
                    && noFoundation
                    && noRules
                    && matchesDefinitionEquation identity proposition proofState

matchesDefinitionEquation
    :: ObjectId
    -> CheckedPropositionContent
    -> CandidateProofState
    -> Bool
matchesDefinitionEquation identity proposition proofState =
    case lookupCheckedObjectContent
            identity
            (candidateProofObjectClosure proofState) of
        Just
                (TransparentObjectContent
                    contentTheory coreType body) ->
            contentTheory
                == logicalBuilderTheory
                    (candidateProofBuilder proofState)
                && frozenCoreTerm (checkedPropositionTerm proposition)
                    `elem` definitionEquationTargets identity coreType body
        _ ->
            False

definitionEquationTargets
    :: ObjectId
    -> CoreType
    -> CanonicalTerm ObjectId
    -> [CanonicalTerm ObjectId]
definitionEquationTargets identity coreType body =
    CEq coreType (CGlobal identity) body
        : case (coreType, body) of
            (TyArrow TySet TyProp, CLam TySet predicate) ->
                [ CForall TySet
                    (CEq TyProp
                        (CApp (CGlobal identity) (CBound 0))
                        predicate)
                ]
            _ -> []


validateCandidateVampireProblem
    :: Provers.PreparedTypedProverTask
        SemanticFactOccurrenceFingerprint
        Void
        origin
        ObjectId
    -> CandidateProofState
    -> ExceptT DeclarationError IO CandidateProofState
validateCandidateVampireProblem prepared initial = do
    let problem = Provers.preparedTypedProverLogicalProblem prepared
        claim = Backend.typedProblemClaim problem
        target = candidateCheckedProposition
            (candidateProofCandidate initial)
    Except.liftEither do
        unless
            ( Vector.null (Backend.supportedPropositionSupport claim)
              && Backend.supportedPropositionTerm claim
                    == frozenCoreTerm (checkedPropositionTerm target)
            )
            (Left VampireTargetMismatch)
        unless
            (Vector.null (Backend.typedProblemLocalPremises problem))
            (Left VampireLocalPremisesNotSupported)
    validateVampireProblemEnvironment prepared initial

validatePreparedVampireProblem
    :: (Eq local, Eq origin)
    => Backend.TypedProblem
        SemanticFactOccurrenceFingerprint
        local
        origin
        ObjectId
    -> Provers.PreparedTypedProverTask
        SemanticFactOccurrenceFingerprint
        local
        origin
        ObjectId
    -> CandidateProofState
    -> ExceptT DeclarationError IO CandidateProofState
validatePreparedVampireProblem expectedProblem prepared initial = do
    let problem = Provers.preparedTypedProverLogicalProblem prepared
    Except.liftEither
        (unless (problem == expectedProblem)
            (Left VampireTargetMismatch)
        )
    validateVampireProblemEnvironment prepared initial

validateVampireProblemEnvironment
    :: Provers.PreparedTypedProverTask
        SemanticFactOccurrenceFingerprint
        local
        origin
        ObjectId
    -> CandidateProofState
    -> ExceptT DeclarationError IO CandidateProofState
validateVampireProblemEnvironment prepared initial = do
    let problem = Provers.preparedTypedProverLogicalProblem prepared
        builder = candidateProofBuilder initial
        closure = candidateProofObjectClosure initial
    Except.liftEither do
        traverse_
            (\(identity, reportedType) ->
                unless
                    (lookupCheckedObjectType identity closure
                        == Just reportedType)
                    (Left (VampireGlobalTypeMismatch identity)))
            (Map.toList (Backend.typedProblemGlobalTypes problem))
        traverse_
            (validateFoundationAuxiliary builder)
            (Backend.typedProblemAuxiliaries problem)
    execCandidateProof initial do
        traverse_
            validatePremise
            (Backend.typedProblemGlobalPremises problem)
  where
    validatePremise selected = do
        let fingerprint = Backend.typedBackendFactReference selected
        proposition <- consumeAuthorizedFact fingerprint
        state <- CandidateProof State.get
        unless
            ( Backend.supportedPropositionTerm
                (Backend.typedBackendFactProposition selected)
                == frozenCoreTerm
                    (checkedPropositionTerm proposition)
            )
            (failCandidateProof
                (VampirePremiseMismatch fingerprint))
        let closure =
                candidateProofObjectClosure state
        supported <-
            either
                (const
                    (failCandidateProof
                        (VampirePremiseCapabilityMismatch
                            fingerprint)))
                pure
                (Backend.supportedProposition
                    Vector.empty
                    (embedClosedCore
                        []
                        (checkedPropositionTerm proposition)))
        capability <-
            either
                (const
                    (failCandidateProof
                        (VampirePremiseCapabilityMismatch
                            fingerprint)))
                pure
                (Backend.classifySupportedProposition
                    (`lookupCheckedObjectType` closure)
                    supported)
        unless
            (capability
                == Backend.typedBackendFactCapability selected)
            (failCandidateProof
                (VampirePremiseCapabilityMismatch fingerprint))

    validateFoundationAuxiliary builder auxiliary = do
        let tag = Backend.typedProblemAuxiliaryTag auxiliary
            actual =
                Backend.supportedPropositionTerm
                    (Backend.typedProblemAuxiliaryProposition auxiliary)
            expectedTerm =
                frozenCoreTerm
                    (mapFrozenGlobals
                        absurd
                        (foundationAxiomFrozen
                            (logicalBuilderFoundation builder)
                            tag))
        unless (actual == expectedTerm)
            (Left (VampireFoundationMismatch tag))

execCandidateProof
    :: CandidateProofState
    -> CandidateProof value
    -> ExceptT DeclarationError IO CandidateProofState
execCandidateProof initial action =
    snd <$> State.runStateT (runCandidateProof action) initial

failCandidateProof
    :: DeclarationError
    -> CandidateProof value
failCandidateProof =
    CandidateProof . State.lift . Except.throwError

data ValidationMode
    = EnvironmentImportMode
    | ProofValidationMode !ProofSyntaxId
    | DeclarationValidationMode !DeclarationSyntaxId

data PlannedVampireDisposition
    = PlannedCachedRequest !Provers.PreparedVerificationRequest
    | PlannedLiveRequest
        !Provers.PreparedVerificationRequest
        !Provers.VampireHandle
    | PlannedSynchronousRequest !Provers.PreparedVerificationRequest

data PlannedCandidate = PlannedCandidate
    !ReservedCandidate
    !FactAuthority
    !DirectAuthorization
    ![PlannedVampireDisposition]

data PlannedReplayRequest
    = ReplayLive
        !Provers.PreparedVerificationRequest
        !Provers.VampireHandle
    | ReplaySynchronous !Provers.PreparedVerificationRequest

data PlannedValidationSelection
    = PlannedFreshValidation
    | PlannedProofValidation
        !ProofValidationKey
        !ProofValidationRecord
    | PlannedCompiledValidation
        !DeclarationValidationKey
        !DeclarationValidationRecord

-- | One completely lowered and submitted declaration.  It carries no
-- builder authorization or materialized certificate; all authority is
-- reconstructed by the source-ordered admission cursor.
data PlannedDeclaration body = PlannedDeclaration
    !(CheckedDeclaration body)
    !PrefixContextId
    !PrefixContextId
    !DeclarationInterfaceDelta
    ![AssertedObject]
    ![CheckedPropositionContent]
    ![NonEmpty PlannedCandidate]
    !PlannedValidationSelection

plannedDeclarationPreviousPrefix
    :: PlannedDeclaration body
    -> PrefixContextId
plannedDeclarationPreviousPrefix
        (PlannedDeclaration _checked previous _next _delta
            _objects _propositions _candidates _validation) =
    previous

plannedDeclarationNextPrefix
    :: PlannedDeclaration body
    -> PrefixContextId
plannedDeclarationNextPrefix
        (PlannedDeclaration _checked _previous next _delta
            _objects _propositions _candidates _validation) =
    next

plannedDeclarationDelta
    :: PlannedDeclaration body
    -> DeclarationInterfaceDelta
plannedDeclarationDelta
        (PlannedDeclaration _checked _previous _next delta
            _objects _propositions _candidates _validation) =
    delta

newtype PlanningIntegrityError = PlanningIntegrityError Text
    deriving stock (Show)

instance Exception.Exception PlanningIntegrityError

-- | Advance the authority-free semantic projection through one complete
-- checked declaration.  Validation selection and every deterministic check
-- finish before the first live request is submitted.
planCheckedDeclaration
    :: CheckedDeclaration body
    -> LoweringDriver (Either DeclarationError (PlannedDeclaration body))
planCheckedDeclaration checked@(CheckedDeclaration
        mode objects explicitPropositions globals descriptors stages
        _body) = LoweringDriver do
    state@(LoweringState resolver (ProspectiveBuilder builder) validationRun) <-
        State.get
    prepared <- liftIO (Except.runExceptT do
        closure <-
            Except.liftEither
                (first DeclarationObjectValidationFailed
                    (extendObjectClosure
                        (logicalBuilderObjectClosure builder)
                        objects))
        let reservedStages =
                reservePlanningStages builder stages
        plannedWithoutDisposition <-
            Except.liftEither
                (preparePlannedCandidates builder closure reservedStages)
        let orderedCandidates = fmap (fmap fst) plannedWithoutDisposition
            occurrences =
                [ candidateOccurrence reserved authority
                | stage <- plannedWithoutDisposition
                , (PlannedCandidate reserved authority _direct _requests,
                    _requestValues) <- toList stage
                ]
            aliases =
                [ semanticAlias alias
                    (semanticFactFingerprint
                        (candidateOccurrence reserved authority))
                | stage <- plannedWithoutDisposition
                , (PlannedCandidate reserved authority _direct _requests,
                    _requestValues) <- toList stage
                , alias <- candidateAliases reserved
                ]
            allCandidatePropositions =
                candidateCheckedProposition . fst
                    <$> concatMap toList reservedStages
            propositions =
                stableUniqueBy checkedPropositionId
                    (explicitPropositions <> allCandidatePropositions)
            objectIds = assertedObjectId <$> objects
            propositionIds = checkedPropositionId <$> propositions
            ownSlot = declarationSlot
                (logicalBuilderOwner builder)
                (localDeclarationOrdinal
                    (logicalBuilderNextDeclaration builder))
        traverse_
            (\proposition ->
                void
                    (Except.liftEither
                        (first DeclarationPropositionValidationFailed
                            (validateAssertedPropositionContent
                                closure
                                (checkedPropositionId proposition)
                                (frozenCoreTerm
                                    (checkedPropositionTerm proposition))))))
            propositions
        (resolvedStructures, delta, next) <-
            Except.liftEither
                (buildCheckedDeclarationDelta
                    builder closure ownSlot occurrences aliases objectIds
                    propositionIds (reverse globals) (reverse descriptors))
        selection <-
            selectPlannedValidation
                validationRun mode builder objects orderedCandidates
        planned <-
            submitPlannedCandidates resolver selection
                plannedWithoutDisposition
        let nextBuilder =
                appendProspectiveBuilder
                    closure resolvedStructures delta next planned builder
            declaration =
                PlannedDeclaration checked
                    (logicalBuilderPrefix builder)
                    next delta objects propositions planned selection
        pure (declaration, nextBuilder))
    case prepared of
        Left failure -> pure (Left failure)
        Right (declaration, nextBuilder) -> do
            let LoweringState currentResolver _current currentValidation = state
            State.put
                (LoweringState
                    currentResolver
                    (ProspectiveBuilder nextBuilder)
                    currentValidation)
            pure (Right declaration)

reservePlanningStages
    :: BuilderState PlanningEvidence
    -> [NonEmpty CheckedCandidate]
    -> [NonEmpty (ReservedCandidate, CandidatePlanningSpec)]
reservePlanningStages builder =
    snd . mapAccumPlanning reserveStage (logicalBuilderNextFact builder)
  where
    invocation = DeclarationInvocation (logicalBuilderNextInvocation builder)
    reserveStage nextFact (stageIndex, specs) =
        let candidates =
                NonEmpty.zipWith
                    (\offset (CheckedCandidate spec planning) ->
                        ( ReservedCandidate
                            (logicalBuilderIdentity builder)
                            (logicalBuilderPrefix builder)
                            invocation
                            (CandidateStage stageIndex)
                            (factSlot
                                (logicalBuilderOwner builder)
                                (localFactOrdinal (nextFact + offset)))
                            spec
                        , planning
                        ))
                    (0 :| [1..])
                    specs
        in ( nextFact + fromIntegral (NonEmpty.length specs)
           , candidates
           )

    mapAccumPlanning action initial values =
        go initial (zip [0..] values)
      where
        go accumulator [] = (accumulator, [])
        go accumulator (value : remaining) =
            let (next, result) = action accumulator value
                (final, results) = go next remaining
            in (final, result : results)

preparePlannedCandidates
    :: BuilderState PlanningEvidence
    -> CheckedObjectClosure
    -> [NonEmpty (ReservedCandidate, CandidatePlanningSpec)]
    -> Either
        DeclarationError
        [NonEmpty (PlannedCandidate, [CheckedPlannedVampireRequest])]
preparePlannedCandidates builder closure stages =
    snd <$> mapAccumM prepareStage Map.empty (zip [0..] stages)
  where
    prepareStage earlier (stageIndex, stage) = do
        (sameStage, planned) <-
            mapAccumM
                (prepareCandidate stageIndex earlier)
                Map.empty
                (zip [0..] (toList stage))
        pure (Map.union earlier sameStage, NonEmpty.fromList planned)

    prepareCandidate stageIndex earlier sameStage
            (candidateIndex, (candidate, contract)) = do
        let position = PlannedCandidatePosition stageIndex candidateIndex
        (direct, safety, requests) <-
            prepareCandidatePlanningContract
                builder closure earlier position candidate contract
        let authority =
                candidateFactAuthority
                    (candidateTheoremReference builder candidate)
                    safety
            planned = PlannedCandidate candidate authority direct []
        pure
            ( Map.insert position (candidate, authority) sameStage
            , (planned, requests)
            )

    mapAccumM action initial values =
        go initial [] values
      where
        go accumulator outputs = \case
            [] -> pure (accumulator, reverse outputs)
            value : remaining -> do
                (next, output) <- action accumulator value
                go next (output : outputs) remaining

prepareCandidatePlanningContract
    :: BuilderState PlanningEvidence
    -> CheckedObjectClosure
    -> Map PlannedCandidatePosition (ReservedCandidate, FactAuthority)
    -> PlannedCandidatePosition
    -> ReservedCandidate
    -> CandidatePlanningSpec
    -> Either
        DeclarationError
        ( DirectAuthorization
        , CandidateSafety
        , [CheckedPlannedVampireRequest]
        )
prepareCandidatePlanningContract builder closure earlier current candidate
        (CandidatePlanningSpec direct extraFacts staged requests) = do
    safetyWithFacts <-
        foldM (accumulatePlanningFact builder closure)
            initialCandidateSafety
            (stableUniqueBy id
                ( extraFacts
                    <> concatMap requestFacts requests
                ))
    safetyWithStages <-
        foldM consumeStage safetyWithFacts staged
    let safety = case direct of
            PlanningSourceAxiom ->
                addCandidateEscape SourceAxiom safetyWithStages
            PlanningOmitted ->
                addCandidateEscape Omitted safetyWithStages
            _ -> safetyWithStages
        requestIds = requestIdentity <$> requests
        directAuthorization = case direct of
            PlanningDefinitionEquation identity ->
                CheckedKernelConstruction
                    (CheckedDefinitionEquation identity)
            PlanningSourceAxiom -> SourceAxiomAuthorization
            PlanningTrustedDatatype descriptor ->
                TrustedCompilation (DatatypeCompilation descriptor)
            PlanningKernelConstruction descriptor ->
                CheckedKernelConstruction descriptor
            PlanningCheckedSourceProof ->
                CheckedSourceProof requestIds
            PlanningOmitted -> OmittedAuthorization
    validatePlanningDirect directAuthorization safety
    pure (directAuthorization, safety, requests)
  where
    requestFacts
            (CheckedPlannedVampireRequest _location _request facts) = facts
    requestIdentity
            (CheckedPlannedVampireRequest _location request _facts) =
        Provers.preparedVerificationRequestId request

    consumeStage safety position = do
        (premise, authority) <-
            maybe
                (Left
                    (PlanningFactContractMismatch
                        (reservedCandidateSlot candidate)))
                Right
                (Map.lookup position earlier)
        let PlannedCandidatePosition premiseStage _premiseIndex = position
            PlannedCandidatePosition currentStage _currentIndex = current
        unless (premiseStage < currentStage)
            (Left
                (StagedPremiseNotEarlier
                    (reservedCandidateSlot premise)
                    premiseStage
                    (reservedCandidateSlot candidate)
                    currentStage))
        first FactSafetyFailed
            (accumulateFactSafety
                (candidateTheoremReference builder premise)
                authority
                safety)

accumulatePlanningFact
    :: BuilderState PlanningEvidence
    -> CheckedObjectClosure
    -> CandidateSafety
    -> SemanticFactOccurrenceFingerprint
    -> Either DeclarationError CandidateSafety
accumulatePlanningFact builder closure safety fingerprint = do
    FactEntry proposition occurrence (PlanningEvidence authority _provenance) <-
        maybe
            (Left (AuthorizedFactNotVisible fingerprint))
            Right
            (Map.lookup fingerprint (logicalBuilderFacts builder))
    unless
        ( semanticFactFingerprint occurrence == fingerprint
          && semanticFactAuthority occurrence == authority
          && propositionMatchesClosure closure proposition
        )
        (Left (PlanningFactContractMismatch (semanticFactSlot occurrence)))
    first FactSafetyFailed
        (accumulateFactSafety
            (theoremRef
                (logicalBuilderTheory builder)
                (checkedPropositionId proposition))
            authority
            safety)

validatePlanningDirect
    :: DirectAuthorization
    -> CandidateSafety
    -> Either DeclarationError ()
validatePlanningDirect direct safety =
    case direct of
        SourceAxiomAuthorization ->
            unless
                (candidateSafetyAuthority safety
                    == authoritySafety (singletonEscapeKind SourceAxiom))
                (Left
                    (ValidationCertificateFailed
                        (SourceAxiomSafetyMismatch
                            (candidateSafetyAuthority safety))))
        OmittedAuthorization ->
            unless
                (Omitted `elem` escapeKindsToList
                    (authoritySafetyEscapeKinds
                        (candidateSafetyAuthority safety)))
                (Left
                    (ValidationCertificateFailed
                        (OmittedSafetyMissing
                            (candidateSafetyAuthority safety))))
        _ -> pure ()

selectPlannedValidation
    :: ValidationRun
    -> CheckedDeclarationMode
    -> BuilderState PlanningEvidence
    -> [AssertedObject]
    -> [NonEmpty PlannedCandidate]
    -> ExceptT DeclarationError IO PlannedValidationSelection
selectPlannedValidation validationRun mode builder objects stages =
    case mode of
        CheckedProofMode syntax ->
            case concatMap toList stages of
                [planned@(PlannedCandidate _candidate authority _direct _)] -> do
                    let key = proofValidationKey
                            (theoremId (factAuthorityTheorem authority))
                            syntax
                            (logicalBuilderPrefix builder)
                    cached <- case validationRun of
                        FreshValidation -> pure Nothing
                        WarmValidation (ValidationLookup lookupProof _) ->
                            liftIO (lookupProof key)
                    traverse_
                        (validateProof planned syntax)
                        cached
                    pure case cached of
                        Nothing -> PlannedFreshValidation
                        Just record -> PlannedProofValidation key record
                candidates ->
                    Except.throwError
                        (CheckedProofCandidateCountMismatch
                            (length candidates))
        CheckedCompiledMode syntax -> do
            let planned = concatMap toList stages
                objectIds = assertedObjectId <$> objects
                theorems =
                    theoremId . factAuthorityTheorem . plannedAuthority
                        <$> planned
                key = declarationValidationKey syntax
                    (logicalBuilderPrefix builder) objectIds theorems
            cached <- case validationRun of
                FreshValidation -> pure Nothing
                WarmValidation (ValidationLookup _ lookupDeclaration) ->
                    liftIO (lookupDeclaration key)
            traverse_
                (validateCompiled planned syntax objectIds theorems)
                cached
            pure case cached of
                Nothing -> PlannedFreshValidation
                Just record -> PlannedCompiledValidation key record
  where
    plannedAuthority (PlannedCandidate _ authority _ _) = authority

    validateProof
            (PlannedCandidate candidate authority direct _)
            syntax record =
        case Materialization.checkCandidateValidation
                (logicalBuilderTheory builder)
                (logicalBuilderPrefix builder)
                (candidateCheckedProposition candidate)
                authority direct
                (Materialization.candidateProofValidation record syntax) of
            Left failure ->
                liftIO
                    (throwIO (CachedValidationIntegrityError failure))
            Right () -> pure ()

    validateCompiled planned syntax objectIds theorems record = do
        case Materialization.checkDeclarationValidationRecord
                (logicalBuilderPrefix builder)
                syntax objectIds theorems record of
            Left failure ->
                liftIO
                    (throwIO (CachedValidationIntegrityError failure))
            Right () -> pure ()
        traverse_
            (\(ordinal,
                PlannedCandidate candidate authority direct _) ->
                case Materialization.checkCandidateValidation
                        (logicalBuilderTheory builder)
                        (logicalBuilderPrefix builder)
                        (candidateCheckedProposition candidate)
                        authority direct
                        (Materialization.candidateDeclarationValidation
                            record syntax objectIds theorems ordinal) of
                    Left failure ->
                        liftIO
                            (throwIO
                                (CachedValidationIntegrityError failure))
                    Right () -> pure ())
            (zip [0..] planned)

submitPlannedCandidates
    :: VampireResolver
    -> PlannedValidationSelection
    -> [NonEmpty (PlannedCandidate, [CheckedPlannedVampireRequest])]
    -> ExceptT DeclarationError IO [NonEmpty PlannedCandidate]
submitPlannedCandidates resolver selection candidates
    | cached =
        pure (fmap (fmap cachedCandidate) candidates)
    | otherwise = do
        let requests =
                [ request
                | stage <- candidates
                , (_candidate, plannedRequests) <- toList stage
                , CheckedPlannedVampireRequest
                    _location request _facts <- plannedRequests
                ]
        case resolver of
            VampireResolver SynchronousVampireResolution{} _observe ->
                pure (fmap (fmap synchronousCandidate) candidates)
            VampireResolver
                    (AsynchronousVampireSubmission submit) _observe -> do
                handles <- case NonEmpty.nonEmpty requests of
                    Nothing -> pure []
                    Just nonempty -> do
                        submitted <- liftIO (submit nonempty)
                        unless
                            (NonEmpty.length submitted == length requests)
                            (Except.throwError
                                (VampireResolverBatchSizeMismatch
                                    (length requests)
                                    (NonEmpty.length submitted)))
                        pure (toList submitted)
                let (planned, remaining) =
                        State.runState
                            (traverse (traverse liveCandidate) candidates)
                            handles
                unless (null remaining)
                    (Except.throwError
                        (VampireResolverBatchSizeMismatch
                            (length requests)
                            (length requests + length remaining)))
                pure planned
  where
    cached = case selection of
        PlannedFreshValidation -> False
        PlannedProofValidation{} -> True
        PlannedCompiledValidation{} -> True

    cachedCandidate
            (PlannedCandidate candidate authority direct _dispositions,
             requests) =
        PlannedCandidate candidate authority direct
            [ PlannedCachedRequest request
            | CheckedPlannedVampireRequest
                _location request _facts <- requests
            ]

    liveCandidate
            (PlannedCandidate candidate authority direct _dispositions,
             requests) = do
        dispositions <- traverse takeHandle requests
        pure (PlannedCandidate candidate authority direct dispositions)

    synchronousCandidate
            (PlannedCandidate candidate authority direct _dispositions,
             requests) =
        PlannedCandidate candidate authority direct
            [ PlannedSynchronousRequest request
            | CheckedPlannedVampireRequest
                _location request _facts <- requests
            ]

    takeHandle
            (CheckedPlannedVampireRequest _location request _facts) = do
        remaining <- State.get
        case remaining of
            [] ->
                impossible
                    "validated prospective handle count became exhausted"
            handle : later -> do
                State.put later
                pure (PlannedLiveRequest request handle)

appendProspectiveBuilder
    :: CheckedObjectClosure
    -> Map SemanticStructurePhrase ResolvedStructure
    -> DeclarationInterfaceDelta
    -> PrefixContextId
    -> [NonEmpty PlannedCandidate]
    -> BuilderState PlanningEvidence
    -> BuilderState PlanningEvidence
appendProspectiveBuilder closure structures delta next planned builder =
    builder
        { logicalBuilderPrefix = next
        , logicalBuilderObjectClosure = closure
        , logicalBuilderFacts =
            foldl' insertPlanningFact
                (logicalBuilderFacts builder)
                (concatMap toList planned)
        , logicalBuilderAliases =
            foldl'
                (\entries alias ->
                    Map.insert
                        (semanticAliasName alias)
                        (ImportedAliasBinding
                            (semanticAliasTarget alias)
                            (ImportedAliasOrigin
                                (declarationDeltaSlot delta)
                                (semanticAliasTarget alias)))
                        entries)
                (logicalBuilderAliases builder)
                (declarationDeltaAliases delta)
        , logicalBuilderGlobals =
            foldl'
                (\entries binding ->
                    Map.insert
                        (semanticGlobalBindingKey binding)
                        (semanticGlobalBindingTarget binding)
                        entries)
                (logicalBuilderGlobals builder)
                (semanticEnvironmentBindings
                    (declarationDeltaEnvironment delta))
        , logicalBuilderStructures = structures
        , logicalBuilderDeltas = delta : logicalBuilderDeltas builder
        , logicalBuilderNextDeclaration =
            logicalBuilderNextDeclaration builder + 1
        , logicalBuilderNextFact =
            logicalBuilderNextFact builder
                + fromIntegral (sum (fmap NonEmpty.length planned))
        , logicalBuilderNextInvocation =
            logicalBuilderNextInvocation builder + 1
        }
  where
    insertPlanningFact entries
            (PlannedCandidate candidate authority _direct _requests) =
        let occurrence = candidateOccurrence candidate authority
            fingerprint = semanticFactFingerprint occurrence
            evidence = PlanningEvidence authority
                (Just
                    (PlanningProvenance
                        (declarationDeltaSlot delta)
                        (reservedStageValue candidate)
                        (reservedCandidateSlot candidate)))
        in Map.insert fingerprint
            (FactEntry
                (candidateCheckedProposition candidate)
                occurrence
                evidence)
            entries

    -- Keep the constructor match private while storing exact stage provenance.
    reservedStageValue
            (ReservedCandidate _identity _prefix _invocation stage _slot _spec) =
        stage

-- | Admit one checked declaration through the existing authoritative
-- source-order cursor.  The callback interprets a closed family recipe over
-- freshly reserved stage slots; it is not retained in the checked value.
admitCheckedDeclaration
    :: CheckedDeclaration body
    -> (body -> [NonEmpty ReservedCandidate] -> Declaration ())
    -> ModuleDriver failure CommittedDeclarationBatch
admitCheckedDeclaration
        (CheckedDeclaration
            mode objects propositions globals structures stages body)
        authorize =
    snd <$> do
        case mode of
            CheckedProofMode syntax ->
                commitProofDeclaration syntax do
                    reserved <- installCheckedStructure
                    authorize body reserved
            CheckedCompiledMode syntax ->
                commitCompiledDeclaration syntax do
                    reserved <- installCheckedStructure
                    authorizeCompiledDeclaration
                        (authorize body reserved)
  where
    installCheckedStructure = do
        traverse_ addDeclarationObject objects
        traverse_ addDeclarationProposition propositions
        traverse_
            (\binding ->
                stageSemanticGlobalBinding
                    (semanticGlobalBindingKey binding)
                    (semanticGlobalBindingTarget binding))
            globals
        traverse_ stageSemanticStructureDescriptor structures
        traverse
            (reserveCandidateBatch . fmap checkedCandidateSemanticSpec)
            stages

    checkedCandidateSemanticSpec
            (CheckedCandidate spec _planning) = spec

-- | Admit one retained plan against the real authorized builder.  The family
-- callback performs the existing authority checks, but every live resolver
-- result comes from the handle submitted during planning and every validation
-- lookup is the inert selection retained by the plan.
admitPlannedCheckedDeclaration
    :: PlannedDeclaration body
    -> (body -> [NonEmpty ReservedCandidate] -> Declaration ())
    -> ModuleDriver failure CommittedDeclarationBatch
admitPlannedCheckedDeclaration planned@(PlannedDeclaration
        checked previous _expectedNext _expectedDelta _objects _propositions
        candidates selection) authorize = ModuleDriver do
    DriverState originalResolver builder prefix originalValidation <-
        State.get
    unless (logicalBuilderPrefix builder == previous)
        (liftIO
            (throwIO
                (PlanningIntegrityError
                    "planned declaration predecessor does not match the admitted builder")))
    liveRef <- liftIO
        (newIORef
            [ replay
            | stage <- candidates
            , PlannedCandidate _candidate _authority _direct dispositions <-
                toList stage
            , disposition <- dispositions
            , replay <- case disposition of
                PlannedCachedRequest{} -> []
                PlannedLiveRequest request handle ->
                    [ReplayLive request handle]
                PlannedSynchronousRequest request ->
                    [ReplaySynchronous request]
            ])
    replay <- liftIO (plannedReplayResolver originalResolver liveRef)
    let validation = plannedAdmissionValidation selection
    State.put (DriverState replay builder prefix validation)
    batch <- runDriverStep (admitCheckedDeclaration checked authorize)
    remaining <- liftIO (readIORef liveRef)
    unless (null remaining)
        (liftIO
            (throwIO
                (PlanningIntegrityError
                    "admission did not consume every planned live request")))
    liftIO (validateAdmittedPlan planned batch)
    DriverState _replay admittedBuilder admittedPrefix _plannedValidation <-
        State.get
    State.put
        (DriverState
            originalResolver admittedBuilder admittedPrefix originalValidation)
    pure batch

plannedReplayResolver
    :: VampireResolver
    -> IORef [PlannedReplayRequest]
    -> IO VampireResolver
plannedReplayResolver original liveRef =
    pure
        (vampireBatchResolverWithPreparationObserver resolve
            (observeVampirePreparation original))
  where
    resolve
        :: forall local origin.
           NonEmpty
                (Provers.PreparedTypedProverTask
                    SemanticFactOccurrenceFingerprint
                    local
                    origin
                    ObjectId)
        -> IO
            (NonEmpty
                (Either
                    Provers.ProverProcessError
                    Provers.ProverAnswer))
    resolve tasks = do
        expected <- atomicModifyIORef' liveRef \remaining ->
            let amount = NonEmpty.length tasks
                (selected, later) = splitAt amount remaining
            in (later, selected)
        unless (length expected == NonEmpty.length tasks)
            (throwIO
                (PlanningIntegrityError
                    "admission requested a different number of live Vampire results"))
        traverse_ validateExpected (zip (toList tasks) expected)
        case expected of
            ReplayLive{} : _ -> do
                unless (all isLive expected)
                    (throwIO
                        (PlanningIntegrityError
                            "planned resolver batch mixed execution modes"))
                results <- traverse awaitOne expected
                maybe
                    (throwIO
                        (PlanningIntegrityError
                            "an admission resolver batch was unexpectedly empty"))
                    pure
                    (NonEmpty.nonEmpty results)
            ReplaySynchronous{} : _ ->
                resolveSynchronousVampireBatch original tasks
            [] ->
                throwIO
                    (PlanningIntegrityError
                        "an admission resolver batch was unexpectedly empty")

    validateExpected (task, replay) = do
        let actual = Provers.preparedTypedProverRequest task
            expected = replayRequest replay
        unless (actual == expected)
            (throwIO
                (PlanningIntegrityError
                    "admission request differs from its planned exact request"))

    awaitOne (ReplayLive expected handle) =
        Provers.awaitPreparedVampireRequest expected handle
    awaitOne ReplaySynchronous{} =
        impossible "validated live resolver batch changed execution mode"

    replayRequest = \case
        ReplayLive request _handle -> request
        ReplaySynchronous request -> request

    isLive = \case
        ReplayLive{} -> True
        ReplaySynchronous{} -> False

plannedAdmissionValidation
    :: PlannedValidationSelection
    -> ValidationRun
plannedAdmissionValidation = \case
    PlannedFreshValidation -> FreshValidation
    PlannedProofValidation expected record ->
        WarmValidation
            (validationLookup
                (\actual ->
                    if actual == expected
                        then pure (Just record)
                        else throwIO
                            (PlanningIntegrityError
                                "proof validation key changed during admission"))
                (\_actual -> pure Nothing))
    PlannedCompiledValidation expected record ->
        WarmValidation
            (validationLookup
                (\_actual -> pure Nothing)
                (\actual ->
                    if actual == expected
                        then pure (Just record)
                        else throwIO
                            (PlanningIntegrityError
                                "declaration validation key changed during admission")))

validateAdmittedPlan
    :: PlannedDeclaration body
    -> CommittedDeclarationBatch
    -> IO ()
validateAdmittedPlan
        (PlannedDeclaration _checked expectedPrevious expectedNext expectedDelta
            expectedObjects expectedPropositions candidates selection)
        batch = do
    let expectedContracts =
            [ (authority, direct)
            | stage <- candidates
            , PlannedCandidate _candidate authority direct _requests <-
                toList stage
            ]
        actualCertificates =
            (proofValidationRecordCertificate
                <$> committedBatchProofValidations batch)
                <> maybe
                    []
                    declarationValidationRecordCertificates
                    (committedBatchDeclarationValidation batch)
        actualContracts =
            [ ( validationTarget certificate
              , validationDirectAuthorization certificate
              )
            | certificate <- actualCertificates
            ]
        validationAgrees = case selection of
            PlannedFreshValidation -> True
            PlannedProofValidation _ record ->
                committedBatchProofValidations batch == [record]
            PlannedCompiledValidation _ record ->
                committedBatchDeclarationValidation batch == Just record
    unless
        ( committedBatchPreviousPrefix batch == expectedPrevious
          && committedBatchNextPrefix batch == expectedNext
          && committedBatchDelta batch == expectedDelta
          && committedBatchObjects batch == expectedObjects
          && fmap propositionContract (committedBatchPropositions batch)
                == fmap propositionContract expectedPropositions
          && actualContracts == expectedContracts
          && validationAgrees
        )
        (throwIO
            (PlanningIntegrityError
                "admitted declaration differs from its prospective contract"))
  where
    propositionContract proposition =
        ( checkedPropositionId proposition
        , checkedPropositionTerm proposition
        )

commitProofDeclaration
    :: ProofSyntaxId
    -> Declaration value
    -> ModuleDriver failure
        (value, CommittedDeclarationBatch)
commitProofDeclaration syntax =
    commitDeclaration (ProofValidationMode syntax)

commitCompiledDeclaration
    :: DeclarationSyntaxId
    -> Declaration value
    -> ModuleDriver failure
        (value, CommittedDeclarationBatch)
commitCompiledDeclaration syntax =
    commitDeclaration (DeclarationValidationMode syntax)

commitDeclaration
    :: ValidationMode
    -> Declaration value
    -> ModuleDriver failure
        (value, CommittedDeclarationBatch)
commitDeclaration mode action = ModuleDriver do
    DriverState resolver builder pendingPrefix validationRun <-
        State.get
    let
        declaration =
            initialDeclarationState
                resolver
                validationRun
                mode
                builder
    result <-
        liftIO
            (Except.runExceptT
                (State.runStateT
                    (runDeclaration action)
                    declaration))
    case result of
        Left err ->
            Except.throwError (DriverDeclarationFailed err)
        Right (value, prepared) ->
            case appendDeclaration mode prepared of
                Left err ->
                    Except.throwError (DriverDeclarationFailed err)
                Right (builder', batch) ->
                    let prefix' = appendPendingBatch batch pendingPrefix
                    in do
                        State.put
                            (DriverState
                                resolver
                                builder'
                                prefix'
                                validationRun)
                        pure (value, batch)

initialDeclarationState
    :: VampireResolver
    -> ValidationRun
    -> ValidationMode
    -> LogicalBuilder
    -> DeclarationState
initialDeclarationState resolver validationRun validationMode builder =
    DeclarationState
        { declarationVampireResolver = resolver
        , declarationValidationRun = validationRun
        , declarationValidationMode = validationMode
        , declarationValidationSelection =
            DeclarationValidationUnselected
        , declarationBuilder = builder
        , declarationOwnSlot =
            declarationSlot
                (logicalBuilderOwner builder)
                (localDeclarationOrdinal
                    (logicalBuilderNextDeclaration builder))
        , declarationInvocation =
            DeclarationInvocation
                (logicalBuilderNextInvocation builder)
        , declarationObjectsReversed = []
        , declarationObjectClosure = Nothing
        , declarationPropositionsReversed = []
        , declarationGlobalBindingsReversed = []
        , declarationStructureDescriptorsReversed = []
        , declarationReservations = Map.empty
        , declarationPending = Map.empty
        , declarationNextFact = logicalBuilderNextFact builder
        , declarationNextStage = 0
        , declarationAuthorizationFrontier = 0
        }

appendDeclaration
    :: ValidationMode
    -> DeclarationState
    -> Either
        DeclarationError
        (LogicalBuilder, CommittedDeclarationBatch)
appendDeclaration mode declaration = do
    let builder = declarationBuilder declaration
        reservations = Map.elems (declarationReservations declaration)
        pending = declarationPending declaration
    unless
        (Map.keysSet pending
            == Map.keysSet (declarationReservations declaration))
        (Left DeclarationHasUnauthorizedCandidates)
    unless
        (declarationAuthorizationFrontier declaration
            == declarationNextStage declaration)
        (Left DeclarationAuthorizationFrontierIncomplete)
    case mode of
        DeclarationValidationMode{} ->
            case declarationValidationSelection declaration of
                DeclarationValidationUnselected ->
                    Left DeclarationValidationNotSelected
                _ -> pure ()
        _ -> pure ()
    closure <- declarationClosure declaration
    propositions <- validateDeclarationPropositions closure declaration
    traverse_ (validatePendingAuthorization declaration) (Map.elems pending)
    let orderedPending =
            [ pendingCandidate
            | reservation <- reservations
            , let slot = reservedCandidateSlot reservation
            , Just pendingCandidate <- [Map.lookup slot pending]
            ]
        occurrences = occurrenceFromPending <$> orderedPending
        aliases = concatMap aliasesFromPending orderedPending
        objectIds =
            assertedObjectId
                <$> reverse
                    (declarationObjectsReversed declaration)
        propositionIds =
            checkedPropositionId <$> propositions
    (structures, delta, next) <-
        buildCheckedDeclarationDelta
            builder
            closure
            (declarationOwnSlot declaration)
            occurrences
            aliases
            objectIds
            propositionIds
            (declarationGlobalBindingsReversed declaration)
            (declarationStructureDescriptorsReversed declaration)
    let previous = logicalBuilderPrefix builder
    (proofValidations, declarationValidation) <-
        buildValidationRecords
            mode previous objectIds orderedPending
    let builder' =
            appendBuilderState
                closure
                structures
                delta
                next
                orderedPending
                builder
                declaration
        batch =
            CommittedDeclarationBatch
                (logicalBuilderOwner builder)
                (declarationOwnSlot declaration)
                previous
                next
                delta
                (reverse
                    (declarationObjectsReversed declaration))
                propositions
                proofValidations
                declarationValidation
    pure (builder', batch)

-- | Construct and collision-check one canonical semantic delta without
-- inspecting fact evidence.  This remains the admitted append path now and
-- is the shared delta seam for the later prospective builder.
buildCheckedDeclarationDelta
    :: BuilderState evidence
    -> CheckedObjectClosure
    -> DeclarationSlot
    -> [SemanticFactOccurrence]
    -> [SemanticAlias]
    -> [ObjectId]
    -> [PropositionId]
    -> [SemanticGlobalBinding]
    -> [SemanticStructureDescriptor]
    -> Either
        DeclarationError
        ( Map SemanticStructurePhrase ResolvedStructure
        , DeclarationInterfaceDelta
        , PrefixContextId
        )
buildCheckedDeclarationDelta
        builder closure slot occurrences aliases objectIds propositionIds
        reversedBindings reversedDescriptors = do
    let bindings =
            List.sortOn
                semanticGlobalBindingKey
                (reverse reversedBindings)
        descriptors =
            List.sortOn
                semanticStructureDescriptorPhrase
                (reverse reversedDescriptors)
    traverse_
        (\binding ->
            first
                (DeclarationGlobalTargetInvalid
                    (semanticGlobalBindingKey binding)
                    (semanticGlobalBindingTarget binding))
                (validateSemanticGlobalBindingTarget
                    (structureOperationBindings
                        (logicalBuilderStructures builder))
                    closure binding))
        bindings
    traverse_
        (\descriptor ->
            let structurePhrase = semanticStructureDescriptorPhrase descriptor
            in when
                (Map.member structurePhrase
                    (logicalBuilderStructures builder))
                (Left (BuilderStructureCollision structurePhrase)))
        descriptors
    structures <- foldM
        (insertSemanticStructure closure)
        (logicalBuilderStructures builder)
        descriptors
    environment <-
        first DeclarationEnvironmentFailed
            (semanticEnvironmentWithStructures bindings descriptors)
    delta <-
        first DeclarationInterfaceFailed
            (declarationInterfaceDelta
                slot
                occurrences
                aliases
                objectIds
                propositionIds
                environment)
    validateBuilderCollisions builder delta
    pure
        ( structures
        , delta
        , nextPrefixContextId (logicalBuilderPrefix builder) delta
        )

declarationClosure
    :: DeclarationState
    -> Either DeclarationError CheckedObjectClosure
declarationClosure declaration =
    case declarationObjectClosure declaration of
        Just closure ->
            Right closure
        Nothing ->
            first DeclarationObjectValidationFailed
                (extendObjectClosure
                    (logicalBuilderObjectClosure
                        (declarationBuilder declaration))
                    (reverse
                        (declarationObjectsReversed declaration)))

prepareDeclarationClosure
    :: DeclarationState
    -> Either DeclarationError DeclarationState
prepareDeclarationClosure declaration = do
    closure <- declarationClosure declaration
    pure declaration{declarationObjectClosure = Just closure}

validateDeclarationPropositions
    :: CheckedObjectClosure
    -> DeclarationState
    -> Either DeclarationError [CheckedPropositionContent]
validateDeclarationPropositions closure declaration = do
    let explicit =
            reverse
                (declarationPropositionsReversed declaration)
        reserved =
            candidateCheckedProposition
                <$> Map.elems
                    (declarationReservations declaration)
        propositions = stableUniqueBy checkedPropositionId (explicit <> reserved)
    traverse_
        (\proposition ->
            void
                (first DeclarationPropositionValidationFailed
                    (validateAssertedPropositionContent
                        closure
                        (checkedPropositionId proposition)
                        (frozenCoreTerm
                            (checkedPropositionTerm proposition)))))
        propositions
    pure propositions

validatePendingAuthorization
    :: DeclarationState
    -> PendingCandidate
    -> Either DeclarationError ()
validatePendingAuthorization declaration
        (PendingCandidate candidate certificate authorization) = do
    validateReservedCandidate declaration candidate
    let builder = declarationBuilder declaration
        PendingFactAuthorization
            identity prefix invocation slot authority stage =
                authorization
    unless
        ( identity == logicalBuilderIdentity builder
          && prefix == logicalBuilderPrefix builder
          && invocation == declarationInvocation declaration
          && slot == reservedCandidateSlot candidate
          && authority == validationTarget certificate
          && stage == reservedStage candidate
        )
        (Left PendingFactAuthorizationMismatch)

occurrenceFromPending
    :: PendingCandidate
    -> SemanticFactOccurrence
occurrenceFromPending
        (PendingCandidate candidate certificate _authorization) =
    candidateOccurrence candidate (validationTarget certificate)

aliasesFromPending :: PendingCandidate -> [SemanticAlias]
aliasesFromPending pending@(PendingCandidate
        candidate _certificate _authorization) =
    let occurrence = occurrenceFromPending pending
        fingerprint = semanticFactFingerprint occurrence
    in (`semanticAlias` fingerprint) <$> candidateAliases candidate

buildValidationRecords
    :: ValidationMode
    -> PrefixContextId
    -> [ObjectId]
    -> [PendingCandidate]
    -> Either
        DeclarationError
        ([ProofValidationRecord], Maybe DeclarationValidationRecord)
buildValidationRecords mode prefix objects pending =
    case mode of
        EnvironmentImportMode ->
            impossible
                "environment import produced declaration validation records"
        ProofValidationMode syntax ->
            case pending of
                [PendingCandidate _ certificate _] ->
                    let authority = validationTarget certificate
                        key =
                            proofValidationKey
                                (theoremId
                                    (factAuthorityTheorem authority))
                                syntax
                                prefix
                    in Right
                        ( [proofValidationRecord key certificate]
                        , Nothing
                        )
                _ ->
                    Left ProofDeclarationMustProduceOneFact
        DeclarationValidationMode syntax ->
            let certificates =
                    [ certificate
                    | PendingCandidate _ certificate _ <- pending
                    ]
                theorems =
                    theoremId
                        . factAuthorityTheorem
                        . validationTarget
                        <$> certificates
                key =
                    declarationValidationKey
                        syntax prefix objects theorems
            in Right
                ( []
                , Just
                    (declarationValidationRecord
                        key certificates)
                )

validateBuilderCollisions
    :: BuilderState evidence
    -> DeclarationInterfaceDelta
    -> Either DeclarationError ()
validateBuilderCollisions builder delta = do
    traverse_
        (\occurrence ->
            when
                (Map.member
                    (semanticFactFingerprint occurrence)
                    (logicalBuilderFacts builder))
                (Left
                    (BuilderFactCollision
                        (semanticFactFingerprint occurrence))))
        (declarationDeltaFacts delta)
    traverse_
        (\alias ->
            when
                (Map.member
                    (semanticAliasName alias)
                    (logicalBuilderAliases builder))
                (Left
                    (BuilderAliasCollision
                        (semanticAliasName alias))))
        (declarationDeltaAliases delta)
    traverse_
        (\identity ->
            when
                (identity
                    `Set.member` checkedObjectIds
                        (logicalBuilderObjectClosure builder))
                (Left (BuilderObjectCollision identity)))
        (declarationDeltaObjects delta)
    traverse_
        (\binding ->
            case Map.lookup
                    (semanticGlobalBindingKey binding)
                    (logicalBuilderGlobals builder) of
                Nothing -> pure ()
                Just existing ->
                    Left
                        (BuilderGlobalCollision
                            (semanticGlobalBindingKey binding)
                            existing))
        (semanticEnvironmentBindings
            (declarationDeltaEnvironment delta))

appendBuilderState
    :: CheckedObjectClosure
    -> Map SemanticStructurePhrase ResolvedStructure
    -> DeclarationInterfaceDelta
    -> PrefixContextId
    -> [PendingCandidate]
    -> LogicalBuilder
    -> DeclarationState
    -> LogicalBuilder
appendBuilderState closure structures delta next pending builder declaration =
    builder
        { logicalBuilderPrefix = next
        , logicalBuilderObjectClosure = closure
        , logicalBuilderFacts =
            foldl'
                (insertAuthorizedFact builder)
                (logicalBuilderFacts builder)
                pending
        , logicalBuilderAliases =
            foldl'
                (\entries alias ->
                    Map.insert
                        (semanticAliasName alias)
                        (ImportedAliasBinding
                            (semanticAliasTarget alias)
                            (ImportedAliasOrigin
                                (declarationDeltaSlot delta)
                                (semanticAliasTarget alias)))
                        entries)
                (logicalBuilderAliases builder)
                (declarationDeltaAliases delta)
        , logicalBuilderGlobals =
            foldl'
                (\entries binding ->
                    Map.insert
                        (semanticGlobalBindingKey binding)
                        (semanticGlobalBindingTarget binding)
                        entries)
                (logicalBuilderGlobals builder)
                (semanticEnvironmentBindings
                    (declarationDeltaEnvironment delta))
        , logicalBuilderStructures = structures
        , logicalBuilderDeltas =
            delta : logicalBuilderDeltas builder
        , logicalBuilderNextDeclaration =
            logicalBuilderNextDeclaration builder + 1
        , logicalBuilderNextFact =
            declarationNextFact declaration
        , logicalBuilderNextInvocation =
            logicalBuilderNextInvocation builder + 1
        }

insertAuthorizedFact
    :: LogicalBuilder
    -> Map
        SemanticFactOccurrenceFingerprint
        (FactEntry BuilderFactAuthorization)
    -> PendingCandidate
    -> Map
        SemanticFactOccurrenceFingerprint
        (FactEntry BuilderFactAuthorization)
insertAuthorizedFact builder entries pending@(PendingCandidate
        candidate certificate _pendingAuthorization) =
    let occurrence = occurrenceFromPending pending
        fingerprint = semanticFactFingerprint occurrence
        authority = validationTarget certificate
        authorization =
            BuilderFactAuthorization
                (logicalBuilderIdentity builder)
                (reservedCandidateSlot candidate)
                authority
    in Map.insert
        fingerprint
        (FactEntry
            (candidateCheckedProposition candidate)
            occurrence
            authorization)
        entries

stableUniqueBy :: Ord key => (value -> key) -> [value] -> [value]
stableUniqueBy key =
    reverse . snd
        . foldl'
            (\(seen, values) value ->
                let identity = key value
                in if identity `Set.member` seen
                    then (seen, values)
                    else
                        ( Set.insert identity seen
                        , value : values
                        ))
            (Set.empty, [])


data DeclarationError
    = CandidateOutsideDeclaration !FactSlot
    | CandidateAlreadyAuthorized !FactSlot
    | CandidateOutsideAuthorizationFrontier
        !FactSlot !Natural !Natural
    | DeclarationHasUnauthorizedCandidates
    | DeclarationAuthorizationFrontierIncomplete
    | CandidatePropositionNotClosed
    | CandidatePropositionNotProposition !CoreType
    | StagedPremiseNotEarlier
        !FactSlot !Natural !FactSlot !Natural
    | StagedPremiseNotAuthorized !FactSlot
    | AuthorizedFactNotVisible
        !SemanticFactOccurrenceFingerprint
    | BuilderFactAuthorizationMismatch
    | PendingFactAuthorizationMismatch
    | PlanningFactContractMismatch !FactSlot
    | CheckedAuthorizationCandidateShapeMismatch !Int !Int
    | CheckedProofCandidateCountMismatch !Int
    | LocalClaimOutsideCandidate
    | FactSafetyFailed !FactSafetyError
    | ValidationCertificateFailed !ValidationCertificateError
    | DerivationImportFailed !DerivationImportError
    | KernelCompletionFailed !KernelReplayError
    | KernelConstructionDescriptorMismatch
    | DefinitionEquationObjectMissing !ObjectId
    | DefinitionEquationObjectNotTransparent !ObjectId
    | DefinitionEquationObjectNotPointwisePredicate !ObjectId
    | DefinitionEquationCandidateMismatch
    | DatatypeCompilationDescriptorMismatch
    | ProofObligationFailedAt !Location !DeclarationError
    | VampireProcessFailed !Provers.ProverProcessError
    | VampireObligationRejected !Provers.ProverAnswer
    | VampireProofHasNoAcceptedObligations
    | VampireCandidateBatchMismatch ![FactSlot] ![FactSlot]
    | VampireCandidateBatchProofShapeMismatch !FactSlot
    | VampireResolverBatchSizeMismatch !Int !Int
    | OmittedProofDidNotRecordUse
    | VampireRequestMismatch
    | VampireTargetMismatch
    | VampireLocalPremisesNotSupported
    | VampireGlobalTypeMismatch !ObjectId
    | VampirePremiseMismatch
        !SemanticFactOccurrenceFingerprint
    | VampirePremiseCapabilityMismatch
        !SemanticFactOccurrenceFingerprint
    | VampireFoundationMismatch !FoundationAxiomTag
    | CurrentCandidateVampirePreparationFailed
        !(VampireObligationPreparationError Void)
    | ProofValidationOutsideProofDeclaration
    | DeclarationValidationOutsideCompiledDeclaration
    | DeclarationValidationAlreadySelected
    | DeclarationValidationNotSelected
    | DeclarationShapeChangedAfterValidationLookup
    | CachedDeclarationCandidateMissing !FactSlot
    | ImportedModuleNotDirect !SemanticInterfaceId
    | ImportedFactMaterializationFailed
        !Materialization.MaterializationError
    | ImportedFactCollision
        !SemanticFactOccurrenceFingerprint
    | ImportedAliasCollision
        !SemanticName !ImportedAliasOrigin !ImportedAliasOrigin
    | ImportedAliasTargetMissing
        !SemanticFactOccurrenceFingerprint
    | ImportedGlobalCollision
        !SemanticGlobalKey !SemanticGlobalTarget !SemanticGlobalTarget
    | ImportedGlobalTargetInvalid
        !SemanticGlobalKey
        !SemanticGlobalTarget
        !SemanticGlobalTargetError
    | ImportedStructureCollision
        !SemanticStructurePhrase
        !SemanticStructureDescriptor
        !SemanticStructureDescriptor
    | SemanticStructureParentMissing
        !SemanticStructurePhrase !SemanticStructurePhrase
    | SemanticStructureOperationConflict
        !StructSymbol !SemanticStructurePhrase !SemanticStructurePhrase
    | SemanticStructurePredicateTargetInvalid
        !SemanticStructurePhrase !ObjectId !(Maybe CoreType) !CoreType
    | SemanticStructureOperationTargetInvalid
        !SemanticStructurePhrase !StructSymbol !ObjectId !(Maybe CoreType) !CoreType
    | ImportedEvidenceDirectMismatch
        ![SemanticInterfaceId] ![SemanticInterfaceId]
    | ImportedEvidenceInterfaceFailed !SemanticInterfaceError
    | ImportedEvidenceObjectMissing !ObjectId
    | ImportedEvidencePropositionMissing !PropositionId
    | ImportedModuleAfterAuthorization
    | DeclarationObjectAddedAfterAuthorization
    | DeclarationObjectValidationFailed !ObjectValidationError
    | DeclarationPropositionValidationFailed
        !PropositionValidationError
    | DeclarationInterfaceFailed !DeclarationInterfaceError
    | DeclarationEnvironmentFailed !SemanticEnvironmentError
    | DeclarationGlobalAlreadyStaged !SemanticGlobalKey
    | DeclarationStructureAlreadyStaged !SemanticStructurePhrase
    | DeclarationGlobalTargetInvalid
        !SemanticGlobalKey
        !SemanticGlobalTarget
        !SemanticGlobalTargetError
    | ProofDeclarationMustProduceOneFact
    | BuilderFactCollision
        !SemanticFactOccurrenceFingerprint
    | BuilderAliasCollision !SemanticName
    | BuilderObjectCollision !ObjectId
    | BuilderGlobalCollision !SemanticGlobalKey !SemanticGlobalTarget
    | BuilderStructureCollision !SemanticStructurePhrase
    deriving stock (Show, Eq)

declarationErrorLocation :: DeclarationError -> Maybe Location
declarationErrorLocation = \case
    ProofObligationFailedAt location _failure ->
        Just location
    _failure ->
        Nothing

renderDeclarationError :: DeclarationError -> Text
renderDeclarationError = \case
    CandidateOutsideDeclaration slot ->
        "candidate " <> shown slot <> " does not belong to this declaration"
    CandidateAlreadyAuthorized slot ->
        "candidate " <> shown slot <> " was authorized more than once"
    CandidateOutsideAuthorizationFrontier slot expected actual ->
        "candidate " <> shown slot <> " is outside authorization frontier "
            <> shown expected <> " (found " <> shown actual <> ")"
    DeclarationHasUnauthorizedCandidates ->
        "the declaration has unauthorized candidates"
    DeclarationAuthorizationFrontierIncomplete ->
        "the declaration authorization frontier is incomplete"
    CandidatePropositionNotClosed ->
        "the candidate proposition still has open local binders"
    CandidatePropositionNotProposition actual ->
        "the candidate has type " <> shown actual <> " instead of Prop"
    StagedPremiseNotEarlier candidate candidateOrdinal premise premiseOrdinal ->
        "candidate " <> shown candidate <> " at stage " <> shown candidateOrdinal
            <> " depends on non-earlier premise " <> shown premise
            <> " at stage " <> shown premiseOrdinal
    StagedPremiseNotAuthorized slot ->
        "staged premise " <> shown slot <> " is not authorized"
    AuthorizedFactNotVisible fingerprint ->
        "authorized fact " <> shown fingerprint <> " is not visible"
    BuilderFactAuthorizationMismatch ->
        "builder fact authority does not match the checked declaration"
    PendingFactAuthorizationMismatch ->
        "pending fact authority does not match the checked declaration"
    PlanningFactContractMismatch slot ->
        "checked declaration-stage fact " <> shown slot
            <> " has inconsistent semantic provenance"
    CheckedAuthorizationCandidateShapeMismatch expected actual ->
        "checked declaration recipe expected " <> shown expected
            <> " candidate stages but received " <> shown actual
    CheckedProofCandidateCountMismatch actual ->
        "checked proof declaration requires exactly one candidate but received "
            <> shown actual
    LocalClaimOutsideCandidate ->
        "proof-local claim was used outside a candidate proof"
    FactSafetyFailed{} ->
        "fact-safety validation failed"
    ValidationCertificateFailed{} ->
        "validation-certificate checking failed"
    DerivationImportFailed{} ->
        "kernel derivation import failed"
    KernelCompletionFailed{} ->
        "kernel replay failed"
    KernelConstructionDescriptorMismatch ->
        "kernel construction does not match its checked descriptor"
    DefinitionEquationObjectMissing identity ->
        "definition equation references missing object " <> shown identity
    DefinitionEquationObjectNotTransparent identity ->
        "definition equation references non-transparent object " <> shown identity
    DefinitionEquationObjectNotPointwisePredicate identity ->
        "definition equation object " <> shown identity
            <> " is not a unary predicate definition"
    DefinitionEquationCandidateMismatch ->
        "definition equation does not match its checked object content"
    DatatypeCompilationDescriptorMismatch ->
        "datatype compilation does not match its complete checked family"
    ProofObligationFailedAt location failure ->
        locationToText location <> ": " <> renderDeclarationError failure
    VampireProcessFailed{} ->
        "Vampire process failed while authorizing the declaration"
    VampireObligationRejected{} ->
        "Vampire did not accept a declaration obligation"
    VampireProofHasNoAcceptedObligations ->
        "Vampire proof contains no accepted obligations"
    VampireCandidateBatchMismatch expected actual ->
        "Vampire candidate batch does not match the complete authorization "
            <> "stage (expected " <> shown expected
            <> ", found " <> shown actual <> ")"
    VampireCandidateBatchProofShapeMismatch slot ->
        "Vampire candidate " <> shown slot
            <> " performed execution before its ready batch"
    VampireResolverBatchSizeMismatch expected actual ->
        "Vampire resolver returned " <> shown actual
            <> " results for " <> shown expected <> " requests"
    OmittedProofDidNotRecordUse ->
        "omitted proof completion did not record an omission"
    VampireRequestMismatch ->
        "accepted Vampire run does not match the prepared request"
    VampireTargetMismatch ->
        "Vampire request target does not match the candidate theorem"
    VampireLocalPremisesNotSupported ->
        "typed Vampire requests do not yet support local premises"
    VampireGlobalTypeMismatch object ->
        "Vampire request has the wrong type for global object " <> shown object
    VampirePremiseMismatch fingerprint ->
        "Vampire request premise does not match visible fact " <> shown fingerprint
    VampirePremiseCapabilityMismatch fingerprint ->
        "Vampire request lacks authority for premise " <> shown fingerprint
    VampireFoundationMismatch tag ->
        "Vampire request has inconsistent foundation axiom " <> shown tag
    CurrentCandidateVampirePreparationFailed failure ->
        "the staged Vampire obligation could not be prepared: " <> shown failure
    ProofValidationOutsideProofDeclaration ->
        "proof validation requires a proof declaration"
    DeclarationValidationOutsideCompiledDeclaration ->
        "declaration validation requires a compiled declaration"
    DeclarationValidationAlreadySelected ->
        "compiled declaration validation was selected more than once"
    DeclarationValidationNotSelected ->
        "compiled declaration validation was not selected"
    DeclarationShapeChangedAfterValidationLookup ->
        "compiled declaration shape changed after validation lookup"
    CachedDeclarationCandidateMissing slot ->
        "cached declaration validation has no candidate for " <> shown slot
    ImportedModuleNotDirect interface ->
        "sealed semantic interface is not a direct import: " <> shown interface
    ImportedFactMaterializationFailed{} ->
        "imported fact failed materialization checks"
    ImportedFactCollision fingerprint ->
        "imported fact " <> shown fingerprint <> " is already registered"
    ImportedAliasCollision alias earlier later ->
        "imported semantic alias " <> shown alias
            <> " conflicts between " <> shown earlier
            <> " and " <> shown later
    ImportedAliasTargetMissing fingerprint ->
        "imported alias targets missing fact " <> shown fingerprint
    ImportedGlobalCollision key earlier later ->
        "imported global " <> shown key
            <> " has conflicting targets " <> shown earlier
            <> " and " <> shown later
    ImportedGlobalTargetInvalid key target _failure ->
        "imported global " <> shown key
            <> " has invalid target " <> shown target
    ImportedEvidenceDirectMismatch expected actual ->
        "imported semantic parents differ: expected " <> shown expected
            <> ", found " <> shown actual
    ImportedStructureCollision structurePhrase _existing _incoming ->
        "structure " <> shown structurePhrase <> " has conflicting descriptors"
    SemanticStructureParentMissing structurePhrase parent ->
        "structure " <> shown structurePhrase <> " has unknown parent " <> shown parent
    SemanticStructureOperationConflict symbol firstOrigin secondOrigin ->
        "structure operation " <> shown symbol <> " conflicts between "
            <> shown firstOrigin <> " and " <> shown secondOrigin
    SemanticStructurePredicateTargetInvalid structurePhrase object _actual expected ->
        "structure " <> shown structurePhrase <> " has invalid predicate object "
            <> shown object <> " (expected " <> shown expected <> ")"
    SemanticStructureOperationTargetInvalid structurePhrase symbol object _actual expected ->
        "structure " <> shown structurePhrase <> " has invalid operation "
            <> shown symbol <> " object " <> shown object
            <> " (expected " <> shown expected <> ")"
    ImportedEvidenceInterfaceFailed{} ->
        "imported semantic interface failed validation"
    ImportedEvidenceObjectMissing identity ->
        "imported semantic interface is missing object " <> shown identity
    ImportedEvidencePropositionMissing identity ->
        "imported semantic interface is missing proposition " <> shown identity
    ImportedModuleAfterAuthorization ->
        "a sealed module was imported after candidate authorization"
    DeclarationObjectAddedAfterAuthorization ->
        "the declaration added an object after candidate authorization"
    DeclarationObjectValidationFailed{} ->
        "declaration object validation failed"
    DeclarationPropositionValidationFailed{} ->
        "declaration proposition validation failed"
    DeclarationInterfaceFailed{} ->
        "declaration interface validation failed"
    DeclarationEnvironmentFailed{} ->
        "declaration environment delta is inconsistent"
    DeclarationGlobalAlreadyStaged key ->
        "global " <> shown key <> " was staged more than once"
    DeclarationStructureAlreadyStaged structurePhrase ->
        "structure " <> shown structurePhrase <> " was staged more than once"
    DeclarationGlobalTargetInvalid key target _failure ->
        "global " <> shown key <> " has invalid target " <> shown target
    ProofDeclarationMustProduceOneFact ->
        "a proof declaration must produce exactly one fact"
    BuilderFactCollision fingerprint ->
        "fact " <> shown fingerprint <> " is already registered"
    BuilderAliasCollision alias ->
        "semantic alias " <> shown alias <> " is already registered"
    BuilderObjectCollision object ->
        "object " <> shown object <> " is already registered"
    BuilderGlobalCollision key object ->
        "global " <> shown key <> " is already bound to " <> shown object
    BuilderStructureCollision structurePhrase ->
        "structure " <> shown structurePhrase <> " is already registered"
  where
    shown :: Show value => value -> Text
    shown = Text.pack . show