summaryrefslogtreecommitdiff
path: root/source/Test/Unit/Declaration.hs
blob: 0823606c938a4d602cdfde1e3bf3ca8acfca061c (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
{-# LANGUAGE NoImplicitPrelude #-}

module Test.Unit.Declaration (unitTests) where

import Base
import Checking.Authority qualified as Authority
import Checking.Backend.Problem qualified as Backend
import Checking.Core qualified as Core
import Checking.Declaration qualified as Declaration
import Checking.Foundation qualified as Foundation
import Checking.Exact qualified as Exact
import Checking.Identity qualified as Identity
import Checking.Kernel.Derivation qualified as Kernel
import Checking.Semantic qualified as Semantic
import Checking.Typed.Inductive qualified as Typed
import Felix.Math.Codec
import Felix.Module
import Felix.Source
import Felix.Store qualified as Store
import Provers qualified
import Report.Location
import Syntax.Abstract qualified as Raw
import Syntax.Interface qualified as Syntax
import Syntax.Internal qualified as Internal
import Syntax.Lexicon qualified as Lexicon

import Data.List.NonEmpty qualified as NonEmpty
import Data.IORef qualified as IORef
import Data.Set qualified as Set
import Data.Text qualified as Text
import Data.Text.Encoding qualified as TextEncoding
import Data.Vector qualified as Vector
import Numeric.Natural (Natural)
import Control.Exception (bracket)
import Control.Exception qualified as Exception
import Control.Monad.Logger (runNoLoggingT)
import System.Directory qualified as Directory
import System.FilePath.Posix qualified as Posix
import Test.Tasty
import Test.Tasty.HUnit


unitTests :: TestTree
unitTests =
    testGroup "Typed declaration seam"
        [ testCase "enforces staged candidate order"
            enforcesStagedCandidateOrder
        , testCase "retains only appended declaration prefixes"
            retainsOnlyAppendedPrefixes
        , testCase "makes declaration failures terminal"
            makesDeclarationFailuresTerminal
        , testCase "propagates unsafe authority through local claims"
            propagatesUnsafeAuthorityThroughLocalClaims
        , testCase "aggregates exact Vampire obligations"
            aggregatesExactVampireObligations
        , testCase "validates complete resolver batches before rejection"
            validatesCompleteResolverBatchesBeforeRejection
        , testCase "rejects retained-plan admission drift fatally"
            rejectsRetainedPlanAdmissionDrift
        , testCase "preserves source-axiom safety through Vampire validation"
            preservesSourceAxiomSafetyThroughVampireValidation
        , testCase "materializes a sealed import with fresh authority"
            materializesSealedImport
        , testCase "reconstructs exact imported global bindings"
            reconstructsImportedGlobalBindings
        , testCase "elaborates scoped exact propositions"
            elaboratesScopedExactPropositions
        , testCase "lowers fixed equality aliases without global support"
            lowersFixedEqualityAliases
        , testCase "prepares exact claim envelopes"
            preparesExactClaimEnvelopes
        , testCase "lowers exact separation comprehensions"
            lowersExactSeparationComprehensions
        , testCase "lowers exact replacement telescopes"
            lowersExactReplacementTelescopes
        , testCase "lowers exact finite sets"
            lowersExactFiniteSets
        , testCase "lowers exact ordinary declarations"
            lowersExactOrdinaryDeclarations
        , testCase "folds transitive and diamond import evidence"
            foldsTransitiveAndDiamondEvidence
        , testCase "validates exact kernel construction descriptors"
            validatesExactKernelConstructionDescriptors
        , testCase "authorizes exact datatype compilation families"
            authorizesExactDatatypeCompilationFamilies
        , testCase "reuses exact compiled declaration validation"
            reusesExactCompiledDeclarationValidation
        , testCase "keeps fatal validation lookup failures out of declarations"
            keepsFatalValidationLookupFailuresOutOfDeclarations
        ]

data FatalValidationLookup = FatalValidationLookup
    deriving (Show)

instance Exception.Exception FatalValidationLookup

keepsFatalValidationLookupFailuresOutOfDeclarations :: Assertion
keepsFatalValidationLookupFailuresOutOfDeclarations = do
    fixture <- makeFixture
    prepared <- makePreparedObligation
        fixture
        Foundation.EmptyCharacteristic
    let lookup = proofOnlyValidationLookup
            (const (Exception.throwIO FatalValidationLookup))
        action = Declaration.commitProofDeclaration
            (Semantic.proofSyntaxId "fatal-validation-lookup") do
                candidate <- Declaration.reserveCandidate
                    (factSpec fixture "fatal-validation-lookup")
                Declaration.authorizeVampireCandidate candidate
                    (Declaration.acceptVampireObligation prepared)
    result <- Exception.try
        (runDriverWithValidation fixture lookup action)
        :: IO
            (Either
                FatalValidationLookup
                (Declaration.DriverResult
                    Void
                    ((), Declaration.CommittedDeclarationBatch)))
    case result of
        Left FatalValidationLookup -> pure ()
        Right _ ->
            assertFailure "fatal validation lookup became a driver result"

enforcesStagedCandidateOrder :: Assertion
enforcesStagedCandidateOrder = do
    fixture <- makeFixture
    accepted <- runSuccessful fixture do
        result <- Declaration.commitCompiledDeclaration
            (Semantic.declarationSyntaxId "staged-success") do
                first <- Declaration.reserveCandidate
                    (factSpec fixture "first")
                later <- Declaration.reserveCandidateBatch
                    ( factSpec fixture "later-a"
                    :| [factSpec fixture "later-b"]
                    )
                Declaration.authorizeCompiledDeclaration do
                    Declaration.authorizeSourceAxiomCandidate first
                    traverse_
                        (\candidate ->
                            Declaration.authorizeKernelProofCandidate
                                candidate do
                                    premise <-
                                        Declaration.useStagedCandidate first
                                    pure
                                        (Kernel.importedFactDerivation premise))
                        later
        pure result
    let (_value, batch) = accepted
    assertEqual
        "all source-ordered candidates appended"
        3
        (length
            (Semantic.declarationDeltaFacts
                (Declaration.committedBatchDelta batch)))

    provenance <- runDriver fixture (priorDeclarationUse fixture)
    case provenance of
        Declaration.DriverFailed
                (Declaration.DriverDeclarationFailed
                    (Declaration.CandidateOutsideDeclaration slot))
                prefix -> do
            assertEqual
                "cross-declaration staged premise"
                (localFact fixture 0)
                slot
            assertSingleCompletedPrefix prefix
        _other ->
            assertFailure
                "cross-declaration staged provenance was not rejected"

    traverse_
        (\(label, action, expectedPremise, expectedCandidate) -> do
            result <- runDriver fixture action
            case result of
                Declaration.DriverFailed
                    (Declaration.DriverDeclarationFailed
                    (Declaration.StagedPremiseNotEarlier
                        premiseSlot premiseStage
                        candidateSlot candidateStage))
                    _prefix -> do
                    assertEqual (label <> " premise slot")
                        expectedPremise premiseSlot
                    assertEqual (label <> " candidate slot")
                        expectedCandidate candidateSlot
                    assertBool (label <> " rejected non-earlier stage")
                        (premiseStage >= candidateStage)
                Declaration.DriverFailed
                    (Declaration.DriverDeclarationFailed other)
                    _prefix ->
                    assertFailure
                        (label <> ": unexpected error " <> show other)
                Declaration.DriverFailed
                    (Declaration.DriverActionFailed _failure)
                    _prefix ->
                    assertFailure
                        (label <> ": unexpected ordinary driver failure")
                Declaration.DriverSucceeded{} ->
                    assertFailure (label <> ": invalid staged use succeeded")
                Declaration.DriverSealFailed{} ->
                    assertFailure (label <> ": invalid staged use reached sealing"))
        [ ( "self"
          , selfUse fixture
          , localFact fixture 0
          , localFact fixture 0
          )
        , ( "same stage"
          , sameStageUse fixture
          , localFact fixture 1
          , localFact fixture 0
          )
        , ( "forward"
          , forwardUse fixture
          , localFact fixture 1
          , localFact fixture 0
          )
        ]
  where
    localFact fixture ordinal =
        Semantic.factSlot
            (fixtureOwner fixture)
            (localFactOrdinal ordinal)

    selfUse fixture =
        Declaration.commitCompiledDeclaration
            (Semantic.declarationSyntaxId "self") do
                candidate <- Declaration.reserveCandidate
                    (factSpec fixture "self")
                Declaration.authorizeCompiledDeclaration
                    (Declaration.authorizeKernelProofCandidate candidate do
                        premise <- Declaration.useStagedCandidate candidate
                        pure (Kernel.importedFactDerivation premise))

    sameStageUse fixture =
        Declaration.commitCompiledDeclaration
            (Semantic.declarationSyntaxId "same-stage") do
                candidates <- Declaration.reserveCandidateBatch
                    ( factSpec fixture "same-a"
                    :| [factSpec fixture "same-b"]
                    )
                let first = NonEmpty.head candidates
                    second = NonEmpty.last candidates
                Declaration.authorizeCompiledDeclaration
                    (Declaration.authorizeKernelProofCandidate first do
                        premise <- Declaration.useStagedCandidate second
                        pure (Kernel.importedFactDerivation premise))

    forwardUse fixture =
        Declaration.commitCompiledDeclaration
            (Semantic.declarationSyntaxId "forward") do
                first <- Declaration.reserveCandidate
                    (factSpec fixture "forward-a")
                second <- Declaration.reserveCandidate
                    (factSpec fixture "forward-b")
                Declaration.authorizeCompiledDeclaration
                    (Declaration.authorizeKernelProofCandidate first do
                        premise <- Declaration.useStagedCandidate second
                        pure (Kernel.importedFactDerivation premise))

    priorDeclarationUse fixture = do
        (premise, _batch) <- Declaration.commitCompiledDeclaration
            (Semantic.declarationSyntaxId "prior-stage") do
                candidate <- Declaration.reserveCandidate
                    (factSpec fixture "prior-stage")
                Declaration.authorizeCompiledDeclaration
                    (Declaration.authorizeSourceAxiomCandidate candidate)
                pure candidate
        void
            (Declaration.commitCompiledDeclaration
                (Semantic.declarationSyntaxId "later-stage") do
                    candidate <- Declaration.reserveCandidate
                        (factSpec fixture "later-stage")
                    Declaration.authorizeCompiledDeclaration
                        (Declaration.authorizeKernelProofCandidate candidate do
                            imported <-
                                Declaration.useStagedCandidate premise
                            pure (Kernel.importedFactDerivation imported)))

retainsOnlyAppendedPrefixes :: Assertion
retainsOnlyAppendedPrefixes = do
    fixture <- makeFixture
    outcome <- runDriver fixture do
        (_value, _firstBatch) <- Declaration.commitProofDeclaration
            (Semantic.proofSyntaxId "accepted") do
                candidate <- Declaration.reserveCandidate
                    (factSpec fixture "accepted")
                Declaration.authorizeSourceAxiomCandidate candidate
        Declaration.failModuleDriver
            ("later checker failure" :: Text)
    case outcome of
        Declaration.DriverFailed
                (Declaration.DriverActionFailed reason) prefix -> do
            assertEqual
                "driver reports the later ordinary failure"
                "later checker failure"
                reason
            assertSingleCompletedPrefix prefix
        Declaration.DriverFailed
                (Declaration.DriverDeclarationFailed err) _prefix ->
            assertFailure
                ("unexpected declaration failure: " <> show err)
        Declaration.DriverSucceeded{} ->
            assertFailure "ordinary driver failure was lost"
        Declaration.DriverSealFailed{} ->
            assertFailure "ordinary driver failure became a seal failure"

makesDeclarationFailuresTerminal :: Assertion
makesDeclarationFailuresTerminal = do
    fixture <- makeFixture
    outcome <- runDriver fixture do
        void
            (Declaration.commitProofDeclaration
                (Semantic.proofSyntaxId "accepted-before-failure") do
                    candidate <- Declaration.reserveCandidate
                        (factSpec fixture "accepted-before-failure")
                    Declaration.authorizeSourceAxiomCandidate candidate)
        void
            (Declaration.commitCompiledDeclaration
                (Semantic.declarationSyntaxId "rolled-back") do
                    void
                        (Declaration.reserveCandidate
                            (factSpec fixture "uncommitted")))
        -- This declaration must be unreachable after the terminal failure.
        void
            (Declaration.commitProofDeclaration
                (Semantic.proofSyntaxId "must-not-publish") do
                    candidate <- Declaration.reserveCandidate
                        (factSpec fixture "must-not-publish")
                    Declaration.authorizeSourceAxiomCandidate candidate)
    case outcome of
        Declaration.DriverFailed
                (Declaration.DriverDeclarationFailed
                    Declaration.DeclarationHasUnauthorizedCandidates)
                prefix ->
            assertSingleCompletedPrefix prefix
        Declaration.DriverFailed
                (Declaration.DriverDeclarationFailed other) _prefix ->
            assertFailure
                ("unexpected declaration failure: " <> show other)
        Declaration.DriverFailed
                (Declaration.DriverActionFailed _failure) _prefix ->
            assertFailure "unexpected ordinary driver failure"
        Declaration.DriverSucceeded{} ->
            assertFailure "failed declaration was skipped"
        Declaration.DriverSealFailed{} ->
            assertFailure "failed declaration reached sealing"

assertSingleCompletedPrefix
    :: Declaration.PendingModulePrefix
    -> Assertion
assertSingleCompletedPrefix prefix = do
    let batches =
            Declaration.pendingModulePrefixBatches prefix
    assertEqual "one completed envelope survives" 1 (length batches)
    case batches of
        [batch] -> do
            let expected =
                    Declaration.committedBatchNextPrefix batch
            assertEqual
                "failed declaration did not advance the prefix"
                expected
                (Declaration.pendingModulePrefixCurrent prefix)
            assertEqual
                "retained envelope ends at the exposed prefix"
                expected
                (Declaration.committedBatchNextPrefix batch)
        _ -> pure ()

propagatesUnsafeAuthorityThroughLocalClaims :: Assertion
propagatesUnsafeAuthorityThroughLocalClaims = do
    fixture <- makeFixture
    result <- runSuccessful fixture do
        (_sourceValue, sourceBatch) <- Declaration.commitProofDeclaration
            (Semantic.proofSyntaxId "source-axiom") do
                candidate <- Declaration.reserveCandidate
                    (factSpec fixture "source")
                Declaration.authorizeSourceAxiomCandidate candidate
        sourceOccurrence <- requireSingleOccurrence sourceBatch
        let
            sourceFingerprint =
                Semantic.semanticFactFingerprint sourceOccurrence
        (_derivedValue, derivedBatch) <- Declaration.commitProofDeclaration
            (Semantic.proofSyntaxId "local-claim") do
                candidate <- Declaration.reserveCandidate
                    (factSpec fixture "derived")
                Declaration.authorizeKernelProofCandidate candidate do
                    sourcePremise <-
                        Declaration.useAuthorizedFact sourceFingerprint
                    claim <- Declaration.proveLocalKernelClaim
                        (fixtureProposition fixture)
                        (Kernel.importedFactDerivation sourcePremise)
                    claimPremise <- Declaration.useLocalClaim claim
                    pure (Kernel.importedFactDerivation claimPremise)
        pure derivedBatch
    occurrence <-
        case Semantic.declarationDeltaFacts
                (Declaration.committedBatchDelta result) of
            [single] -> pure single
            facts ->
                assertFailure
                    ("unexpected fact count: " <> show (length facts))
                    >> fail "unreachable"
    let authority = Semantic.semanticFactAuthority occurrence
    assertEqual
        "local claim cannot erase source-axiom safety"
        (Authority.authoritySafety
            (Authority.singletonEscapeKind Authority.SourceAxiom))
        (Authority.factAuthoritySafety authority)
    case Declaration.committedBatchProofValidations result of
        [record] ->
            assertEqual
                "local support is absent from the compact direct authorization"
                (Authority.CheckedSourceProof [])
                (Authority.validationDirectAuthorization
                    (Semantic.proofValidationRecordCertificate record))
        records ->
            assertFailure
                ("unexpected proof validation count: "
                    <> show (length records))

aggregatesExactVampireObligations :: Assertion
aggregatesExactVampireObligations =
    withTemporaryDirectory "felix-declaration-vampire" \root -> do
        fixture <- makeFixture
        let executable = root Posix.</> "vampire"
        writeAcceptedVampire executable
        first <- makePreparedObligation
            fixture
            Foundation.EmptyCharacteristic
        second <- makePreparedObligation
            fixture
            Foundation.PairSetCharacteristic
        let exactResolver = acceptedResolver executable
        freshOutcome <-
            (runDriverWithResolver fixture exactResolver do
                (_value, committed) <- Declaration.commitProofDeclaration
                    (Semantic.proofSyntaxId "two-vampire-obligations") do
                        candidate <- Declaration.reserveCandidate
                            (factSpec fixture "two-vampire-obligations")
                        Declaration.authorizeVampireCandidate candidate do
                            Declaration.acceptVampireObligation first
                            Declaration.acceptVampireObligation second
                pure committed
                :: IO
                    (Declaration.DriverResult Text
                        Declaration.CommittedDeclarationBatch))
        (batch, freshPrefix) <-
            case freshOutcome of
                Declaration.DriverSucceeded value _ prefix _closure ->
                    pure (value, prefix)
                Declaration.DriverFailed failure _ ->
                    assertFailure
                        ("fresh Vampire fixture failed: " <> show failure)
                        >> fail "unreachable"
                Declaration.DriverSealFailed failure _ ->
                    assertFailure
                        ("fresh Vampire fixture did not seal: "
                            <> show failure)
                        >> fail "unreachable"
        let expectedRequests =
                Provers.preparedVerificationRequestId
                    (Provers.preparedTypedProverRequest first)
                : [Provers.preparedVerificationRequestId
                    (Provers.preparedTypedProverRequest second)]
        case Declaration.committedBatchProofValidations batch of
            [record] ->
                assertEqual
                    "accepted requests retain source order"
                    (Authority.CheckedSourceProof expectedRequests)
                    (Authority.validationDirectAuthorization
                        (Semantic.proofValidationRecordCertificate record))
            records ->
                assertFailure
                    ("unexpected proof validation count: "
                        <> show (length records))

        cachedRecord <-
            case Declaration.committedBatchProofValidations batch of
                [record] -> pure record
                records ->
                    assertFailure
                        ("unexpected cached proof records: "
                            <> show (length records))
                    >> fail "unreachable"
        cachedLookupKey <- IORef.newIORef Nothing
        cached <- runSuccessfulWithValidation fixture
            (proofOnlyValidationLookup
                (\key -> do
                    IORef.writeIORef cachedLookupKey (Just key)
                    pure (Just cachedRecord))) do
            (_value, committed) <- Declaration.commitProofDeclaration
                (Semantic.proofSyntaxId "two-vampire-obligations") do
                    candidate <- Declaration.reserveCandidate
                        (factSpec fixture "two-vampire-obligations")
                    Declaration.authorizeVampireCandidate candidate do
                        Declaration.acceptVampireObligation first
                        Declaration.acceptVampireObligation second
            pure committed
        publishedRecord <-
            case Declaration.committedBatchProofValidations cached of
                [record] -> pure record
                records ->
                    assertFailure
                        ("unexpected cached validation records: "
                            <> show (length records))
                        >> fail "unreachable"
        assertEqual
            "cached authorization preserves the exact direct proof"
            (Authority.CheckedSourceProof expectedRequests)
            (Authority.validationDirectAuthorization
                (Semantic.proofValidationRecordCertificate publishedRecord))
        assertEqual
            "lookup and publication retain the same validation key"
            (Semantic.proofValidationRecordKey cachedRecord)
            (Semantic.proofValidationRecordKey publishedRecord)
        assertEqual
            "one proof syntax key governs lookup and publication"
            (Just
                (Semantic.proofValidationRecordKey cachedRecord))
            =<< IORef.readIORef cachedLookupKey

        missLookups <- IORef.newIORef (0 :: Int)
        missRuns <- IORef.newIORef (0 :: Int)
        let missLookup = proofOnlyValidationLookup \_key -> do
                IORef.modifyIORef' missLookups (+ 1)
                pure Nothing
            missResolver = Declaration.vampireResolver \prepared -> do
                IORef.modifyIORef' missRuns (+ 1)
                resolveAccepted executable prepared
        miss <- runDriverWithValidationAndResolver
            fixture
            missLookup
            missResolver
            do
                (_value, committed) <- Declaration.commitProofDeclaration
                    (Semantic.proofSyntaxId "two-vampire-obligations") do
                        candidate <- Declaration.reserveCandidate
                            (factSpec fixture "two-vampire-obligations")
                        Declaration.authorizeVampireCandidate candidate do
                            Declaration.acceptVampireObligation first
                            Declaration.acceptVampireObligation second
                pure committed
        case miss of
            Declaration.DriverSucceeded{} -> pure ()
            _ ->
                assertFailure "warm miss failed"
        assertEqual "warm miss performs one exact lookup"
            1
            =<< IORef.readIORef missLookups
        assertEqual "warm miss runs every reached Vampire request"
            2
            =<< IORef.readIORef missRuns

        mismatchRuns <- IORef.newIORef (0 :: Int)
        let editedSyntax =
                Semantic.proofSyntaxId "edited-proof-syntax"
            cachedCertificate =
                Semantic.proofValidationRecordCertificate cachedRecord
            corruptedKey =
                Semantic.proofValidationKey
                    (Identity.theoremId
                        (Authority.factAuthorityTheorem
                            (Authority.validationTarget
                                cachedCertificate)))
                    editedSyntax
                    (Declaration.committedBatchPreviousPrefix batch)
            corruptedRecord =
                Semantic.proofValidationRecord
                    corruptedKey
                    cachedCertificate
            mismatchResolver = Declaration.vampireResolver \prepared -> do
                IORef.modifyIORef' mismatchRuns (+ 1)
                resolveAccepted executable prepared
            mismatchingLookup = proofOnlyValidationLookup
                (const (pure (Just corruptedRecord)))
        mismatching <- Exception.try
            (runDriverWithValidationAndResolver
                fixture
                mismatchingLookup
                mismatchResolver
                do
                    Declaration.commitProofDeclaration editedSyntax do
                        candidate <- Declaration.reserveCandidate
                            (factSpec fixture "two-vampire-obligations")
                        Declaration.authorizeVampireCandidate candidate
                            (Declaration.acceptVampireObligation first))
            :: IO
                (Either
                    Declaration.ValidationIntegrityError
                    (Declaration.DriverResult
                        Text
                        ((), Declaration.CommittedDeclarationBatch)))
        case mismatching of
            Left Declaration.CachedValidationIntegrityError{} ->
                pure ()
            Right _ ->
                assertFailure "mismatching hit did not abort as corruption"
        assertEqual "mismatching hit does not fall back to Vampire"
            0
            =<< IORef.readIORef mismatchRuns

        withOpenedStore fixture root \store -> do
            expectRightIO
                (Store.writePendingModulePrefix store freshPrefix)
            warmCalls <- IORef.newIORef (0 :: Int)
            let storeLookup = proofOnlyValidationLookup \key -> do
                    IORef.modifyIORef' warmCalls (+ 1)
                    Store.loadProofValidation store key >>= expectRight
            warm <- runSuccessfulWithValidation fixture
                storeLookup
                do
                    (_value, committed) <- Declaration.commitProofDeclaration
                        (Semantic.proofSyntaxId "two-vampire-obligations") do
                            candidate <- Declaration.reserveCandidate
                                (factSpec fixture "two-vampire-obligations")
                            Declaration.authorizeVampireCandidate candidate do
                                Declaration.acceptVampireObligation first
                                Declaration.acceptVampireObligation second
                    pure committed
            assertEqual "warm lookup executes once through the store"
                1
                =<< IORef.readIORef warmCalls
            assertEqual "warm path retains cached request IDs"
                (Authority.CheckedSourceProof expectedRequests)
                (case Declaration.committedBatchProofValidations warm of
                    [record] ->
                        Authority.validationDirectAuthorization
                            (Semantic.proofValidationRecordCertificate record)
                    records ->
                        error
                            ("unexpected warm validation records: "
                                <> show (length records)))

        emptyProof <- runDriver fixture do
            Declaration.commitProofDeclaration
                (Semantic.proofSyntaxId "empty-vampire-proof") do
                    candidate <- Declaration.reserveCandidate
                        (factSpec fixture "empty-vampire-proof")
                    Declaration.authorizeVampireCandidate candidate
                        (pure ())
        case emptyProof of
            Declaration.DriverFailed
                    (Declaration.DriverDeclarationFailed
                        Declaration.VampireProofHasNoAcceptedObligations)
                    prefix ->
                assertEqual
                    "empty Vampire proof publishes no declaration"
                    0
                    (length
                        (Declaration.pendingModulePrefixBatches prefix))
            Declaration.DriverFailed
                    (Declaration.DriverDeclarationFailed other) _prefix ->
                assertFailure
                    ("unexpected empty-proof failure: " <> show other)
            Declaration.DriverFailed
                    (Declaration.DriverActionFailed _failure) _prefix ->
                assertFailure "unexpected ordinary driver failure"
            Declaration.DriverSucceeded{} ->
                assertFailure "empty Vampire proof was authorized"
            Declaration.DriverSealFailed{} ->
                assertFailure "empty Vampire proof reached sealing"

        invalidClosure <- expectRight
            (Identity.validateObjectClosure
                (Identity.theoryId (fixtureFoundation fixture))
                [])
        invalidTarget <- expectRight
            (Identity.validatePropositionContent
                invalidClosure
                (Core.CImp Core.CFalsum Core.CFalsum))
        invalidCalls <- IORef.newIORef (0 :: Int)
        let invalidResolver =
                Declaration.vampireResolver \prepared -> do
                    IORef.modifyIORef' invalidCalls (+ 1)
                    resolveAccepted executable prepared
        invalid <- runDriverWithResolver fixture invalidResolver do
            Declaration.commitProofDeclaration
                (Semantic.proofSyntaxId "invalid-vampire-target") do
                    candidate <- Declaration.reserveCandidate
                        (Declaration.candidateSpec
                            invalidTarget
                            Semantic.SearchEligible
                            [Semantic.semanticName
                                "invalid-vampire-target"])
                    Declaration.authorizeVampireCandidate candidate
                        (Declaration.acceptVampireObligation first)
        assertEqual
            "invalid prepared problem does not invoke Vampire"
            0
            =<< IORef.readIORef invalidCalls
        case invalid of
            Declaration.DriverFailed
                    (Declaration.DriverDeclarationFailed
                        Declaration.VampireTargetMismatch)
                    prefix ->
                assertEqual
                    "invalid prepared problem publishes no declaration"
                    0
                    (length
                        (Declaration.pendingModulePrefixBatches prefix))
            Declaration.DriverFailed
                    (Declaration.DriverDeclarationFailed other) _prefix ->
                assertFailure
                    ("unexpected prepared-problem failure: " <> show other)
            Declaration.DriverFailed
                    (Declaration.DriverActionFailed _failure) _prefix ->
                assertFailure "unexpected ordinary driver failure"
            Declaration.DriverSucceeded{} ->
                assertFailure "invalid prepared problem was authorized"
            Declaration.DriverSealFailed{} ->
                assertFailure "invalid prepared problem reached sealing"

        let mismatchedResolver =
                Declaration.vampireResolver \_prepared ->
                    resolveAccepted executable second
        mismatch <- runDriverWithResolver fixture mismatchedResolver do
            Declaration.commitProofDeclaration
                (Semantic.proofSyntaxId "mismatched-vampire-request") do
                    candidate <- Declaration.reserveCandidate
                        (factSpec fixture "mismatched-vampire-request")
                    Declaration.authorizeVampireCandidate candidate
                        (Declaration.acceptVampireObligation first)
        case mismatch of
            Declaration.DriverFailed
                    (Declaration.DriverDeclarationFailed
                        Declaration.VampireRequestMismatch)
                    prefix ->
                assertEqual
                    "mismatch publishes no declaration"
                    0
                    (length
                        (Declaration.pendingModulePrefixBatches prefix))
            Declaration.DriverFailed
                    (Declaration.DriverDeclarationFailed other) _prefix ->
                assertFailure
                    ("unexpected mismatch failure: " <> show other)
            Declaration.DriverFailed
                    (Declaration.DriverActionFailed _failure) _prefix ->
                assertFailure "unexpected ordinary driver failure"
            Declaration.DriverSucceeded{} ->
                assertFailure "mismatched request was authorized"
            Declaration.DriverSealFailed{} ->
                assertFailure "mismatched request reached sealing"

        unrecorded <- runDriver fixture do
            Declaration.commitProofDeclaration
                (Semantic.proofSyntaxId "unrecorded-omission") do
                    candidate <- Declaration.reserveCandidate
                        (factSpec fixture "unrecorded-omission")
                    Declaration.authorizeOmittedCandidate candidate
                        (pure ())
        case unrecorded of
            Declaration.DriverFailed
                    (Declaration.DriverDeclarationFailed
                        Declaration.OmittedProofDidNotRecordUse)
                    prefix ->
                assertEqual
                    "unrecorded omission publishes no declaration"
                    0
                    (length
                        (Declaration.pendingModulePrefixBatches prefix))
            Declaration.DriverFailed
                    (Declaration.DriverDeclarationFailed other) _prefix ->
                assertFailure
                    ("unexpected unrecorded-omission failure: "
                        <> show other)
            Declaration.DriverFailed
                    (Declaration.DriverActionFailed _failure) _prefix ->
                assertFailure "unexpected ordinary driver failure"
            Declaration.DriverSucceeded{} ->
                assertFailure "unrecorded omission was authorized"
            Declaration.DriverSealFailed{} ->
                assertFailure "unrecorded omission reached sealing"

        calls <- IORef.newIORef (0 :: Int)
        let countingResolver =
                Declaration.vampireResolver \prepared -> do
                    IORef.modifyIORef' calls (+ 1)
                    resolveAccepted executable prepared
        omittedBatch <- runSuccessfulWithResolver fixture countingResolver do
            (_value, committed) <- Declaration.commitProofDeclaration
                (Semantic.proofSyntaxId "omitted-after-obligations") do
                    candidate <- Declaration.reserveCandidate
                        (factSpec fixture "omitted-after-obligations")
                    Declaration.authorizeOmittedCandidate candidate do
                        Declaration.acceptVampireObligation first
                        Declaration.acceptVampireObligation second
                        Declaration.recordOmittedUse
            pure committed
        assertEqual
            "omitted proof still checks preceding obligations"
            2
            =<< IORef.readIORef calls
        case Declaration.committedBatchProofValidations omittedBatch of
            [record] ->
                assertEqual
                    "omitted direct authorization discards request IDs"
                    Authority.OmittedAuthorization
                    (Authority.validationDirectAuthorization
                        (Semantic.proofValidationRecordCertificate record))
            records ->
                assertFailure
                    ("unexpected omitted validation count: "
                        <> show (length records))

validatesCompleteResolverBatchesBeforeRejection :: Assertion
validatesCompleteResolverBatchesBeforeRejection =
    withTemporaryDirectory "felix-declaration-batch-integrity" \root -> do
        fixture <- makeFixture
        let executable = root Posix.</> "vampire"
            firstLocation = mkLocation (FileId 76) 1 1
            secondLocation = mkLocation (FileId 76) 2 1
        writeAcceptedVampire executable
        mismatchedTask <-
            makePreparedObligation
                fixture
                Foundation.EmptyCharacteristic
        let integrityResolver =
                Declaration.vampireBatchResolver \_tasks -> do
                    mismatched <- resolveAccepted executable mismatchedTask
                    pure
                        ( Right (Provers.CounterSatisfiable "earlier")
                        :| [mismatched]
                        )
        integrityOutcome <-
            (runDriverWithResolver fixture integrityResolver do
                Declaration.commitProofDeclaration
                    (Semantic.proofSyntaxId "batch-integrity-priority") do
                        candidates <- Declaration.reserveCandidateBatch
                            ( factSpec fixture "batch-integrity-first"
                            :| [factSpec fixture "batch-integrity-second"]
                            )
                        Declaration.authorizeVampireCandidateBatch
                            ( ( firstLocation
                              , NonEmpty.head candidates
                              , Declaration.prepareCurrentCandidateVampire
                              )
                            :| [ ( secondLocation
                                 , NonEmpty.last candidates
                                 , Declaration.prepareCurrentCandidateVampire
                                 )
                               ]
                            )
                :: IO
                    (Declaration.DriverResult Text
                        ((), Declaration.CommittedDeclarationBatch)))
        case integrityOutcome of
            Declaration.DriverFailed
                    (Declaration.DriverDeclarationFailed
                        (Declaration.ProofObligationFailedAt
                            location
                            Declaration.VampireRequestMismatch))
                    prefix -> do
                assertEqual
                    "later request mismatch retains its location"
                    secondLocation
                    location
                assertEqual
                    "integrity failure rolls back the complete declaration"
                    0
                    (length
                        (Declaration.pendingModulePrefixBatches prefix))
            Declaration.DriverFailed failure _prefix ->
                assertFailure
                    ("unexpected batch-integrity failure: " <> show failure)
            Declaration.DriverSucceeded{} ->
                assertFailure
                    "earlier ordinary rejection concealed no integrity failure"
            Declaration.DriverSealFailed{} ->
                assertFailure "invalid batch reached module sealing"

        prepared <-
            makePreparedObligation
                fixture
                Foundation.EmptyCharacteristic
        let excessResolver =
                Declaration.vampireBatchResolver \_tasks ->
                    pure
                        ( Right (Provers.CounterSatisfiable "first")
                        :| [Right (Provers.CounterSatisfiable "excess")]
                        )
        excessOutcome <-
            (runDriverWithResolver fixture excessResolver do
                Declaration.commitProofDeclaration
                    (Semantic.proofSyntaxId "singleton-excess-result") do
                        candidate <- Declaration.reserveCandidate
                            (factSpec fixture "singleton-excess-result")
                        Declaration.authorizeVampireCandidate candidate
                            (Declaration.acceptVampireObligation prepared)
                :: IO
                    (Declaration.DriverResult Text
                        ((), Declaration.CommittedDeclarationBatch)))
        case excessOutcome of
            Declaration.DriverFailed
                    (Declaration.DriverDeclarationFailed
                        (Declaration.VampireResolverBatchSizeMismatch 1 2))
                    prefix ->
                assertEqual
                    "malformed singleton response publishes no declaration"
                    0
                    (length
                        (Declaration.pendingModulePrefixBatches prefix))
            Declaration.DriverFailed failure _prefix ->
                assertFailure
                    ("unexpected singleton-cardinality failure: "
                        <> show failure)
            Declaration.DriverSucceeded{} ->
                assertFailure "singleton resolver ignored an excess result"
            Declaration.DriverSealFailed{} ->
                assertFailure "malformed singleton reached module sealing"

rejectsRetainedPlanAdmissionDrift :: Assertion
rejectsRetainedPlanAdmissionDrift = do
    fixture <- makeFixture
    let checked =
            Declaration.checkedProofDeclaration
                (Semantic.proofSyntaxId "planned-admission-drift")
                []
                []
                []
                []
                [ Declaration.checkedCandidate
                    (factSpec fixture "planned-admission-drift")
                    Declaration.checkedSourceAxiomPlanning
                    :| []
                ]
                ()
        action = do
            planned <-
                Declaration.runProspectiveLoweringDriver
                    (Declaration.planCheckedDeclaration checked)
                    >>= either Declaration.failDeclarationDriver pure
            Declaration.admitPlannedCheckedDeclaration planned
                (\() stages ->
                    case concatMap toList stages of
                        [candidate] ->
                            Declaration.authorizeOmittedCandidate candidate
                                Declaration.recordOmittedUse
                        _ -> error "planned drift fixture candidate shape")
    outcome <-
        Exception.try (runDriver fixture action)
            :: IO
                (Either
                    Declaration.PlanningIntegrityError
                    (Declaration.DriverResult
                        Void
                        Declaration.CommittedDeclarationBatch))
    case outcome of
        Left (Declaration.PlanningIntegrityError diagnostic) ->
            assertBool "fatal mismatch identifies prospective contract drift"
                ("prospective contract" `Text.isInfixOf` diagnostic)
        Right _ ->
            assertFailure
                "a changed admitted authority was accepted against its plan"

preservesSourceAxiomSafetyThroughVampireValidation :: Assertion
preservesSourceAxiomSafetyThroughVampireValidation =
    withTemporaryDirectory "felix-declaration-source-axiom" \root -> do
        fixture <- makeFixture
        let executable = root Posix.</> "vampire"
        writeAcceptedVampire executable
        prepared <-
            makePreparedObligationWithPremise
                fixture
                (fixtureSourceAxiomFingerprint fixture)
        freshCalls <- IORef.newIORef (0 :: Int)
        let freshResolver = Declaration.vampireResolver \task -> do
                IORef.modifyIORef' freshCalls (+ 1)
                resolveAccepted executable task
        freshOutcome <-
            (runDriverWithResolver fixture freshResolver
                (sourceAxiomThenVampire fixture prepared)
                :: IO
                    (Declaration.DriverResult Text
                        Declaration.CommittedDeclarationBatch))
        assertEqual
            "fresh source-axiom theorem invokes Vampire once"
            1
            =<< IORef.readIORef freshCalls
        freshBatch <-
            case freshOutcome of
                Declaration.DriverSucceeded batch _ _ _closure ->
                    pure batch
                Declaration.DriverFailed failure _ ->
                    assertFailure
                        ("fresh source-axiom driver failed: "
                            <> show failure)
                        >> fail "unreachable"
                Declaration.DriverSealFailed failure _ ->
                    assertFailure
                        ("fresh source-axiom driver did not seal: "
                            <> show failure)
                        >> fail "unreachable"
        let freshRecord = singleProofValidation freshBatch
        assertEqual
            "fresh theorem retains source-axiom safety"
            sourceAxiomSafety
            (Authority.factAuthoritySafety
                (Authority.validationTarget
                    (Semantic.proofValidationRecordCertificate freshRecord)))
        separationCalls <- IORef.newIORef (0 :: Int)
        let separationResolver = Declaration.vampireResolver \task -> do
                IORef.modifyIORef' separationCalls (+ 1)
                resolveAccepted executable task
        separated <-
            (runDriverWithResolver fixture separationResolver do
                void
                    (Declaration.commitProofDeclaration
                        (Semantic.proofSyntaxId "source-axiom") do
                            candidate <- Declaration.reserveCandidate
                                (factSpec fixture "source-axiom")
                            Declaration.authorizeSourceAxiomCandidate candidate)
                Declaration.commitProofDeclaration
                    (Semantic.proofSyntaxId "atp-does-not-import") do
                        candidate <- Declaration.reserveCandidate
                            (factSpec fixture "atp-does-not-import")
                        Declaration.authorizeKernelProofCandidate candidate do
                            Declaration.acceptVampireObligation prepared
                            pure
                                (Kernel.importedFactDerivation
                                    (Kernel.importIx 0))
                :: IO
                    (Declaration.DriverResult Text
                        ((), Declaration.CommittedDeclarationBatch)))
        assertEqual "mixed proof executes its ATP obligation"
            1
            =<< IORef.readIORef separationCalls
        case separated of
            Declaration.DriverFailed
                    (Declaration.DriverDeclarationFailed
                        (Declaration.KernelCompletionFailed
                            (Kernel.KernelReplayImportOutOfBounds index)))
                    prefix -> do
                assertEqual "ATP premise is absent from kernel imports"
                    (Kernel.importIx 0)
                    index
                assertEqual "failed mixed proof retains only its prefix"
                    1
                    (length
                        (Declaration.pendingModulePrefixBatches prefix))
            Declaration.DriverFailed failure _prefix ->
                assertFailure
                    ("unexpected mixed-proof failure: " <> show failure)
            Declaration.DriverSucceeded{} ->
                assertFailure "ATP premise entered the kernel import inventory"
            Declaration.DriverSealFailed{} ->
                assertFailure "mixed proof unexpectedly reached sealing"
        withOpenedStore fixture root \store -> do
            freshPrefix <-
                case freshOutcome of
                    Declaration.DriverSucceeded _ _ prefix _closure ->
                        pure prefix
                    Declaration.DriverFailed failure _ ->
                        assertFailure
                            ("fresh source-axiom driver failed: "
                                <> show failure)
                            >> fail "unreachable"
                    Declaration.DriverSealFailed failure _ ->
                        assertFailure
                            ("fresh source-axiom driver did not seal: "
                                <> show failure)
                            >> fail "unreachable"
            expectRightIO
                (Store.writePendingModulePrefix store freshPrefix)
            warmCalls <- IORef.newIORef (0 :: Int)
            let storeLookup = proofOnlyValidationLookup \key -> do
                    IORef.modifyIORef' warmCalls (+ 1)
                    Store.loadProofValidation store key >>= expectRight
            warmBatch <- runSuccessfulWithValidation fixture
                storeLookup
                (sourceAxiomThenVampire fixture prepared)
            assertEqual
                "warm source-axiom theorem performs one store lookup"
                1
                =<< IORef.readIORef warmCalls
            assertEqual
                "warm theorem retains source-axiom safety"
                sourceAxiomSafety
                (Authority.factAuthoritySafety
                    (Authority.validationTarget
                        (Semantic.proofValidationRecordCertificate
                            (singleProofValidation warmBatch))))
  where
    sourceAxiomSafety =
        Authority.authoritySafety
            (Authority.singletonEscapeKind Authority.SourceAxiom)

    singleProofValidation batch =
        case Declaration.committedBatchProofValidations batch of
            [record] -> record
            records ->
                error
                    ("unexpected proof validation count: "
                        <> show (length records))

sourceAxiomThenVampire
    :: Fixture
    -> Provers.PreparedTypedProverTask
        Semantic.SemanticFactOccurrenceFingerprint
        Void
        ()
        Identity.ObjectId
    -> Declaration.ModuleDriver failure
        Declaration.CommittedDeclarationBatch
sourceAxiomThenVampire fixture prepared = do
    void
        (Declaration.commitProofDeclaration
            (Semantic.proofSyntaxId "source-axiom") do
                candidate <- Declaration.reserveCandidate
                    (factSpec fixture "source-axiom")
                Declaration.authorizeSourceAxiomCandidate candidate)
    (_value, batch) <- Declaration.commitProofDeclaration
        (Semantic.proofSyntaxId "source-axiom-vampire") do
            candidate <- Declaration.reserveCandidate
                (factSpec fixture "source-axiom-vampire")
            Declaration.authorizeVampireCandidate candidate
                (Declaration.acceptVampireObligation prepared)
    pure batch

fixtureSourceAxiomFingerprint
    :: Fixture
    -> Semantic.SemanticFactOccurrenceFingerprint
fixtureSourceAxiomFingerprint fixture =
    Semantic.semanticFactOccurrenceFingerprint
        (Semantic.factSlot
            (fixtureOwner fixture)
            (localFactOrdinal 0))
        (Authority.factAuthority
            (Identity.theoremRef
                (Identity.theoryId (fixtureFoundation fixture))
                (Identity.checkedPropositionId
                    (fixtureProposition fixture)))
            (Authority.authoritySafety
                (Authority.singletonEscapeKind Authority.SourceAxiom)))

makePreparedObligationWithPremise
    :: Fixture
    -> Semantic.SemanticFactOccurrenceFingerprint
    -> IO
        (Provers.PreparedTypedProverTask
            Semantic.SemanticFactOccurrenceFingerprint
            Void
            ()
            Identity.ObjectId)
makePreparedObligationWithPremise fixture fingerprint = do
    claim <- expectRight
        (Backend.supportedProposition
            (Vector.empty :: Vector.Vector (Void, Core.CoreType))
            (Core.embedClosedCore
                []
                (Identity.checkedPropositionTerm
                    (fixtureProposition fixture))))
    factProposition <- expectRight
        (Backend.supportedProposition
            (Vector.empty :: Vector.Vector (Void, Core.CoreType))
            (Core.embedClosedCore
                []
                (Identity.checkedPropositionTerm
                    (fixtureProposition fixture))))
    capability <- expectRight
        (Backend.classifySupportedProposition
            (const Nothing)
            factProposition)
    problem <- expectRight
        (Backend.planTypedProblem
            (const Nothing)
            (Vector.singleton
                (Backend.typedBackendFact
                    fingerprint
                    factProposition
                    capability))
            claim
            []
            []
            Backend.ExplicitGlobalPremiseSelection)
    expectRight
        (Provers.prepareTypedProverTask
            Provers.DirectTask
            problem)

makePreparedObligation
    :: Fixture
    -> Foundation.FoundationAxiomTag
    -> IO
        (Provers.PreparedTypedProverTask
            Semantic.SemanticFactOccurrenceFingerprint
            Void
            ()
            Identity.ObjectId)
makePreparedObligation fixture tag = do
    claim <- expectRight
        (Backend.supportedProposition
            (Vector.empty :: Vector.Vector (Void, Core.CoreType))
            (Core.embedClosedCore
                []
                (Identity.checkedPropositionTerm
                    (fixtureProposition fixture))))
    problem <- expectRight
        (Backend.planTypedProblem
            (const Nothing)
            Vector.empty
            claim
            []
            [Backend.typedFoundationAuxiliaryInput
                (fixtureFoundation fixture)
                tag]
            Backend.LocalOnlyPremiseSelection)
    expectRight
        (Provers.prepareTypedProverTask
            Provers.DirectTask
            problem)

acceptedResolver :: FilePath -> Declaration.VampireResolver
acceptedResolver executable =
    Declaration.vampireResolver (resolveAccepted executable)

resolveAccepted
    :: FilePath
    -> Provers.PreparedTypedProverTask
        ref local origin global
    -> IO
        (Either
            Provers.ProverProcessError
            Provers.ProverAnswer)
resolveAccepted executable prepared =
    runNoLoggingT
        (Provers.runPreparedTypedProver
            (Provers.vampire
                executable
                Provers.defaultTimeLimit
                Provers.defaultMemoryLimit)
            prepared)

writeAcceptedVampire :: FilePath -> IO ()
writeAcceptedVampire executable = do
    writeFile executable
        (unlines
            [ "#!/bin/sh"
            , "cat >/dev/null"
            , "printf '%s\\n' '% SZS status Theorem for typed'"
            ])
    permissions <- Directory.getPermissions executable
    Directory.setPermissions executable
        (Directory.setOwnerExecutable True permissions)

validatesExactKernelConstructionDescriptors :: Assertion
validatesExactKernelConstructionDescriptors = do
    fixture <- makeFixture
    proposition <- foundationProposition
        fixture
        Foundation.EmptyCharacteristic
    let declaredObject = opaqueFixtureObject fixture
        run descriptor =
            runDriver fixture
                (Declaration.commitCompiledDeclaration
                    (Semantic.declarationSyntaxId
                        "kernel-construction-descriptor") do
                        Declaration.addDeclarationObject declaredObject
                        candidate <- Declaration.reserveCandidate
                            (Declaration.candidateSpec
                                proposition
                                Semantic.SearchEligible
                                [Semantic.semanticName "kernel-construction"])
                        Declaration.authorizeCompiledDeclaration
                            (Declaration.authorizeKernelConstructionCandidate
                                descriptor
                                candidate
                                (pure
                                    (Kernel.foundationFactDerivation
                                        Foundation.EmptyCharacteristic))))
    success <- run
        (Authority.FoundationLeaf
            Foundation.EmptyCharacteristic)
    case success of
        Declaration.DriverSucceeded (_value, batch) _interface _prefix _closure -> do
            assertEqual
                "new object is included in the checked declaration batch"
                1
                (length (Declaration.committedBatchObjects batch))
            case Declaration.committedBatchDeclarationValidation batch of
                Just record ->
                    case Semantic.declarationValidationRecordCertificates
                            record of
                        [certificate] ->
                            assertEqual
                                "exact kernel descriptor is retained"
                                (Authority.CheckedKernelConstruction
                                    (Authority.FoundationLeaf
                                        Foundation.EmptyCharacteristic))
                                (Authority.validationDirectAuthorization
                                    certificate)
                        certificates ->
                            assertFailure
                                ("unexpected kernel certificate count: "
                                    <> show (length certificates))
                Nothing ->
                    assertFailure "missing declaration validation"
        Declaration.DriverFailed
                (Declaration.DriverDeclarationFailed failure) _prefix ->
            assertFailure
                ("valid kernel descriptor failed: " <> show failure)
        Declaration.DriverFailed
                (Declaration.DriverActionFailed _failure) _prefix ->
            assertFailure "unexpected ordinary driver failure"
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure (show failure)

    traverse_
        (\(label, descriptor) -> do
            outcome <- run descriptor
            case outcome of
                Declaration.DriverFailed
                        (Declaration.DriverDeclarationFailed
                            Declaration.KernelConstructionDescriptorMismatch)
                        prefix ->
                    assertEqual
                        (label <> " publishes no declaration")
                        0
                        (length
                            (Declaration.pendingModulePrefixBatches prefix))
                Declaration.DriverFailed
                        (Declaration.DriverDeclarationFailed other)
                        _prefix ->
                    assertFailure
                        (label <> ": unexpected error " <> show other)
                Declaration.DriverFailed
                        (Declaration.DriverActionFailed _failure)
                        _prefix ->
                    assertFailure (label <> ": ordinary driver failure")
                Declaration.DriverSucceeded{} ->
                    assertFailure (label <> ": mismatch was accepted")
                Declaration.DriverSealFailed{} ->
                    assertFailure (label <> ": mismatch reached sealing"))
        [ ( "wrong foundation leaf"
          , Authority.FoundationLeaf
                Foundation.PairSetCharacteristic
          )
        , ( "wrong construction family"
          , Authority.GuardedFoundationRules
                (Authority.guardedRuleSet
                    (Foundation.SetLfpBound :| []))
          )
        ]

authorizesExactDatatypeCompilationFamilies :: Assertion
authorizesExactDatatypeCompilationFamilies = do
    fixture <- makeFixture
    firstProposition <- foundationProposition
        fixture
        Foundation.EmptyCharacteristic
    secondProposition <- foundationProposition
        fixture
        Foundation.PairSetCharacteristic
    let carrier = datatypeFixtureObject fixture 0
        constructor = datatypeFixtureObject fixture 1
        carrierId = Identity.assertedObjectId carrier
        constructorId = Identity.assertedObjectId constructor
        references =
            fmap
                (Identity.theoremRef
                    (Identity.theoryId
                        (fixtureFoundation fixture))
                    . Identity.checkedPropositionId)
                [firstProposition, secondProposition]
        descriptor =
            Authority.datatypeCompilationDescriptor
                carrierId
                (constructorId :| [])
                references
        action
            :: Authority.DatatypeCompilationDescriptor
            -> Declaration.ModuleDriver Text
                ((), Declaration.CommittedDeclarationBatch)
        action suppliedDescriptor =
            Declaration.commitCompiledDeclaration
                (Semantic.declarationSyntaxId "datatype-compilation") do
                traverse_ Declaration.addDeclarationObject
                    [carrier, constructor]
                candidates <-
                    Declaration.reserveCandidateBatch
                        ( Declaration.candidateSpec
                            firstProposition
                            Semantic.SearchEligible
                            [Semantic.semanticName "datatype-first"]
                        :| [ Declaration.candidateSpec
                                secondProposition
                                Semantic.SearchEligible
                                [Semantic.semanticName "datatype-second"]
                           ]
                        )
                Declaration.authorizeCompiledDeclaration
                    (Declaration.authorizeDatatypeCompilationCandidates
                        suppliedDescriptor
                        carrierId
                        (constructorId :| [])
                        candidates)

    (_value, batch) <- runSuccessful fixture (action descriptor)
    assertEqual "complete object family was published"
        [carrier, constructor]
        (Declaration.committedBatchObjects batch)
    case Declaration.committedBatchDeclarationValidation batch of
        Just record -> do
            let certificates =
                    Semantic.declarationValidationRecordCertificates record
            assertEqual "complete fact family was authorized" 2
                (length certificates)
            traverse_
                (\certificate -> do
                    assertEqual "datatype authority is clean"
                        Authority.cleanAuthoritySafety
                        (Authority.factAuthoritySafety
                            (Authority.validationTarget certificate))
                    assertEqual "one descriptor protects every member"
                        (Authority.TrustedCompilation
                            (Authority.DatatypeCompilation descriptor))
                        (Authority.validationDirectAuthorization certificate))
                certificates
        Nothing ->
            assertFailure "datatype compilation omitted validation"

    let mismatched =
            Authority.datatypeCompilationDescriptor
                carrierId
                (constructorId :| [])
                (reverse references)
    rejected <- runDriver fixture (action mismatched)
    case rejected of
        Declaration.DriverFailed
                (Declaration.DriverDeclarationFailed
                    Declaration.DatatypeCompilationDescriptorMismatch)
                prefix ->
            assertEqual "mismatched family publishes no declaration"
                0
                (length
                    (Declaration.pendingModulePrefixBatches prefix))
        Declaration.DriverFailed failure _prefix ->
            assertFailure
                ("unexpected datatype-family failure: " <> show failure)
        Declaration.DriverSucceeded{} ->
            assertFailure "mismatched datatype family was authorized"
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure
                ("mismatched datatype family reached sealing: "
                    <> show failure)

reusesExactCompiledDeclarationValidation :: Assertion
reusesExactCompiledDeclarationValidation = do
    fixture <- makeFixture
    proposition <- foundationProposition
        fixture
        Foundation.EmptyCharacteristic
    let declaredObject = opaqueFixtureObject fixture
        syntax =
            Semantic.declarationSyntaxId
                "cached-kernel-construction"
        action derivationTag =
            Declaration.commitCompiledDeclaration syntax do
                Declaration.addDeclarationObject declaredObject
                candidate <- Declaration.reserveCandidate
                    (Declaration.candidateSpec
                        proposition
                        Semantic.SearchEligible
                        [Semantic.semanticName
                            "cached-kernel-construction"])
                Declaration.authorizeCompiledDeclaration
                    (Declaration.authorizeKernelConstructionCandidate
                        (Authority.FoundationLeaf
                            Foundation.EmptyCharacteristic)
                        candidate
                        (pure
                            (Kernel.foundationFactDerivation
                                derivationTag)))
    freshBatch <- runSuccessful fixture
        (snd <$> action Foundation.EmptyCharacteristic)
    freshRecord <-
        case Declaration.committedBatchDeclarationValidation freshBatch of
            Just record -> pure record
            Nothing ->
                assertFailure "fresh compiled declaration omitted validation"
                    >> fail "unreachable"

    missLookups <- IORef.newIORef (0 :: Int)
    missBatch <- runSuccessfulWithValidation fixture
        (compiledOnlyValidationLookup \_key -> do
            IORef.modifyIORef' missLookups (+ 1)
            pure Nothing)
        (snd <$> action Foundation.EmptyCharacteristic)
    assertEqual "compiled warm miss performs one exact lookup"
        1
        =<< IORef.readIORef missLookups
    assertBool "compiled miss publishes fresh validation"
        (isJust
            (Declaration.committedBatchDeclarationValidation missBatch))

    hitLookups <- IORef.newIORef []
    hitBatch <- runSuccessfulWithValidation fixture
        (compiledOnlyValidationLookup \key -> do
            IORef.modifyIORef' hitLookups (key :)
            pure (Just freshRecord))
        (snd <$> action Foundation.PairSetCharacteristic)
    assertEqual "compiled warm hit performs one exact lookup"
        [Semantic.declarationValidationRecordKey freshRecord]
        . reverse
        =<< IORef.readIORef hitLookups
    case Declaration.committedBatchDeclarationValidation hitBatch of
        Just record ->
            assertEqual
                "compiled hit republishes the exact validation"
                freshRecord
                record
        Nothing ->
            assertFailure "compiled hit omitted validation"

foundationProposition
    :: Fixture
    -> Foundation.FoundationAxiomTag
    -> IO Identity.CheckedPropositionContent
foundationProposition fixture tag = do
    closure <- expectRight
        (Identity.validateObjectClosure
            (Identity.theoryId (fixtureFoundation fixture))
            [])
    expectRight
        (Identity.validatePropositionContent
            closure
            (Core.frozenCoreTerm
                (Core.mapFrozenGlobals
                    absurd
                    (Foundation.foundationAxiomFrozen
                        (fixtureFoundation fixture)
                        tag))))

opaqueFixtureObject :: Fixture -> Identity.AssertedObject
opaqueFixtureObject fixture =
    let theory = Identity.theoryId (fixtureFoundation fixture)
        seed =
            Identity.opaqueDeclarationSeed
                (fixtureOwner fixture)
                (localDeclarationOrdinal 0)
                SignatureDeclaration
                (generatedObjectSlot 0)
        identity =
            Identity.opaqueObjectId
                theory
                seed
                Core.TySet
    in Identity.assertedObject
        identity
        (Identity.OpaqueObjectContent
            theory
            seed
            Core.TySet)

datatypeFixtureObject
    :: Fixture
    -> Natural
    -> Identity.AssertedObject
datatypeFixtureObject fixture slot =
    let theory = Identity.theoryId (fixtureFoundation fixture)
        seed =
            Identity.opaqueDeclarationSeed
                (fixtureOwner fixture)
                (localDeclarationOrdinal 0)
                DatatypeDeclaration
                (generatedObjectSlot slot)
        identity =
            Identity.opaqueObjectId theory seed Core.TySet
    in Identity.assertedObject
        identity
        (Identity.OpaqueObjectContent theory seed Core.TySet)


data Fixture = Fixture
    { fixtureFoundation :: !Foundation.CheckedFoundation
    , fixtureOwner :: !ModuleName
    , fixtureProposition :: !Identity.CheckedPropositionContent
    }

makeFixture :: IO Fixture
makeFixture =
    makeNamedFixture "root"

makeNamedFixture :: Text -> IO Fixture
makeNamedFixture name = do
    foundation <- expectRight Foundation.checkedFoundation
    namespaceDigest <- expectRight
        (hashCanonicalFields
            "declaration-test-namespace"
            [TextEncoding.encodeUtf8 name])
    relative <- expectRight
        (safeRelativePath
            (Text.unpack name <> ".tex"))
    let theory = Identity.theoryId foundation
        owner =
            moduleNameFromParts
                (sourceNamespaceIdFromDigest namespaceDigest)
                relative
    closure <- expectRight
        (Identity.validateObjectClosure theory [])
    proposition <- expectRight
        (Identity.validatePropositionContent closure Core.CFalsum)
    pure
        Fixture
            { fixtureFoundation = foundation
            , fixtureOwner = owner
            , fixtureProposition = proposition
            }

factSpec :: Fixture -> Text -> Declaration.CandidateSpec
factSpec fixture alias =
    Declaration.candidateSpec
        (fixtureProposition fixture)
        Semantic.SearchEligible
        [Semantic.semanticName alias]

runDriver
    :: Fixture
    -> Declaration.ModuleDriver failure value
    -> IO (Declaration.DriverResult failure value)
runDriver fixture =
    runDriverWithResolver fixture unavailableVampireResolver

runDriverWithResolver
    :: Fixture
    -> Declaration.VampireResolver
    -> Declaration.ModuleDriver failure value
    -> IO (Declaration.DriverResult failure value)
runDriverWithResolver fixture resolver action = do
    result <- Declaration.runModuleDriver
        (fixtureFoundation fixture)
        (fixtureOwner fixture)
        []
        resolver
        Declaration.FreshValidation
        action
    expectRight result

runDriverWithValidation
    :: Fixture
    -> Declaration.ValidationLookup
    -> Declaration.ModuleDriver failure value
    -> IO (Declaration.DriverResult failure value)
runDriverWithValidation fixture lookup action = do
    runDriverWithValidationAndResolver
        fixture
        lookup
        unavailableVampireResolver
        action

runDriverWithValidationAndResolver
    :: Fixture
    -> Declaration.ValidationLookup
    -> Declaration.VampireResolver
    -> Declaration.ModuleDriver failure value
    -> IO (Declaration.DriverResult failure value)
runDriverWithValidationAndResolver fixture lookup resolver action = do
    result <- Declaration.runModuleDriver
        (fixtureFoundation fixture)
        (fixtureOwner fixture)
        []
        resolver
        (Declaration.WarmValidation lookup)
        action
    expectRight result

proofOnlyValidationLookup
    :: (Semantic.ProofValidationKey
        -> IO (Maybe Semantic.ProofValidationRecord))
    -> Declaration.ValidationLookup
proofOnlyValidationLookup lookupProof =
    Declaration.validationLookup
        lookupProof
        (const (pure Nothing))

compiledOnlyValidationLookup
    :: (Semantic.DeclarationValidationKey
        -> IO (Maybe Semantic.DeclarationValidationRecord))
    -> Declaration.ValidationLookup
compiledOnlyValidationLookup lookupDeclaration =
    Declaration.validationLookup
        (const (pure Nothing))
        lookupDeclaration

runDriverWithDirect
    :: Fixture
    -> [Semantic.SemanticInterfaceId]
    -> Declaration.ModuleDriver failure value
    -> IO (Declaration.DriverResult failure value)
runDriverWithDirect fixture direct action = do
    result <- Declaration.runModuleDriver
        (fixtureFoundation fixture)
        (fixtureOwner fixture)
        direct
        unavailableVampireResolver
        Declaration.FreshValidation
        action
    expectRight result

unavailableVampireResolver :: Declaration.VampireResolver
unavailableVampireResolver =
    Declaration.vampireResolver \_prepared ->
        pure
            (Left
                (Provers.ProverLaunchFailed
                    "unused"
                    "Vampire resolver was not expected"))

runSuccessful
    :: Fixture
    -> Declaration.ModuleDriver failure value
    -> IO value
runSuccessful fixture =
    runSuccessfulWithResolver fixture unavailableVampireResolver

runSuccessfulWithResolver
    :: Fixture
    -> Declaration.VampireResolver
    -> Declaration.ModuleDriver failure value
    -> IO value
runSuccessfulWithResolver fixture resolver action = do
    outcome <- runDriverWithResolver fixture resolver action
    case outcome of
        Declaration.DriverSucceeded value _interface _prefix _closure ->
            pure value
        Declaration.DriverFailed _failure _prefix ->
            assertFailure "unexpected driver failure" >> fail "unreachable"
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure (show failure) >> fail "unreachable"

runSuccessfulWithValidation
    :: Fixture
    -> Declaration.ValidationLookup
    -> Declaration.ModuleDriver failure value
    -> IO value
runSuccessfulWithValidation fixture lookup action = do
    outcome <- runDriverWithValidation fixture lookup action
    case outcome of
        Declaration.DriverSucceeded value _interface _prefix _closure ->
            pure value
        Declaration.DriverFailed _failure _prefix ->
            assertFailure "unexpected driver failure" >> fail "unreachable"
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure (show failure) >> fail "unreachable"

materializesSealedImport :: Assertion
materializesSealedImport = do
    fixture <- makeFixture
    producer <- runDriver fixture do
        (_value, batch) <- Declaration.commitProofDeclaration
            (Semantic.proofSyntaxId "sealed-import-producer") do
                candidate <- Declaration.reserveCandidate
                    (factSpec fixture "producer-fact")
                Declaration.authorizeOmittedCandidate candidate
                    Declaration.recordOmittedUse
        pure batch
    (producerInterface, evidence, fingerprint) <-
        case producer of
            Declaration.DriverSucceeded _ interface prefix _closure ->
                let imported =
                        Declaration.freshImportedModuleEvidence
                            [] interface prefix
                in case concatMap
                        Semantic.declarationDeltaFacts
                        (Semantic.semanticInterfaceDeclarations interface) of
                    [occurrence] ->
                        pure
                            ( interface
                            , imported
                            , Semantic.semanticFactFingerprint occurrence
                            )
                    occurrences ->
                        assertFailure
                            ("unexpected producer facts: "
                                <> show (length occurrences))
                            >> fail "unreachable"
            Declaration.DriverFailed failure _prefix ->
                assertFailure
                    ("producer failed: "
                        <> show
                            (failure
                                :: Declaration.DriverFailure
                                    Declaration.DeclarationError))
                    >> fail "unreachable"
            Declaration.DriverSealFailed failure _prefix ->
                assertFailure ("producer did not seal: " <> show failure)
                    >> fail "unreachable"
    consumerNamespace <- expectRight
        (hashCanonicalFields
            "declaration-import-consumer"
            ["consumer"])
    consumerPath <- expectRight (safeRelativePath "consumer.tex")
    let consumerFixture =
            fixture
                { fixtureOwner =
                    moduleNameFromParts
                        (sourceNamespaceIdFromDigest consumerNamespace)
                        consumerPath
                }
    consumer <- runDriverWithDirect consumerFixture
        [Semantic.semanticInterfaceAssertedId producerInterface]
        do
            (_value, committed) <- Declaration.commitProofDeclaration
                (Semantic.proofSyntaxId "sealed-import-consumer") do
                    Declaration.importSealedModule evidence
                    candidate <- Declaration.reserveCandidate
                        (factSpec fixture "consumer-fact")
                    Declaration.authorizeOmittedCandidate candidate do
                        _ <- Declaration.useAuthorizedFact fingerprint
                        Declaration.recordOmittedUse
            pure committed
    case consumer of
        Declaration.DriverSucceeded committed _ _ _ -> do
            case Semantic.declarationDeltaFacts
                    (Declaration.committedBatchDelta committed) of
                [localOccurrence] -> do
                    assertEqual
                        "the first local fact keeps ordinal zero"
                        (localFactOrdinal 0)
                        (Semantic.factSlotOrdinal
                            (Semantic.semanticFactSlot localOccurrence))
                    assertEqual
                        "the local fact belongs to the consumer"
                        (fixtureOwner consumerFixture)
                        (Semantic.factSlotModule
                            (Semantic.semanticFactSlot localOccurrence))
                facts ->
                    assertFailure
                        ("unexpected consumer fact count: "
                            <> show (length facts))
        Declaration.DriverFailed failure _prefix ->
            assertFailure
                ("consumer failed: "
                    <> show
                        (failure
                            :: Declaration.DriverFailure
                                Declaration.DeclarationError))
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure ("consumer did not seal: " <> show failure)

elaboratesScopedExactPropositions :: Assertion
elaboratesScopedExactPropositions = do
    fixture <- makeNamedFixture "exact-scoped-proposition"
    let x = Raw.NamedVar "x"
        y = Raw.NamedVar "y"
        statement =
            Raw.SymbolicQuantified
                Nowhere
                Raw.Universally
                (x :| [y])
                Raw.Unbounded
                Nothing
                (Raw.StmtFormula
                    (Raw.FormulaChain
                        (Raw.ChainBase
                            (Raw.ExprVar x :| [])
                            Raw.Positive
                            (Raw.Relation
                                Nowhere
                                Raw.EqSymbol
                                [])
                            (Raw.ExprVar y :| []))))
        action
            :: Declaration.ModuleDriver Text
                (Either
                    Exact.ExactCompileError
                    Exact.PreparedExactProposition)
        action =
            Declaration.runProspectiveLoweringDriver
                (Exact.prepareExactProposition
                    Exact.emptyExactBinderContext
                    statement)
    outcome <- runDriver fixture action
    case outcome of
        Declaration.DriverSucceeded (Right prepared) _interface _prefix _closure ->
            assertEqual
                "source-order universal binders"
                (Core.CForall Core.TySet
                    (Core.CForall Core.TySet
                        (Core.CEq Core.TySet
                            (Core.CBound 1)
                            (Core.CBound 0))))
                (Core.scopedCoreTerm
                    (Exact.preparedExactPropositionCore prepared))
        Declaration.DriverSucceeded (Left failure) _interface _prefix _closure ->
            assertFailure
                ("scoped exact elaboration failed: "
                    <> Text.unpack (Exact.renderExactCompileError failure))
        Declaration.DriverFailed failure _prefix ->
            assertFailure ("scoped exact driver failed: " <> show failure)
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure ("scoped exact driver did not seal: " <> show failure)

lowersFixedEqualityAliases :: Assertion
lowersFixedEqualityAliases = do
    fixture <- makeNamedFixture "fixed-equality-aliases"
    let x = Raw.NamedVar "x"
        y = Raw.NamedVar "y"
        z = Raw.NamedVar "z"
        term variable = Raw.TermExpr (Raw.ExprVar variable)
        equality left right =
            Raw.StmtFormula
                (Raw.FormulaChain
                    (Raw.ChainBase
                        (Raw.ExprVar left :| [])
                        Raw.Positive
                        (Raw.Relation Nowhere Raw.EqSymbol [])
                        (Raw.ExprVar right :| [])))
        quantified variables statement =
            Raw.SymbolicQuantified
                Nowhere
                Raw.Universally
                variables
                Raw.Unbounded
                Nothing
                statement
        adjective =
            Raw.Adj
                Nowhere
                Lexicon.builtinEqualityRightAdjective
                [term y]
        copular =
            Raw.StmtVerbPhrase
                (term x :| [])
                (Raw.VPAdj (adjective :| []))
        rightAttribute =
            Raw.StmtNoun
                (term x :| [])
                (Raw.NounPhrase
                    []
                    (Raw.Noun Nowhere Lexicon.builtinSetNoun [])
                    Nothing
                    [ Raw.AdjR
                        Nowhere
                        Lexicon.builtinEqualityRightAdjective
                        [term y]
                    ]
                    Nothing)
        rightAttributeExpected =
            Raw.StmtNoun
                (term x :| [])
                (Raw.NounPhrase
                    []
                    (Raw.Noun Nowhere Lexicon.builtinSetNoun [])
                    Nothing
                    []
                    (Just (equality x y)))
        verb argument =
            Raw.Verb
                Nowhere
                Lexicon.builtinEqualityVerb
                [term argument]
        singular =
            Raw.StmtVerbPhrase
                (term x :| [])
                (Raw.VPVerb (verb y))
        negated =
            Raw.StmtVerbPhrase
                (term x :| [])
                (Raw.VPVerbNot (verb y))
        coordinated =
            Raw.StmtVerbPhrase
                (term x :| [term y])
                (Raw.VPVerb (verb z))
        coordinatedExpected =
            Raw.StmtConnected
                Raw.Conjunction
                Nothing
                (equality x z)
                (equality y z)
        comparisons =
            [ ( "copular adjective"
              , quantified (x :| [y]) copular
              , quantified (x :| [y]) (equality x y)
              )
            , ( "right adjective"
              , quantified (x :| [y]) rightAttribute
              , quantified (x :| [y]) rightAttributeExpected
              )
            , ( "singular verb"
              , quantified (x :| [y]) singular
              , quantified (x :| [y]) (equality x y)
              )
            , ( "negated verb"
              , quantified (x :| [y]) negated
              , quantified
                    (x :| [y])
                    (Raw.StmtNeg Nowhere (equality x y))
              )
            , ( "quantified coordinated verb"
              , quantified (x :| [y, z]) coordinated
              , quantified (x :| [y, z]) coordinatedExpected
              )
            ]
        action
            :: Declaration.ModuleDriver Text
                [ ( Either
                        Exact.ExactCompileError
                        Exact.PreparedExactProposition
                  , Either
                        Exact.ExactCompileError
                        Exact.PreparedExactProposition
                  )
                ]
        action =
            Declaration.runProspectiveLoweringDriver
                (traverse
                    (\(_label, alias, symbolic) ->
                        (,)
                            <$> Exact.prepareExactProposition
                                Exact.emptyExactBinderContext alias
                            <*> Exact.prepareExactProposition
                                Exact.emptyExactBinderContext symbolic)
                    comparisons)
    runDriver fixture action >>= \case
        Declaration.DriverSucceeded results _interface _prefix _closure ->
            for_ (zip comparisons results) \((label, _alias, _symbolic), result) ->
                case result of
                    (Right alias, Right symbolic) -> do
                        let aliasTerm =
                                Core.scopedCoreTerm
                                    (Exact.preparedExactPropositionCore alias)
                            symbolicTerm =
                                Core.scopedCoreTerm
                                    (Exact.preparedExactPropositionCore symbolic)
                        assertEqual
                            (label <> " checked core")
                            symbolicTerm
                            aliasTerm
                        assertEqual
                            (label <> " global support")
                            Set.empty
                            (Core.canonicalTermGlobals aliasTerm)
                        assertEqual
                            (label <> " foundation support")
                            Set.empty
                            (Foundation.foundationAxiomDependencies aliasTerm)
                    (Left failure, _) ->
                        assertFailure
                            (label <> " alias failed: "
                                <> Text.unpack
                                    (Exact.renderExactCompileError failure))
                    (_, Left failure) ->
                        assertFailure
                            (label <> " symbolic comparison failed: "
                                <> Text.unpack
                                    (Exact.renderExactCompileError failure))
        Declaration.DriverFailed failure _prefix ->
            assertFailure ("fixed equality driver failed: " <> show failure)
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure ("fixed equality driver did not seal: " <> show failure)

    let internalEquality =
            Internal.FormulaVerb
                Nowhere
                (Internal.EmptySet Nowhere)
                Lexicon.builtinEqualityVerb
                [Internal.EmptySet Nowhere]
        internalResult
            :: Either
                Typed.TypedInductiveError
                (Core.FrozenCheckedCore Void)
        internalResult =
            Typed.prepareTypedClosedFormula
                absurd
                (const Nothing)
                internalEquality
    case internalResult of
        Right checked -> do
            assertEqual
                "internal fixed verb core"
                (Core.CEq
                    Core.TySet
                    (Core.CIntrinsic Core.Empty)
                    (Core.CIntrinsic Core.Empty))
                (Core.frozenCoreTerm checked)
            assertEqual
                "internal fixed verb global support"
                Set.empty
                (Core.frozenCoreGlobals checked)
        Left failure ->
            assertFailure
                ("internal fixed verb failed: " <> show failure)

preparesExactClaimEnvelopes :: Assertion
preparesExactClaimEnvelopes = do
    fixture <- makeNamedFixture "exact-claim-envelope"
    let bLocation = mkLocation (FileId 78) 2 11
        aLocation = mkLocation (FileId 78) 2 15
        xLocation = mkLocation (FileId 78) 3 9
        b = Raw.NamedVarAt bLocation "b"
        a = Raw.NamedVarAt aLocation "a"
        x = Raw.NamedVarAt xLocation "x"
        c = Raw.NamedVarAt Nowhere "c"
        d = Raw.NamedVarAt Nowhere "d"
        z = Raw.NamedVarAt Nowhere "z"
        equality left right =
            Raw.StmtFormula
                (Raw.FormulaChain
                    (Raw.ChainBase
                        (Raw.ExprVar left :| [])
                        Raw.Positive
                        (Raw.Relation Nowhere Raw.EqSymbol [])
                        (Raw.ExprVar right :| [])))
        quantified variable body =
            Raw.SymbolicQuantified
                (locate variable)
                Raw.Universally
                (variable :| [])
                Raw.Unbounded
                Nothing
                body
        sourceAssumptions = [Raw.AsmSuppose (equality b a)]
        sourceConclusion = quantified x (equality x b)
        alphaAssumptions = [Raw.AsmSuppose (equality c d)]
        alphaConclusion = quantified z (equality z c)
        action
            :: Declaration.ModuleDriver Text
                ( Either
                    Exact.ExactCompileError
                    Exact.PreparedExactClaimEnvelope
                , Either
                    Exact.ExactCompileError
                    Exact.PreparedExactClaimEnvelope
                )
        action =
            Declaration.runProspectiveLoweringDriver do
                source <- Exact.prepareExactClaimEnvelope
                    sourceAssumptions sourceConclusion
                alpha <- Exact.prepareExactClaimEnvelope
                    alphaAssumptions alphaConclusion
                pure (source, alpha)
        expected =
            Core.CForall Core.TySet
                (Core.CForall Core.TySet
                    (Core.CImp
                        (Core.CEq Core.TySet
                            (Core.CBound 1)
                            (Core.CBound 0))
                        (Core.CForall Core.TySet
                            (Core.CEq Core.TySet
                                (Core.CBound 0)
                                (Core.CBound 2)))))
    runDriver fixture action >>= \case
        Declaration.DriverSucceeded
                (Right source, Right alpha)
                _interface _prefix _closure -> do
            let sourceTarget = Exact.preparedExactClaimTarget source
                alphaTarget = Exact.preparedExactClaimTarget alpha
            assertEqual "closed claim envelope core"
                expected
                (Core.scopedCoreTerm sourceTarget)
            assertEqual "claim envelope is closed"
                []
                (Core.scopedCoreContext sourceTarget)
            assertEqual "first semantic occurrence binder order"
                [bLocation, aLocation]
                (locate <$> Exact.preparedExactClaimVariables source)
            assertEqual "explicit binders are not generalized"
                2
                (length (Exact.preparedExactClaimVariables source))
            assertEqual "header antecedent count"
                1
                (Exact.preparedExactClaimAntecedentCount source)
            assertEqual "alpha-renaming preserves the checked target"
                sourceTarget alphaTarget
            assertEqual "alpha-renaming preserves proposition identity"
                (Identity.propositionIdOf
                    (Core.scopedCoreTerm sourceTarget))
                (Identity.propositionIdOf
                    (Core.scopedCoreTerm alphaTarget))
        Declaration.DriverSucceeded result _interface _prefix _closure ->
            assertFailure
                ("exact claim envelope preparation failed: "
                    <> case result of
                        (Left failure, _) ->
                            Text.unpack
                                (Exact.renderExactCompileError failure)
                        (_, Left failure) ->
                            Text.unpack
                                (Exact.renderExactCompileError failure))
        Declaration.DriverFailed failure _prefix ->
            assertFailure ("claim envelope driver failed: " <> show failure)
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure
                ("claim envelope driver did not seal: " <> show failure)

lowersExactSeparationComprehensions :: Assertion
lowersExactSeparationComprehensions = do
    fixture <- makeNamedFixture "exact-separation-comprehension"
    let binderLocation = mkLocation (FileId 73) 2 7
        ambientLocation = mkLocation (FileId 73) 2 18
        boundOccurrenceLocation = mkLocation (FileId 73) 3 14
        x = Raw.NamedVarAt binderLocation "x"
        a = Raw.NamedVarAt ambientLocation "A"
        equality left right =
            Raw.StmtFormula
                (Raw.FormulaChain
                    (Raw.ChainBase
                        (left :| [])
                        Raw.Positive
                        (Raw.Relation Nowhere Raw.EqSymbol [])
                        (right :| [])))
        separation bound =
            Raw.ExprSep
                binderLocation
                x
                bound
                (equality (Raw.ExprVar x) (Raw.ExprVar a))
        validStatement =
            Raw.SymbolicQuantified
                Nowhere
                Raw.Universally
                (a :| [])
                Raw.Unbounded
                Nothing
                (equality
                    (separation (Raw.ExprVar a))
                    (Raw.ExprVar a))
        boundOccurrence =
            Raw.NamedVarAt boundOccurrenceLocation "x"
        invalidStatement =
            equality
                (separation (Raw.ExprVar boundOccurrence))
                (Raw.ExprVar a)
        action
            :: Declaration.ModuleDriver Text
                ( Either
                    Exact.ExactCompileError
                    Exact.PreparedExactProposition
                , Either
                    Exact.ExactCompileError
                    Exact.PreparedExactProposition
                )
        action =
            Declaration.runProspectiveLoweringDriver do
                valid <- Exact.prepareExactProposition
                    Exact.emptyExactBinderContext
                    validStatement
                invalid <- Exact.prepareExactProposition
                    Exact.emptyExactBinderContext
                    invalidStatement
                pure (valid, invalid)
    outcome <- runDriver fixture action
    case outcome of
        Declaration.DriverSucceeded
                (Right prepared, Left failure) _interface _prefix _closure -> do
            assertEqual
                "separation comprehension core"
                (Core.CForall Core.TySet
                    (Core.CEq Core.TySet
                        (Core.CApp
                            (Core.CApp
                                (Core.CIntrinsic Core.Sep)
                                (Core.CBound 0))
                            (Core.CLam Core.TySet
                                (Core.CEq Core.TySet
                                    (Core.CBound 0)
                                    (Core.CBound 1))))
                        (Core.CBound 0)))
                (Core.scopedCoreTerm
                    (Exact.preparedExactPropositionCore prepared))
            assertEqual
                "separation proposition type"
                Core.TyProp
                (Core.scopedCoreType
                    (Exact.preparedExactPropositionCore prepared))
            assertEqual
                "the separation binder is unavailable in its bound"
                (Exact.ExactFreeVariable
                    boundOccurrenceLocation
                    boundOccurrence)
                failure
        Declaration.DriverSucceeded result _interface _prefix _closure ->
            case result of
                (Left validFailure, _) ->
                    assertFailure
                        ("valid separation failed: "
                            <> Text.unpack
                                (Exact.renderExactCompileError validFailure))
                (_, Right{}) ->
                    assertFailure "invalid separation was accepted"
        Declaration.DriverFailed failure _prefix ->
            assertFailure ("separation exact driver failed: " <> show failure)
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure ("separation exact driver did not seal: " <> show failure)

lowersExactReplacementTelescopes :: Assertion
lowersExactReplacementTelescopes = do
    fixture <- makeNamedFixture "exact-replacement-telescope"
    let location = mkLocation (FileId 74) 2 1
        futureOccurrenceLocation = mkLocation (FileId 74) 7 19
        a = Raw.NamedVarAt location "A"
        x = Raw.NamedVarAt location "x"
        y = Raw.NamedVarAt location "y"
        futureY = Raw.NamedVarAt futureOccurrenceLocation "y"
        equality left right =
            Raw.StmtFormula
                (Raw.FormulaChain
                    (Raw.ChainBase
                        (left :| [])
                        Raw.Positive
                        (Raw.Relation Nowhere Raw.EqSymbol [])
                        (right :| [])))
        replacement firstDomain =
            Raw.ExprReplace
                location
                (Raw.ExprVar y)
                ( (x, firstDomain) :|
                    [(y, Raw.ExprVar x)]
                )
                (Just (equality (Raw.ExprVar x) (Raw.ExprVar y)))
        validStatement =
            Raw.SymbolicQuantified
                Nowhere
                Raw.Universally
                (a :| [])
                Raw.Unbounded
                Nothing
                (equality
                    (replacement (Raw.ExprVar a))
                    (Raw.ExprVar a))
        invalidStatement =
            equality
                (replacement (Raw.ExprVar futureY))
                (Raw.ExprInteger Nowhere 0)
        predicateReplacementLocation = mkLocation (FileId 74) 9 3
        predicateReplacementStatement =
            equality
                (Raw.ExprReplacePred
                    predicateReplacementLocation
                    y
                    x
                    (Raw.ExprInteger Nowhere 0)
                    (equality (Raw.ExprVar x) (Raw.ExprVar y)))
                (Raw.ExprInteger Nowhere 0)
        app1 intrinsic argument =
            Core.CApp (Core.CIntrinsic intrinsic) argument
        app2 intrinsic first second =
            Core.CApp (app1 intrinsic first) second
        expected =
            Core.CForall Core.TySet $
                Core.CEq Core.TySet
                    (app1 Core.FamilyUnion $
                        app2 Core.Repl (Core.CBound 0) $
                            Core.CLam Core.TySet $
                                app2 Core.Repl
                                    (app2 Core.Sep
                                        (Core.CBound 0)
                                        (Core.CLam Core.TySet $
                                            Core.CEq Core.TySet
                                                (Core.CBound 1)
                                                (Core.CBound 0)))
                                    (Core.CLam Core.TySet
                                        (Core.CBound 0)))
                    (Core.CBound 0)
        action
            :: Declaration.ModuleDriver Text
                ( Either
                    Exact.ExactCompileError
                    Exact.PreparedExactProposition
                , Either
                    Exact.ExactCompileError
                    Exact.PreparedExactProposition
                , Either
                    Exact.ExactCompileError
                    Exact.PreparedExactProposition
                )
        action =
            Declaration.runProspectiveLoweringDriver do
                valid <- Exact.prepareExactProposition
                    Exact.emptyExactBinderContext
                    validStatement
                invalid <- Exact.prepareExactProposition
                    Exact.emptyExactBinderContext
                    invalidStatement
                predicateReplacement <- Exact.prepareExactProposition
                    Exact.emptyExactBinderContext
                    predicateReplacementStatement
                pure (valid, invalid, predicateReplacement)
    runDriver fixture action >>= \case
        Declaration.DriverSucceeded
                ( Right prepared
                    , Left failure
                    , Left predicateReplacementFailure
                    ) _interface _prefix _closure -> do
            assertEqual
                "dependent replacement core"
                expected
                (Core.scopedCoreTerm
                    (Exact.preparedExactPropositionCore prepared))
            assertEqual
                "future replacement binder location"
                (Exact.ExactFreeVariable futureOccurrenceLocation futureY)
                failure
            assertEqual
                "predicate replacement remains unsupported at its location"
                (Exact.ExactUnsupportedDeclarationBody
                    predicateReplacementLocation)
                predicateReplacementFailure
        Declaration.DriverSucceeded
                (Left validFailure, _, _) _interface _prefix _closure ->
            assertFailure
                ("valid replacement failed: "
                    <> Text.unpack
                        (Exact.renderExactCompileError validFailure))
        Declaration.DriverSucceeded
                (_, Right{}, _) _interface _prefix _closure ->
            assertFailure "invalid replacement was accepted"
        Declaration.DriverSucceeded
                (_, _, Right{}) _interface _prefix _closure ->
            assertFailure "predicate replacement was accepted"
        Declaration.DriverFailed failure _prefix ->
            assertFailure
                ("replacement driver failed: " <> show failure)
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure
                ("replacement driver did not seal: " <> show failure)

lowersExactFiniteSets :: Assertion
lowersExactFiniteSets = do
    fixture <- makeNamedFixture "exact-finite-set"
    let location = mkLocation (FileId 75) 2 1
        a = Raw.NamedVarAt location "a"
        b = Raw.NamedVarAt location "b"
        equality left right =
            Raw.StmtFormula
                (Raw.FormulaChain
                    (Raw.ChainBase
                        (left :| [])
                        Raw.Positive
                        (Raw.Relation Nowhere Raw.EqSymbol [])
                        (right :| [])))
        statement =
            Raw.SymbolicQuantified
                Nowhere
                Raw.Universally
                (a :| [b])
                Raw.Unbounded
                Nothing
                (equality
                    (Raw.ExprFiniteSet
                        location
                        (Raw.ExprVar a :| [Raw.ExprVar b]))
                    (Raw.ExprVar a))
        app1 intrinsic argument =
            Core.CApp (Core.CIntrinsic intrinsic) argument
        app2 intrinsic first second =
            Core.CApp (app1 intrinsic first) second
        insert element rest =
            app1 Core.FamilyUnion
                (app2 Core.PairSet
                    (app2 Core.PairSet element element)
                    rest)
        expected =
            Core.CForall Core.TySet
                (Core.CForall Core.TySet
                    (Core.CEq Core.TySet
                        (insert
                            (Core.CBound 1)
                            (insert
                                (Core.CBound 0)
                                (Core.CIntrinsic Core.Empty)))
                        (Core.CBound 1)))
        action
            :: Declaration.ModuleDriver Text
                (Either
                    Exact.ExactCompileError
                    Exact.PreparedExactProposition)
        action =
            Declaration.runProspectiveLoweringDriver
                (Exact.prepareExactProposition
                    Exact.emptyExactBinderContext
                    statement)
    runDriver fixture action >>= \case
        Declaration.DriverSucceeded
                (Right prepared) _interface _prefix _closure ->
            assertEqual
                "source-order finite-set core"
                expected
                (Core.scopedCoreTerm
                    (Exact.preparedExactPropositionCore prepared))
        Declaration.DriverSucceeded
                (Left failure) _interface _prefix _closure ->
            assertFailure
                ("valid finite set failed: "
                    <> Text.unpack
                        (Exact.renderExactCompileError failure))
        Declaration.DriverFailed failure _prefix ->
            assertFailure
                ("finite-set driver failed: " <> show failure)
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure
                ("finite-set driver did not seal: " <> show failure)

lowersExactOrdinaryDeclarations :: Assertion
lowersExactOrdinaryDeclarations = do
    fixture <- makeNamedFixture "exact-lowering"
    level <- expectRight (Syntax.mixfixLevel 2)
    let makeSymbol command marker =
            Raw.mkMixfixItem
                [ Just (Raw.Command command)
                , Just Raw.InvisibleBraceL
                , Nothing
                , Just Raw.InvisibleBraceR
                ]
                (Raw.Marker marker)
                Raw.NonAssoc
        opaqueSymbol = makeSymbol "phasefiveopaque" "opaque-label"
        aliasSymbol = makeSymbol "phasefivealias" "alias-label"
        definitionSymbol = makeSymbol "phasefivedef" "definition-label"
        entry symbol =
            Syntax.CanonicalExpressionFunction
                (Raw.mixfixPattern symbol)
                (Raw.mixfixMarker symbol)
                (Syntax.Fixity Raw.NonAssoc level)
        parameter = Raw.NamedVar "x"
        exactSet =
            Raw.NounPhrase
                []
                (Raw.Noun Nowhere Lexicon.builtinSetNoun [])
                Nothing
                []
                Nothing
        signature =
            Raw.BlockSig
                Nowhere Nothing (Raw.Marker "opaque-declaration") []
                (Raw.SignatureSymbolic
                    (Raw.SymbolPattern opaqueSymbol [parameter])
                    exactSet)
        application symbol =
            Raw.ExprOp Nowhere symbol [Raw.ExprVar parameter]
        abbreviation =
            Raw.BlockAbbr
                Nowhere Nothing (Raw.Marker "alias-declaration")
                (Raw.AbbreviationEq
                    (Raw.SymbolPattern aliasSymbol [parameter])
                    (application opaqueSymbol))
        definition =
            Raw.BlockDefn
                Nowhere Nothing (Raw.Marker "definition-declaration")
                (Raw.DefnOp
                    (Raw.SymbolPattern definitionSymbol [parameter])
                    (application aliasSymbol))
        compile block lexicalEntry = do
            Declaration.runProspectiveLoweringDriver
                (Exact.prepareExactDeclaration block [lexicalEntry]) >>= \case
                Left failure ->
                    Declaration.failModuleDriver
                        (Exact.renderExactCompileError failure)
                Right prepared -> pure prepared
        admit prepared = do
            lowered <-
                Declaration.runProspectiveLoweringDriver
                    (Exact.lowerPreparedExactBinding prepared)
            checked <-
                either Declaration.failDeclarationDriver pure lowered
            void
                (Declaration.admitCheckedDeclaration
                    checked
                    Exact.authorizeCheckedExactBinding)
    outcome <- runFixtureDriver fixture [] do
        preparedSignature <-
            compile signature (entry opaqueSymbol)
        admit preparedSignature
        preparedAbbreviation <-
            compile abbreviation (entry aliasSymbol)
        admit preparedAbbreviation
        preparedDefinition <-
            compile definition (entry definitionSymbol)
        admit preparedDefinition
        pure
            ( preparedSignature
            , preparedAbbreviation
            , preparedDefinition
            )
    case outcome of
        Declaration.DriverSucceeded
                (preparedSignature, preparedAbbreviation, preparedDefinition)
                interface prefix _closure -> do
            assertEqual "three committed declarations"
                3
                (length (Semantic.semanticInterfaceDeclarations interface))
            assertEqual "three committed batches"
                3
                (length (Declaration.pendingModulePrefixBatches prefix))
            assertEqual "opaque signature family"
                Identity.OpaqueObject
                (Identity.objectIdFamily
                    (Exact.preparedExactObjectId preparedSignature))
            assertEqual "transparent abbreviation family"
                Identity.TransparentObject
                (Identity.objectIdFamily
                    (Exact.preparedExactObjectId preparedAbbreviation))
            assertEqual "transparent definition family"
                Identity.TransparentObject
                (Identity.objectIdFamily
                    (Exact.preparedExactObjectId preparedDefinition))
            assertEqual "expanded definition coalesces with abbreviation"
                (Exact.preparedExactObjectId preparedAbbreviation)
                (Exact.preparedExactObjectId preparedDefinition)
            case Exact.preparedExactObject preparedAbbreviation of
                Just object ->
                    case Identity.assertedObjectContent object of
                        Identity.TransparentObjectContent
                                _theory coreType body -> do
                            assertEqual "definition type"
                                (Core.TyArrow Core.TySet Core.TySet)
                                coreType
                            assertEqual "expanded body retains opaque seed"
                                (Core.CLam Core.TySet
                                    (Core.CApp
                                        (Core.CGlobal
                                            (Exact.preparedExactObjectId
                                                preparedSignature))
                                        (Core.CBound 0)))
                                body
                        content ->
                            assertFailure
                                ("unexpected definition content: " <> show content)
                Nothing ->
                    assertFailure "new abbreviation object was not prepared"
            assertEqual "coalesced definition adds no object"
                Nothing
                (Exact.preparedExactObject preparedDefinition)
            case reverse (Declaration.pendingModulePrefixBatches prefix) of
                definitionBatch : _ -> do
                    case Declaration.committedBatchDeclarationValidation
                            definitionBatch of
                        Just record ->
                            case Semantic.declarationValidationRecordCertificates
                                    record of
                                [certificate] -> do
                                    assertEqual "definition authority"
                                        (Authority.CheckedKernelConstruction
                                            (Authority.CheckedDefinitionEquation
                                                (Exact.preparedExactObjectId
                                                    preparedDefinition)))
                                        (Authority.validationDirectAuthorization
                                            certificate)
                                    assertEqual "definition authority is clean"
                                        Authority.cleanAuthoritySafety
                                        (Authority.factAuthoritySafety
                                            (Authority.validationTarget
                                                certificate))
                                certificates ->
                                    assertFailure
                                        ("unexpected definition certificate count: "
                                            <> show (length certificates))
                        Nothing ->
                            assertFailure "definition has no declaration validation"
                [] -> assertFailure "definition batch is absent"
        Declaration.DriverFailed failure _prefix ->
            assertFailure ("exact lowering failed: " <> show failure)
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure ("exact lowering did not seal: " <> show failure)

    let theory = Identity.theoryId (fixtureFoundation fixture)
        mismatchBody = Core.COpaqueInteger 0
        mismatchType = Core.TySet
        mismatchId =
            Identity.transparentObjectId theory mismatchType mismatchBody
        mismatchObject =
            Identity.assertedObject
                mismatchId
                (Identity.TransparentObjectContent
                    theory mismatchType mismatchBody)
    let mismatchAction
            :: Declaration.ModuleDriver Text
                ((), Declaration.CommittedDeclarationBatch)
        mismatchAction =
            Declaration.commitCompiledDeclaration
                (Semantic.declarationSyntaxId
                    "mismatched-definition-equation") do
                    Declaration.addDeclarationObject mismatchObject
                    candidate <- Declaration.reserveCandidate
                        (factSpec fixture "not-a-definition-equation")
                    Declaration.authorizeCompiledDeclaration
                        (Declaration.authorizeDefinitionEquationCandidate
                            mismatchId
                            candidate)
    mismatch <- runDriver fixture mismatchAction
    case mismatch of
        Declaration.DriverFailed
                (Declaration.DriverDeclarationFailed
                    Declaration.DefinitionEquationCandidateMismatch)
                prefix ->
            assertEqual "mismatched equation publishes no batch"
                0
                (length (Declaration.pendingModulePrefixBatches prefix))
        Declaration.DriverFailed failure _prefix ->
            assertFailure
                ("unexpected mismatched-equation failure: " <> show failure)
        Declaration.DriverSucceeded{} ->
            assertFailure "mismatched definition equation was authorized"
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure
                ("mismatched definition equation reached sealing: "
                    <> show failure)

reconstructsImportedGlobalBindings :: Assertion
reconstructsImportedGlobalBindings = do
    producerFixture <- makeNamedFixture "global-producer"
    consumerFixture <- makeNamedFixture "global-consumer"
    conflictFixture <- makeNamedFixture "global-conflict"
    rootFixture <- makeNamedFixture "global-root"
    let key =
            Semantic.SemanticExpressionFunction
                (Raw.TokenCons (Raw.Command "phasefive") Raw.End)
        asserted = opaqueFixtureObject producerFixture
        target = Identity.assertedObjectId asserted
        publishWith targetMode fixture object = do
            (batch, sealed) <- sealFixture fixture [] do
                (_value, committed) <-
                    Declaration.commitCompiledDeclaration
                        (Semantic.declarationSyntaxId "global-binding") do
                            Declaration.addDeclarationObject object
                            Declaration.stageSemanticGlobalBinding
                                key
                                (targetMode
                                    (Identity.assertedObjectId object))
                            Declaration.authorizeCompiledDeclaration (pure ())
                pure committed
            pure (batch, sealed)
    (producerBatch, freshProducer) <-
        publishWith Semantic.GlobalReference producerFixture asserted
    let FixtureSealed producerInterface _freshEvidence = freshProducer
        objects = Declaration.committedBatchObjects producerBatch
    cachedEvidence <- expectRight
        (Declaration.validateImportedModuleEvidence
            (Identity.theoryId
                (fixtureFoundation producerFixture))
            []
            producerInterface
            objects
            [])
    let cachedProducer = FixtureSealed producerInterface cachedEvidence
        resolveThrough label parent = do
            outcome <- runFixtureDriver consumerFixture [parent] do
                fst <$> Declaration.commitCompiledDeclaration
                    (Semantic.declarationSyntaxId
                        (TextEncoding.encodeUtf8 (Text.pack label))) do
                        found <- Declaration.resolveVisibleGlobal key
                        Declaration.authorizeCompiledDeclaration (pure ())
                        pure found
            case outcome of
                Declaration.DriverSucceeded found _interface _prefix _closure ->
                    assertEqual label
                        (Just
                            ( Semantic.GlobalReference target
                            , Core.TySet
                            ))
                        found
                Declaration.DriverFailed failure _prefix ->
                    assertFailure
                        ("global binding consumer failed: " <> show failure)
                Declaration.DriverSealFailed failure _prefix ->
                    assertFailure
                        ("global binding consumer did not seal: " <> show failure)
    resolveThrough "fresh-global-binding" freshProducer
    resolveThrough "cached-global-binding" cachedProducer

    missingEnvironment <- expectRight
        (Semantic.semanticEnvironmentDelta
            [Semantic.semanticGlobalBinding
                key
                (Semantic.GlobalReference target)])
    missingDelta <- expectRight
        (Semantic.declarationInterfaceDelta
            (Semantic.declarationSlot
                (fixtureOwner producerFixture)
                (localDeclarationOrdinal 0))
            []
            []
            []
            []
            missingEnvironment)
    missingInterface <- expectRight
        (Semantic.semanticInterface
            (fixtureOwner producerFixture)
            []
            [missingDelta])
    case Declaration.validateImportedModuleEvidence
            (Identity.theoryId
                (fixtureFoundation producerFixture))
            []
            missingInterface
            []
            [] of
        Left (Declaration.ImportedGlobalTargetInvalid
                actualKey actualTarget
                (Semantic.SemanticGlobalTargetMissing missingTarget)) -> do
            assertEqual "missing target key" key actualKey
            assertEqual "missing target mode"
                (Semantic.GlobalReference target)
                actualTarget
            assertEqual "missing target object" target missingTarget
        Left failure ->
            assertFailure
                ("unexpected missing-target failure: " <> show failure)
        Right _evidence ->
            assertFailure "cached evidence accepted a missing target object"

    expansionEnvironment <- expectRight
        (Semantic.semanticEnvironmentDelta
            [Semantic.semanticGlobalBinding
                key
                (Semantic.TransparentExpansion target)])
    expansionDelta <- expectRight
        (Semantic.declarationInterfaceDelta
            (Semantic.declarationSlot
                (fixtureOwner producerFixture)
                (localDeclarationOrdinal 0))
            [] [] [target] [] expansionEnvironment)
    expansionInterface <- expectRight
        (Semantic.semanticInterface
            (fixtureOwner producerFixture) [] [expansionDelta])
    case Declaration.validateImportedModuleEvidence
            (Identity.theoryId
                (fixtureFoundation producerFixture))
            []
            expansionInterface
            [asserted]
            [] of
        Left (Declaration.ImportedGlobalTargetInvalid
                actualKey actualTarget
                (Semantic.SemanticGlobalExpansionNotTransparent
                    invalidTarget)) -> do
            assertEqual "nontransparent target key" key actualKey
            assertEqual "nontransparent target mode"
                (Semantic.TransparentExpansion target)
                actualTarget
            assertEqual "nontransparent target object" target invalidTarget
        Left failure ->
            assertFailure
                ("unexpected nontransparent-target failure: "
                    <> show failure)
        Right _evidence ->
            assertFailure "cached evidence accepted a nontransparent expansion"

    let intrinsicTarget =
            Identity.intrinsicObjectId
                (Identity.theoryId
                    (fixtureFoundation producerFixture))
                Core.Empty
                Core.TySet
        intrinsicObject =
            Identity.assertedObject
                intrinsicTarget
                (Identity.IntrinsicObjectContent
                    (Identity.theoryId
                        (fixtureFoundation producerFixture))
                    Core.Empty
                    Core.TySet)
    intrinsicFailure <- runFixtureDriver producerFixture [] do
        Declaration.commitCompiledDeclaration
            (Semantic.declarationSyntaxId "intrinsic-global-binding") do
                Declaration.addDeclarationObject intrinsicObject
                Declaration.stageSemanticGlobalBinding
                    key
                    (Semantic.GlobalReference intrinsicTarget)
                Declaration.authorizeCompiledDeclaration (pure ())
    case intrinsicFailure of
        Declaration.DriverFailed
                (Declaration.DriverDeclarationFailed
                    (Declaration.DeclarationGlobalTargetInvalid
                        actualKey actualTarget
                        (Semantic.SemanticGlobalTargetIsIntrinsic
                            invalidTarget)))
                _prefix -> do
            assertEqual "intrinsic target key" key actualKey
            assertEqual "intrinsic target mode"
                (Semantic.GlobalReference intrinsicTarget)
                actualTarget
            assertEqual "intrinsic target object"
                intrinsicTarget invalidTarget
        other ->
            assertFailure
                (case other of
                    Declaration.DriverSucceeded{} ->
                        "ordinary binding accepted an intrinsic target"
                    Declaration.DriverFailed failure _prefix ->
                        "unexpected intrinsic-target failure: " <> show failure
                    Declaration.DriverSealFailed failure _prefix ->
                        "intrinsic target reached sealing: " <> show failure)

    conflictObject <- pure (opaqueFixtureObject conflictFixture)
    (_conflictBatch, conflicting) <-
        publishWith Semantic.GlobalReference conflictFixture conflictObject
    collision <- runFixtureDriver rootFixture
        [freshProducer, conflicting]
        (pure ())
    case collision of
        Declaration.DriverFailed
                (Declaration.DriverDeclarationFailed
                    (Declaration.ImportedGlobalCollision
                        actualKey firstTarget secondTarget))
                _prefix -> do
            assertEqual "colliding global key" key actualKey
            assertEqual "first imported target"
                (Semantic.GlobalReference target)
                firstTarget
            assertEqual "second imported target"
                (Semantic.GlobalReference
                    (Identity.assertedObjectId conflictObject))
                secondTarget
        Declaration.DriverFailed failure _prefix ->
            assertFailure
                ("unexpected imported collision: " <> show failure)
        Declaration.DriverSucceeded{} ->
            assertFailure "unequal imported bindings did not collide"
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure
                ("global collision reached sealing: " <> show failure)

    let theory = Identity.theoryId (fixtureFoundation producerFixture)
        transparentBody = Core.COpaqueInteger 0
        transparentTarget =
            Identity.transparentObjectId
                theory Core.TySet transparentBody
        transparentObject =
            Identity.assertedObject
                transparentTarget
                (Identity.TransparentObjectContent
                    theory Core.TySet transparentBody)
    (_referenceBatch, referenceProducer) <-
        publishWith
            Semantic.GlobalReference
            producerFixture
            transparentObject
    (_expansionBatch, expansionProducer) <-
        publishWith
            Semantic.TransparentExpansion
            conflictFixture
            transparentObject
    modeCollision <- runFixtureDriver rootFixture
        [referenceProducer, expansionProducer]
        (pure ())
    case modeCollision of
        Declaration.DriverFailed
                (Declaration.DriverDeclarationFailed
                    (Declaration.ImportedGlobalCollision
                        actualKey firstTarget secondTarget))
                _prefix -> do
            assertEqual "mode collision key" key actualKey
            assertEqual "reference target"
                (Semantic.GlobalReference transparentTarget)
                firstTarget
            assertEqual "expansion target"
                (Semantic.TransparentExpansion transparentTarget)
                secondTarget
        other ->
            assertFailure
                (case other of
                    Declaration.DriverSucceeded{} ->
                        "different global target modes did not collide"
                    Declaration.DriverFailed failure _prefix ->
                        "unexpected mode-collision failure: " <> show failure
                    Declaration.DriverSealFailed failure _prefix ->
                        "mode collision reached sealing: " <> show failure)

data FixtureSealed = FixtureSealed
    !Semantic.SemanticInterface
    !Declaration.ImportedModuleEvidence

foldsTransitiveAndDiamondEvidence :: Assertion
foldsTransitiveAndDiamondEvidence = do
    baseFixture <- makeNamedFixture "base"
    middleFixture <- makeNamedFixture "middle"
    transitiveFixture <- makeNamedFixture "transitive"
    leftFixture <- makeNamedFixture "left"
    rightFixture <- makeNamedFixture "right"
    diamondFixture <- makeNamedFixture "diamond"
    conflictLeftFixture <- makeNamedFixture "conflict-left"
    conflictRightFixture <- makeNamedFixture "conflict-right"
    conflictRootFixture <- makeNamedFixture "conflict-root"

    (base, baseFingerprint) <-
        sealFactFixture baseFixture [] "transitive-shared"
    middle <- snd <$> sealFixture middleFixture [base] (pure ())
    transitive <- sealUsingImportedFact
        transitiveFixture [middle] baseFingerprint
    assertLocalFactOrdinalZero "transitive importer" transitive

    left <- snd <$> sealFixture leftFixture [base] (pure ())
    right <- snd <$> sealFixture rightFixture [base] (pure ())
    diamond <- sealUsingImportedFact
        diamondFixture [left, right] baseFingerprint
    assertLocalFactOrdinalZero "diamond importer" diamond

    (conflictLeft, leftFingerprint) <-
        sealFactFixture conflictLeftFixture [] "diamond-conflict"
    (conflictRight, rightFingerprint) <-
        sealFactFixture conflictRightFixture [] "diamond-conflict"
    conflict <- runFixtureDriver
        conflictRootFixture
        [conflictLeft, conflictRight]
        (pure ())
    case conflict of
        Declaration.DriverFailed
                (Declaration.DriverDeclarationFailed
                    (Declaration.ImportedAliasCollision
                        alias
                        (Declaration.ImportedAliasOrigin
                            _leftSlot firstTarget)
                        (Declaration.ImportedAliasOrigin
                            _rightSlot secondTarget)))
                _prefix -> do
            assertEqual "conflicting alias"
                (Semantic.semanticName "diamond-conflict")
                alias
            assertEqual "first alias origin"
                leftFingerprint
                firstTarget
            assertEqual "second alias origin"
                rightFingerprint
                secondTarget
        _ ->
            assertFailure "conflicting diamond alias was not rejected"
  where
    sealUsingImportedFact fixture parents fingerprint = do
        (batch, _sealed) <- sealFixture fixture parents do
            (_value, committed) <- Declaration.commitProofDeclaration
                (Semantic.proofSyntaxId "use-transitive-import") do
                    candidate <- Declaration.reserveCandidate
                        (factSpec fixture "local-after-import")
                    Declaration.authorizeOmittedCandidate candidate do
                        void (Declaration.useAuthorizedFact fingerprint)
                        Declaration.recordOmittedUse
            pure committed
        pure batch

    assertLocalFactOrdinalZero label batch =
        case Semantic.declarationDeltaFacts
                (Declaration.committedBatchDelta batch) of
            [occurrence] ->
                assertEqual label
                    (localFactOrdinal 0)
                    (Semantic.factSlotOrdinal
                        (Semantic.semanticFactSlot occurrence))
            facts ->
                assertFailure
                    (label <> ": unexpected fact count "
                        <> show (length facts))

sealFactFixture
    :: Fixture
    -> [FixtureSealed]
    -> Text
    -> IO
        ( FixtureSealed
        , Semantic.SemanticFactOccurrenceFingerprint
        )
sealFactFixture fixture parents alias = do
    (batch, sealed) <- sealFixture fixture parents do
        (_value, committed) <- Declaration.commitProofDeclaration
            (Semantic.proofSyntaxId
                (TextEncoding.encodeUtf8 alias)) do
                candidate <- Declaration.reserveCandidate
                    (factSpec fixture alias)
                Declaration.authorizeSourceAxiomCandidate candidate
        pure committed
    case Semantic.declarationDeltaFacts
            (Declaration.committedBatchDelta batch) of
        [occurrence] ->
            pure
                ( sealed
                , Semantic.semanticFactFingerprint occurrence
                )
        facts ->
            assertFailure
                ("unexpected sealed fact count: " <> show (length facts))
                >> fail "unreachable"

sealFixture
    :: Fixture
    -> [FixtureSealed]
    -> Declaration.ModuleDriver Text value
    -> IO (value, FixtureSealed)
sealFixture fixture parents action = do
    outcome <- runFixtureDriver fixture parents action
    case outcome of
        Declaration.DriverSucceeded value interface prefix _closure ->
            pure
                ( value
                , FixtureSealed
                    interface
                    (Declaration.freshImportedModuleEvidence
                        [ evidence
                        | FixtureSealed _interface evidence <- parents
                        ]
                        interface
                        prefix)
                )
        Declaration.DriverFailed failure _prefix ->
            assertFailure ("fixture failed: " <> show failure)
                >> fail "unreachable"
        Declaration.DriverSealFailed failure _prefix ->
            assertFailure ("fixture did not seal: " <> show failure)
                >> fail "unreachable"

runFixtureDriver
    :: Fixture
    -> [FixtureSealed]
    -> Declaration.ModuleDriver Text value
    -> IO (Declaration.DriverResult Text value)
runFixtureDriver fixture parents action = do
    result <- Declaration.runModuleDriver
        (fixtureFoundation fixture)
        (fixtureOwner fixture)
        [ Semantic.semanticInterfaceAssertedId interface
        | FixtureSealed interface _evidence <- parents
        ]
        unavailableVampireResolver
        Declaration.FreshValidation
        do
            traverse_
                (\(FixtureSealed _interface evidence) ->
                    Declaration.importSealedModuleDriver evidence)
                parents
            action
    expectRight result

requireSingleOccurrence
    :: Declaration.CommittedDeclarationBatch
    -> Declaration.ModuleDriver
        Declaration.DeclarationError
        Semantic.SemanticFactOccurrence
requireSingleOccurrence batch =
    case Semantic.declarationDeltaFacts
            (Declaration.committedBatchDelta batch) of
        [occurrence] ->
            pure occurrence
        _ ->
            Declaration.failModuleDriver
                Declaration.ProofDeclarationMustProduceOneFact

expectRight :: Show error => Either error value -> IO value
expectRight = \case
    Left err ->
        assertFailure (show err) >> fail "unreachable"
    Right value ->
        pure value

expectRightIO :: Show error => IO (Either error value) -> IO value
expectRightIO action =
    action >>= expectRight

withOpenedStore
    :: Fixture
    -> FilePath
    -> (Store.Store -> IO value)
    -> IO value
withOpenedStore fixture root action =
    bracket
        (expectRightIO
            (Store.openStore
                (root Posix.</> "store.sqlite")
                (Identity.theoryId (fixtureFoundation fixture))))
        (Store.closeStore . snd)
        (action . snd)

withTemporaryDirectory :: String -> (FilePath -> IO a) -> IO a
withTemporaryDirectory template =
    bracket create Directory.removePathForcibly
  where
    create = do
        root <- Directory.getTemporaryDirectory
        (path, handle) <- openTempFile root template
        hClose handle
        Directory.removeFile path
        Directory.createDirectory path
        pure path